diff options
Diffstat (limited to 'widgets')
58 files changed, 16050 insertions, 8785 deletions
diff --git a/widgets/BandHopping.cpp b/widgets/BandHopping.cpp new file mode 100644 index 00000000..867511d7 --- /dev/null +++ b/widgets/BandHopping.cpp @@ -0,0 +1,18 @@ +#include "widgets/BandHopping.hpp" + +int next_band_hop_index (std::vector<bool> const& selected, int start_index) +{ + auto const entry_count = static_cast<int> (selected.size ()); + if (0 == entry_count) return -1; + + auto normalized_start = start_index % entry_count; + if (normalized_start < 0) normalized_start += entry_count; + + for (int offset = 0; offset < entry_count; ++offset) + { + auto const index = (normalized_start + offset) % entry_count; + if (selected[index]) return index; + } + + return -1; +} diff --git a/widgets/BandHopping.hpp b/widgets/BandHopping.hpp new file mode 100644 index 00000000..f8a43bbe --- /dev/null +++ b/widgets/BandHopping.hpp @@ -0,0 +1,8 @@ +#ifndef BAND_HOPPING_HPP +#define BAND_HOPPING_HPP + +#include <vector> + +int next_band_hop_index (std::vector<bool> const& selected, int start_index); + +#endif diff --git a/widgets/CompactButtonSize.hpp b/widgets/CompactButtonSize.hpp new file mode 100644 index 00000000..d9455456 --- /dev/null +++ b/widgets/CompactButtonSize.hpp @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#ifndef COMPACT_BUTTON_SIZE_HPP +#define COMPACT_BUTTON_SIZE_HPP + +#include <QPushButton> +#include <QStyle> +#include <QStyleOptionButton> + +// Measure the label and native decoration without the style's recommended +// dialog-button width (75 logical pixels on Windows). Painting stays native. +inline QSize compactButtonSize (QPushButton const * button) +{ + QStyleOptionButton option; + option.initFrom (button); + if (button->autoDefault ()) option.features |= QStyleOptionButton::AutoDefaultButton; + auto contents = button->fontMetrics ().size (Qt::TextShowMnemonic, button->text ()); + // The text is already measured above. An empty option text avoids the + // Windows style's dialog-width floor without discarding its frame margins. + return button->style ()->sizeFromContents (QStyle::CT_PushButton, &option, contents, button); +} + +#endif diff --git a/widgets/CurrentPageHeightStackedWidget.hpp b/widgets/CurrentPageHeightStackedWidget.hpp new file mode 100644 index 00000000..e205e047 --- /dev/null +++ b/widgets/CurrentPageHeightStackedWidget.hpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#ifndef CURRENT_PAGE_HEIGHT_STACKED_WIDGET_HPP +#define CURRENT_PAGE_HEIGHT_STACKED_WIDGET_HPP + +#include <QStackedWidget> + +class CurrentPageHeightStackedWidget final : public QStackedWidget +{ +public: + explicit CurrentPageHeightStackedWidget (QWidget * parent = nullptr) + : QStackedWidget {parent} + { + connect (this, &QStackedWidget::currentChanged, this, [this] {updateGeometry ();}); + } + + QSize sizeHint () const override + { + return withCurrentPageHeight (QStackedWidget::sizeHint (), false); + } + + QSize minimumSizeHint () const override + { + return withCurrentPageHeight (QStackedWidget::minimumSizeHint (), true); + } + +private: + QSize withCurrentPageHeight (QSize hint, bool minimum) const + { + if (auto * page = currentWidget ()) + { + auto const pageHint = minimum ? page->minimumSizeHint () : page->sizeHint (); + if (pageHint.isValid ()) hint.setHeight (pageHint.height ()); + } + return hint; + } +}; + +#endif diff --git a/widgets/DecodeHighlightingListView.cpp b/widgets/DecodeHighlightingListView.cpp index cfb14fc5..2997017a 100644 --- a/widgets/DecodeHighlightingListView.cpp +++ b/widgets/DecodeHighlightingListView.cpp @@ -15,6 +15,10 @@ DecodeHighlightingListView::DecodeHighlightingListView (QWidget * parent) addAction (fg_colour_action); connect (fg_colour_action, &QAction::triggered, [this] (bool /*checked*/) { auto const& index = currentIndex (); + if (!model () || !index.isValid ()) + { + return; + } auto colour = QColorDialog::getColor (model ()->data (index, Qt::ForegroundRole).value<QBrush> ().color () , this , tr ("Choose %1 Foreground Color") @@ -28,13 +32,21 @@ DecodeHighlightingListView::DecodeHighlightingListView (QWidget * parent) auto * unset_fg_colour_action = new QAction {tr ("&Unset foreground color"), this}; addAction (unset_fg_colour_action); connect (unset_fg_colour_action, &QAction::triggered, [this] (bool /*checked*/) { - model ()->setData (currentIndex (), QBrush {}, Qt::ForegroundRole); + auto const& index = currentIndex (); + if (model () && index.isValid ()) + { + model ()->setData (index, QBrush {}, Qt::ForegroundRole); + } }); auto * bg_colour_action = new QAction {tr ("&Background color ..."), this}; addAction (bg_colour_action); connect (bg_colour_action, &QAction::triggered, [this] (bool /*checked*/) { auto const& index = currentIndex (); + if (!model () || !index.isValid ()) + { + return; + } auto colour = QColorDialog::getColor (model ()->data (index, Qt::BackgroundRole).value<QBrush> ().color () , this , tr ("Choose %1 Background Color") @@ -48,13 +60,21 @@ DecodeHighlightingListView::DecodeHighlightingListView (QWidget * parent) auto * unset_bg_colour_action = new QAction {tr ("U&nset background color"), this}; addAction (unset_bg_colour_action); connect (unset_bg_colour_action, &QAction::triggered, [this] (bool /*checked*/) { - model ()->setData (currentIndex (), QBrush {}, Qt::BackgroundRole); + auto const& index = currentIndex (); + if (model () && index.isValid ()) + { + model ()->setData (index, QBrush {}, Qt::BackgroundRole); + } }); auto * defaults_action = new QAction {tr ("&Reset this item to defaults"), this}; addAction (defaults_action); connect (defaults_action, &QAction::triggered, [this] (bool /*checked*/) { auto const& index = currentIndex (); + if (!model () || !index.isValid ()) + { + return; + } model ()->setData (index, model ()->data (index, DecodeHighlightingModel::EnabledDefaultRole).toBool () ? Qt::Checked : Qt::Unchecked, Qt::CheckStateRole); model ()->setData (index, model ()->data (index, DecodeHighlightingModel::ForegroundDefaultRole), Qt::ForegroundRole); model ()->setData (index, model ()->data (index, DecodeHighlightingModel::BackgroundDefaultRole), Qt::BackgroundRole); diff --git a/widgets/FrequencyDeltaLineEdit.cpp b/widgets/FrequencyDeltaLineEdit.cpp index 59ae9bc9..aeeec2a7 100644 --- a/widgets/FrequencyDeltaLineEdit.cpp +++ b/widgets/FrequencyDeltaLineEdit.cpp @@ -2,6 +2,7 @@ #include <limits> +#include <QColor> #include <QDoubleValidator> #include <QString> #include <QLocale> @@ -10,6 +11,9 @@ namespace { + double constexpr MHz_factor {1.e6}; + QColor const invalid_text_color {180, 0, 0}; + class MHzValidator : public QDoubleValidator { @@ -38,17 +42,46 @@ namespace FrequencyDeltaLineEdit::FrequencyDeltaLineEdit (QWidget * parent) : QLineEdit (parent) + , default_palette_ {palette ()} { - setValidator (new MHzValidator {static_cast<double>(std::numeric_limits<FrequencyDelta>::min ()) / 10.e6, - static_cast<double>(std::numeric_limits<FrequencyDelta>::max ()) / 10.e6, this}); + setValidator (new MHzValidator {static_cast<double>(std::numeric_limits<FrequencyDelta>::min ()) / MHz_factor, + static_cast<double>(std::numeric_limits<FrequencyDelta>::max ()) / MHz_factor, this}); + setPlaceholderText (tr ("Offset in MHz")); + connect (this, &QLineEdit::textChanged, this, [this] {update_input_feedback ();}); + update_input_feedback (); } auto FrequencyDeltaLineEdit::frequency_delta () const -> FrequencyDelta { - return Radio::frequency_delta (text (), 6); + return frequency_delta (nullptr); +} + +auto FrequencyDeltaLineEdit::frequency_delta (bool * ok) const -> FrequencyDelta +{ + if (!hasAcceptableInput ()) + { + if (ok) *ok = false; + return 0; + } + return Radio::frequency_delta (text (), 6, ok); } void FrequencyDeltaLineEdit::frequency_delta (FrequencyDelta d) { setText (Radio::frequency_MHz_string (d)); } + +void FrequencyDeltaLineEdit::update_input_feedback () +{ + auto palette = default_palette_; + if (hasAcceptableInput ()) + { + setToolTip (tr ("Frequency offset in MHz")); + } + else + { + palette.setColor (QPalette::Text, invalid_text_color); + setToolTip (tr ("Enter a frequency offset in MHz.")); + } + setPalette (palette); +} diff --git a/widgets/FrequencyDeltaLineEdit.hpp b/widgets/FrequencyDeltaLineEdit.hpp index caa00ecb..6b0aa8a9 100644 --- a/widgets/FrequencyDeltaLineEdit.hpp +++ b/widgets/FrequencyDeltaLineEdit.hpp @@ -2,6 +2,7 @@ #define FREQUENCY_DELTA_LINE_EDIT_HPP_ #include <QLineEdit> +#include <QPalette> #include "Radio.hpp" @@ -23,7 +24,13 @@ public: // Property frequency_delta implementation FrequencyDelta frequency_delta () const; + FrequencyDelta frequency_delta (bool *) const; void frequency_delta (FrequencyDelta); + +private: + void update_input_feedback (); + + QPalette default_palette_; }; #endif diff --git a/widgets/FrequencyLineEdit.cpp b/widgets/FrequencyLineEdit.cpp index 8e74c7db..9be31644 100644 --- a/widgets/FrequencyLineEdit.cpp +++ b/widgets/FrequencyLineEdit.cpp @@ -2,6 +2,7 @@ #include <limits> +#include <QColor> #include <QDoubleValidator> #include <QString> #include <QLocale> @@ -10,6 +11,10 @@ namespace { + double constexpr MHz_factor {1.e6}; + double constexpr minimum_frequency_MHz {1. / MHz_factor}; + QColor const invalid_text_color {180, 0, 0}; + class MHzValidator : public QDoubleValidator { @@ -38,16 +43,45 @@ namespace FrequencyLineEdit::FrequencyLineEdit (QWidget * parent) : QLineEdit (parent) + , default_palette_ {palette ()} { - setValidator (new MHzValidator {0., static_cast<double>(std::numeric_limits<Radio::Frequency>::max ()) / 10.e6, this}); + setValidator (new MHzValidator {minimum_frequency_MHz, static_cast<double>(std::numeric_limits<Radio::Frequency>::max ()) / MHz_factor, this}); + setPlaceholderText (tr ("Frequency in MHz")); + connect (this, &QLineEdit::textChanged, this, [this] {update_input_feedback ();}); + update_input_feedback (); } auto FrequencyLineEdit::frequency () const -> Frequency { - return Radio::frequency (text (), 6); + return frequency (nullptr); +} + +auto FrequencyLineEdit::frequency (bool * ok) const -> Frequency +{ + if (!hasAcceptableInput ()) + { + if (ok) *ok = false; + return 0; + } + return Radio::frequency (text (), 6, ok); } void FrequencyLineEdit::frequency (Frequency f) { setText (Radio::frequency_MHz_string (f)); } + +void FrequencyLineEdit::update_input_feedback () +{ + auto palette = default_palette_; + if (hasAcceptableInput ()) + { + setToolTip (tr ("Frequency in MHz")); + } + else + { + palette.setColor (QPalette::Text, invalid_text_color); + setToolTip (tr ("Enter a positive frequency in MHz.")); + } + setPalette (palette); +} diff --git a/widgets/FrequencyLineEdit.hpp b/widgets/FrequencyLineEdit.hpp index 7e535f5a..9a4dfe9d 100644 --- a/widgets/FrequencyLineEdit.hpp +++ b/widgets/FrequencyLineEdit.hpp @@ -2,6 +2,7 @@ #define FREQUENCY_LINE_EDIT_HPP_ #include <QLineEdit> +#include <QPalette> #include "Radio.hpp" @@ -23,7 +24,13 @@ public: // Property frequency implementation Frequency frequency () const; + Frequency frequency (bool *) const; void frequency (Frequency); + +private: + void update_input_feedback (); + + QPalette default_palette_; }; #endif diff --git a/widgets/JttyDraftAcceptanceTracker.hpp b/widgets/JttyDraftAcceptanceTracker.hpp new file mode 100644 index 00000000..2263831f --- /dev/null +++ b/widgets/JttyDraftAcceptanceTracker.hpp @@ -0,0 +1,56 @@ +#ifndef JTTY_DRAFT_ACCEPTANCE_TRACKER_HPP_ +#define JTTY_DRAFT_ACCEPTANCE_TRACKER_HPP_ + +#include <QHash> + +class JttyDraftAcceptanceTracker +{ +public: + void noteDraftChanged () noexcept + { + ++revision_; + } + + void trackSubmission (qint64 requestId) + { + submissions_.insert (requestId, revision_); + } + + bool hasPendingSubmissionForCurrentDraft () const + { + for (auto it = submissions_.cbegin (); it != submissions_.cend (); ++it) { + if (it.value () == revision_) { + return true; + } + } + return false; + } + + bool isPending (qint64 requestId) const + { + return submissions_.contains (requestId); + } + + bool accept (qint64 requestId) + { + auto const it = submissions_.find (requestId); + if (it == submissions_.end ()) { + return false; + } + + auto const submittedRevision = it.value (); + submissions_.erase (it); + return submittedRevision == revision_; + } + + void reject (qint64 requestId) + { + submissions_.remove (requestId); + } + +private: + quint64 revision_ {0}; + QHash<qint64, quint64> submissions_; +}; + +#endif diff --git a/widgets/JttyMessages.hpp b/widgets/JttyMessages.hpp new file mode 100644 index 00000000..2a1f4162 --- /dev/null +++ b/widgets/JttyMessages.hpp @@ -0,0 +1,950 @@ +// -*- Mode: C++ -*- +#ifndef JTTY_MESSAGES_HPP +#define JTTY_MESSAGES_HPP + +#include <algorithm> +#include <cmath> +#include <cstddef> +#include <type_traits> + +#include <QByteArray> +#include <QDateTime> +#include <QRegularExpression> +#include <QString> +#include <QStringList> +#include <QTime> +#include <QVector> + +namespace Jtty +{ + struct ParsedDecodeLine + { + int frequency {0}; + QString message; + bool valid {false}; + }; + + struct PreparedTransmitText + { + QString text; + bool substituted {false}; + bool truncated {false}; + + bool changed () const + { + return substituted || truncated; + } + }; + + enum class NativeAtomKind : qint8 + { + Call = 0, + ExchangeNumber = 1, + ExchangeLocation = 2, + ExchangePair = 3, + ExchangeNumberTime = 4, + Control = 5, + Grid4 = 6, + Text5 = 7 + }; + + enum class CallAction : qint8 + { + Cq = 0, + Call = 1, + TuCq = 2, + CallTu = 3, + CallAgn = 4, + TuNowCall = 5 + }; + + enum class ExchangeRole : qint8 + { + FieldOnly = 0, + Full = 1 + }; + + enum class NumberKind : qint8 + { + Serial = 0, + CqZone = 1, + ItuZone = 2, + Age = 3, + Power = 4, + Check = 5, + FirstLicenseYear = 6, + Generic = 7 + }; + + enum class LocationKind : qint8 + { + StateProvince = 0, + ArrlRacSection = 1, + CountryPrefix = 2, + Qth = 3, + LocalAdministrativeCode = 4 + }; + + enum class PairSchema : qint8 + { + ZoneLocation = 0, + ClassSection = 1 + }; + + enum class NativeExchangeProfile + { + // Shared with the Fortran text packer; None leaves text inference unprofiled. + None = 0, + FieldDay = 1, + RttyRoundup = 2 + }; + + struct NativeAtomDescriptor + { + qint8 kind {}; + qint8 subtype {}; + qint8 role {}; + qint8 reserved {}; + qint32 value {}; + char text[9] {}; + }; + + static_assert (std::is_standard_layout<NativeAtomDescriptor>::value, + "NativeAtomDescriptor must remain C-compatible"); + static_assert (offsetof (NativeAtomDescriptor, kind) == 0, "atom ABI mismatch"); + static_assert (offsetof (NativeAtomDescriptor, subtype) == 1, "atom ABI mismatch"); + static_assert (offsetof (NativeAtomDescriptor, role) == 2, "atom ABI mismatch"); + static_assert (offsetof (NativeAtomDescriptor, reserved) == 3, "atom ABI mismatch"); + static_assert (offsetof (NativeAtomDescriptor, value) == 4, "atom ABI mismatch"); + static_assert (offsetof (NativeAtomDescriptor, text) == 8, "atom ABI mismatch"); + static_assert (sizeof (NativeAtomDescriptor) == 20, "atom ABI mismatch"); + + enum class NativeEncodeStatus + { + Ok = 0, + InvalidDescriptor = 1, + UnknownSection = 2 + }; + + enum class NativeMacroStatus + { + Native, + LiteralFallback, + InvalidRuntime + }; + + struct NativeMacroContext + { + QString myCall; + QString hisCall; + int serialNumber {}; + NativeExchangeProfile exchangeProfile {NativeExchangeProfile::None}; + QString configuredExchange; + QString grid; + + NativeMacroContext () = default; + + NativeMacroContext (QString const& myCallValue, QString const& hisCallValue, + int serialNumberValue, + NativeExchangeProfile profile = NativeExchangeProfile::None, + QString const& exchangeValue = {}, QString const& gridValue = {}) + : myCall {myCallValue} + , hisCall {hisCallValue} + , serialNumber {serialNumberValue} + , exchangeProfile {profile} + , configuredExchange {exchangeValue} + , grid {gridValue} + { + } + }; + + struct NativeMacroCompilation + { + NativeMacroStatus status {NativeMacroStatus::LiteralFallback}; + QVector<NativeAtomDescriptor> atoms; + QString text; + QString error; + + bool isNative () const + { + return status == NativeMacroStatus::Native; + } + }; + + inline QString sourceAlphabet () + { + // Keep in sync with ALPHABET in lib/jtty/jtty_source_codec.f90. + return QStringLiteral ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ +-./?!\"#$%,&*()_'=[]{}<>|:;"); + } + + inline bool isSourceCharacter (QChar c) + { + return sourceAlphabet ().contains (c) + || (c >= QLatin1Char {'a'} && c <= QLatin1Char {'z'}); + } + + // Fixed width of a JTTY transmit frame; genjtty_ (lib/jtty/genjtty.f90) + // expects exactly this many characters. + inline constexpr int maxMessageLength = 80; + inline constexpr int maxTransmitLength = maxMessageLength; + + inline PreparedTransmitText prepareTransmitText (QString const& message) + { + PreparedTransmitText result; + int const maxLength {maxTransmitLength}; + result.truncated = message.size () > maxLength; + QString const bounded = message.left (maxLength); + result.text.reserve (bounded.size ()); + + for (QChar c : bounded) { + if (c == QChar::Null || c == QLatin1Char {'~'}) { + result.text.append (QLatin1Char {' '}); + result.substituted = true; + } else if (isSourceCharacter (c)) { + result.text.append (c); + } else { + result.text.append (QLatin1Char {'#'}); + result.substituted = true; + } + } + + return result; + } + + // A message being queued behind one still transmitting (FIFO chaining, + // see MainWindow::execute_jtty_tx) gets a leading space inserted, since + // the user is unlikely to remember (or want) to type one themselves, + // and unlikely to hit Return mid-word. Re-bounds to maxTransmitLength + // in case the message was already at prepareTransmitText's limit. + // No-op (returns message unchanged) when isChained is false. + inline QString withChainedSpacing (QString const& message, bool isChained) + { + if (!isChained) return message; + return (QLatin1Char {' '} + message).left (maxTransmitLength); + } + + // Builds the fixed-width frame passed to genjtty_. The chained leading space + // is transport-only spacing, so it belongs here rather than in the logical + // message that is logged, displayed, and checked for contest serials. + inline QString transmitFrame (QString const& message, bool isChained) + { + QString const spaced = withChainedSpacing (message, isChained); + return spaced + QString (maxTransmitLength - spaced.size (), QLatin1Char {' '}); + } + + // Number of receive samples in one complete JTTY frame: 59 symbols of 384 + // samples (lib/jtty/jtty.f90). Anything shorter is not a decodable interval. + inline constexpr qint32 jttyFrameSamples = 59 * 384; + + // m_k0 starts at this sentinel and is only replaced once fastSink has real + // audio, so it marks "nothing captured yet". + inline constexpr qint32 invalidCaptureSamples = 9999999; + + // True when k0 describes a captured JTTY receive buffer worth saving: at + // least one full frame, and not the uninitialised sentinel. + inline bool wavCaptureValid (qint32 k0) + { + return k0 > jttyFrameSamples && k0 < invalidCaptureSamples; + } + + inline QString formatSerialNumber (int serialNumber) + { + return QString {"%1"}.arg (serialNumber, 3, 10, QLatin1Char {'0'}); + } + + inline QString nativeMacroTemplate (int functionKey) + { + static QString const templates[] { + QStringLiteral ("CQ %M CQ"), + QStringLiteral ("%H %E"), + QStringLiteral ("%H TU CQ %M CQ"), + QStringLiteral ("%M"), + QStringLiteral ("%H"), + QStringLiteral ("TU NOW %Q %E"), + QStringLiteral ("%H AGN?"), + QStringLiteral ("%E") + }; + if (functionKey < 1 || functionKey > 8) return {}; + return templates[functionKey - 1]; + } + + inline QString legacyNativeMacroTemplate (int functionKey) + { + static QString const templates[] { + QStringLiteral ("CQ %M CQ"), + QStringLiteral ("%H 599 %N"), + QStringLiteral ("%H TU CQ %M CQ"), + QStringLiteral ("%M"), + QStringLiteral ("%H"), + QStringLiteral ("TU NOW %Q 599 %N"), + QStringLiteral ("%H AGN?"), + QStringLiteral ("599 %N") + }; + if (functionKey < 1 || functionKey > 8) return {}; + return templates[functionKey - 1]; + } + + inline QString nativeGridMacroTemplate (int functionKey) + { + switch (functionKey) { + case 2: return QStringLiteral ("%H %G"); + case 6: return QStringLiteral ("TU NOW %Q %G"); + case 8: return QStringLiteral ("%G"); + default: return {}; + } + } + + inline QString normalizedMacroTemplate (QString const& macroTemplate) + { + return macroTemplate.simplified ().toUpper (); + } + + inline int nativeMacroFunctionKey (QString const& macroTemplate) + { + QString const normalized = normalizedMacroTemplate (macroTemplate); + if (normalized == QStringLiteral ("599 %G")) return 8; + for (int functionKey = 1; functionKey <= 8; ++functionKey) { + QString const gridTemplate = nativeGridMacroTemplate (functionKey); + if (normalized == nativeMacroTemplate (functionKey) + || macroTemplate == legacyNativeMacroTemplate (functionKey) + || (!gridTemplate.isEmpty () && normalized == gridTemplate)) { + return functionKey; + } + } + return 0; + } + + inline bool isNativeMacroTemplate (QString const& macroTemplate) + { + return nativeMacroFunctionKey (macroTemplate) != 0; + } + + inline QString nativeExchangeFieldText (NativeMacroContext const& context) + { + QString const configured = context.configuredExchange.simplified ().toUpper (); + if (context.exchangeProfile == NativeExchangeProfile::None + || (context.exchangeProfile == NativeExchangeProfile::RttyRoundup + && (configured == QStringLiteral ("DX") || configured == QStringLiteral ("#")))) { + return formatSerialNumber (context.serialNumber); + } + return configured; + } + + inline QString expandLiteralMacro (QString macroTemplate, + NativeMacroContext const& context) + { + macroTemplate.replace (QStringLiteral ("%M"), context.myCall); + macroTemplate.replace (QStringLiteral ("%H"), context.hisCall); + macroTemplate.replace (QStringLiteral ("%Q"), context.hisCall); + macroTemplate.replace (QStringLiteral ("%N"), formatSerialNumber (context.serialNumber)); + macroTemplate.replace (QStringLiteral ("%E"), nativeExchangeFieldText (context)); + macroTemplate.replace (QStringLiteral ("%G"), context.grid); + return macroTemplate; + } + + inline QString migratedNativeMacroTemplate (int functionKey, QString const& savedValue) + { + if ((functionKey == 2 || functionKey == 6 || functionKey == 8) + && savedValue == legacyNativeMacroTemplate (functionKey)) { + return nativeMacroTemplate (functionKey); + } + return savedValue; + } + + inline QString normalizedNativeCall (QString const& call) + { + return call.trimmed ().toUpper (); + } + + inline bool isNativeCall (QString const& rawCall) + { + QString const call = normalizedNativeCall (rawCall); + if (call.size () < 3 || call.size () > 6 || call.startsWith (QLatin1Char {'Q'})) { + return false; + } + + int area = -1; + for (int i = call.size () - 1; i >= 1; --i) { + QChar const c = call.at (i); + if (c >= QLatin1Char {'0'} && c <= QLatin1Char {'9'}) { + area = i; + break; + } + } + if (area != 1 && area != 2) return false; + + bool prefixHasLetter {false}; + for (int i = 0; i < area; ++i) { + QChar const c = call.at (i); + bool const isLetter = c >= QLatin1Char {'A'} && c <= QLatin1Char {'Z'}; + bool const isDigit = c >= QLatin1Char {'0'} && c <= QLatin1Char {'9'}; + if (!isLetter && !isDigit) return false; + prefixHasLetter = prefixHasLetter || isLetter; + } + if (!prefixHasLetter || area == call.size () - 1) return false; + + for (int i = area + 1; i < call.size (); ++i) { + QChar const c = call.at (i); + if (c < QLatin1Char {'A'} || c > QLatin1Char {'Z'}) return false; + } + return call.size () - area - 1 <= 3; + } + + inline NativeAtomDescriptor nativeCallAtom (CallAction action, QString const& rawCall) + { + NativeAtomDescriptor atom; + atom.kind = static_cast<qint8> (NativeAtomKind::Call); + atom.subtype = static_cast<qint8> (action); + QByteArray const call = normalizedNativeCall (rawCall).toLatin1 (); + std::copy_n (call.cbegin (), std::min (call.size (), 8), atom.text); + return atom; + } + + inline NativeAtomDescriptor nativeSerialAtom (int serialNumber) + { + NativeAtomDescriptor atom; + atom.kind = static_cast<qint8> (NativeAtomKind::ExchangeNumber); + atom.subtype = static_cast<qint8> (NumberKind::Serial); + atom.role = static_cast<qint8> (ExchangeRole::Full); + atom.value = serialNumber; + return atom; + } + + inline void setNativeAtomText (NativeAtomDescriptor& atom, QString const& value) + { + QByteArray const text = value.toLatin1 (); + std::copy_n (text.cbegin (), std::min (text.size (), 8), atom.text); + } + + inline NativeAtomDescriptor nativeLocationAtom (ExchangeRole role, LocationKind kind, + QString const& token) + { + NativeAtomDescriptor atom; + atom.kind = static_cast<qint8> (NativeAtomKind::ExchangeLocation); + atom.subtype = static_cast<qint8> (kind); + atom.role = static_cast<qint8> (role); + setNativeAtomText (atom, token); + return atom; + } + + inline NativeAtomDescriptor nativeClassSectionAtom (int count, QChar classLetter, + QString const& section) + { + NativeAtomDescriptor atom; + atom.kind = static_cast<qint8> (NativeAtomKind::ExchangePair); + atom.subtype = static_cast<qint8> (PairSchema::ClassSection); + atom.role = static_cast<qint8> (classLetter.unicode () - QLatin1Char {'A'}.unicode ()); + atom.value = count; + setNativeAtomText (atom, section); + return atom; + } + + inline NativeAtomDescriptor nativeControlAtom (int phraseId) + { + NativeAtomDescriptor atom; + atom.kind = static_cast<qint8> (NativeAtomKind::Control); + atom.subtype = static_cast<qint8> (phraseId); + return atom; + } + + inline NativeAtomDescriptor nativeGridAtom (ExchangeRole role, QString const& grid) + { + NativeAtomDescriptor atom; + atom.kind = static_cast<qint8> (NativeAtomKind::Grid4); + atom.role = static_cast<qint8> (role); + setNativeAtomText (atom, grid); + return atom; + } + + inline bool isDecimal (QString const& value) + { + if (value.isEmpty ()) return false; + for (QChar const c : value) { + if (c < QLatin1Char {'0'} || c > QLatin1Char {'9'}) return false; + } + return true; + } + + inline QString normalizedFieldDayExchange (QString const& value) + { + QString exchange = value.simplified ().toUpper (); + if (exchange.contains (QLatin1Char {' '})) return exchange; + + int classPosition {0}; + while (classPosition < exchange.size () + && exchange.at (classPosition) >= QLatin1Char {'0'} + && exchange.at (classPosition) <= QLatin1Char {'9'}) { + ++classPosition; + } + if (classPosition > 0 && classPosition + 1 < exchange.size () + && exchange.at (classPosition) >= QLatin1Char {'A'} + && exchange.at (classPosition) <= QLatin1Char {'F'}) { + exchange.insert (classPosition + 1, QLatin1Char {' '}); + } + return exchange; + } + + inline bool isCanonicalBase36Token (QString const& value) + { + if (value.size () != 2 && value.size () != 3) return false; + if (value.size () == 3 && value.startsWith (QLatin1Char {'0'})) return false; + for (QChar const c : value) { + bool const digit = c >= QLatin1Char {'0'} && c <= QLatin1Char {'9'}; + bool const letter = c >= QLatin1Char {'A'} && c <= QLatin1Char {'Z'}; + if (!digit && !letter) return false; + } + return true; + } + + inline bool isGrid4 (QString const& value) + { + if (value.size () != 4) return false; + return value.at (0) >= QLatin1Char {'A'} && value.at (0) <= QLatin1Char {'R'} + && value.at (1) >= QLatin1Char {'A'} && value.at (1) <= QLatin1Char {'R'} + && value.at (2) >= QLatin1Char {'0'} && value.at (2) <= QLatin1Char {'9'} + && value.at (3) >= QLatin1Char {'0'} && value.at (3) <= QLatin1Char {'9'}; + } + + inline QString controlPhrase (int phraseId) + { + static QString const phrases[] { + QStringLiteral ("AGN?"), + QStringLiteral ("CALL?"), + QStringLiteral ("AGN CALL"), + QStringLiteral ("NR?"), + QStringLiteral ("AGN NR"), + QStringLiteral ("EXCH?"), + QStringLiteral ("STATE?"), + QStringLiteral ("SECTION?"), + QStringLiteral ("ZONE?"), + QStringLiteral ("GRID?"), + QStringLiteral ("RPRT?"), + QStringLiteral ("QSL TU"), + QStringLiteral ("TU"), + QStringLiteral ("QRZ?"), + QStringLiteral ("QSO B4"), + QStringLiteral ("WAIT"), + QStringLiteral ("NIL?"), + QStringLiteral ("OK?") + }; + if (phraseId < 0 || phraseId >= 18) return {}; + return phrases[phraseId]; + } + + inline int controlPhraseId (QString const& macroTemplate) + { + QString const normalized = normalizedMacroTemplate (macroTemplate); + for (int phraseId = 0; phraseId < 18; ++phraseId) { + if (normalized == controlPhrase (phraseId)) return phraseId; + } + return -1; + } + + struct NativeExchangeCompilation + { + bool valid {false}; + NativeAtomDescriptor atom; + QString text; + QString error; + }; + + inline NativeExchangeCompilation nativeExchange (NativeMacroContext const& context) + { + NativeExchangeCompilation result; + auto invalid = [&result] (QString const& error) { + result.error = error; + return result; + }; + auto serial = [&result] (int value) { + if (value < 0 || value >= (1 << 17)) return false; + result.valid = true; + result.atom = nativeSerialAtom (value); + result.text = QStringLiteral ("599 %1").arg (formatSerialNumber (value)); + return true; + }; + + QString const configured = context.configuredExchange.simplified ().toUpper (); + switch (context.exchangeProfile) { + case NativeExchangeProfile::None: + if (!serial (context.serialNumber)) { + return invalid (QStringLiteral ("Serial number must be between 0 and 131071")); + } + return result; + + case NativeExchangeProfile::FieldDay: { + QStringList const fields = configured.split (QLatin1Char {' '}); + if (fields.size () != 2 || fields.at (0).size () < 2) { + return invalid (QStringLiteral ("Field Day exchange must be COUNTCLASS SECTION")); + } + QString const countClass = fields.at (0); + QChar const classLetter = countClass.back (); + QString const countText = countClass.left (countClass.size () - 1); + bool countOk {false}; + int const count = countText.toInt (&countOk); + if (!countOk || !isDecimal (countText) || count < 1 || count > 32) { + return invalid (QStringLiteral ("Field Day transmitter count must be between 1 and 32")); + } + if (classLetter < QLatin1Char {'A'} || classLetter > QLatin1Char {'F'}) { + return invalid (QStringLiteral ("Field Day class must be A through F")); + } + QString const section = fields.at (1); + if (!isCanonicalBase36Token (section)) { + return invalid (QStringLiteral ("Field Day section must be a canonical 2-3 character code")); + } + result.valid = true; + result.atom = nativeClassSectionAtom (count, classLetter, section); + result.text = QStringLiteral ("%1%2 %3").arg (count).arg (classLetter).arg (section); + return result; + } + + case NativeExchangeProfile::RttyRoundup: + if (configured == QStringLiteral ("DX") || configured == QStringLiteral ("#")) { + if (!serial (context.serialNumber)) { + return invalid (QStringLiteral ("Serial number must be between 0 and 131071")); + } + return result; + } + if (isDecimal (configured)) { + bool valueOk {false}; + int const value = configured.toInt (&valueOk); + if (!valueOk || !serial (value)) { + return invalid (QStringLiteral ("Configured serial must be between 0 and 131071")); + } + return result; + } + if (!isCanonicalBase36Token (configured)) { + return invalid (QStringLiteral ( + "RTTY exchange must be DX, #, a decimal serial, or a canonical 2-3 character state/province")); + } + result.valid = true; + result.atom = nativeLocationAtom ( + ExchangeRole::Full, LocationKind::StateProvince, configured); + result.text = QStringLiteral ("599 %1").arg (configured); + return result; + } + + return invalid (QStringLiteral ("Unsupported exchange profile")); + } + + inline NativeExchangeCompilation nativeGridExchange (NativeMacroContext const& context, + ExchangeRole role) + { + NativeExchangeCompilation result; + QString const locator = context.grid.trimmed ().toUpper (); + static QRegularExpression const locatorPattern { + QStringLiteral ("^[A-R]{2}[0-9]{2}(?:[A-X]{2}(?:[0-9]{2})?)?$")}; + if (!locatorPattern.match (locator).hasMatch ()) { + result.error = QStringLiteral ("Grid must be a valid four-, six-, or eight-character Maidenhead locator"); + return result; + } + QString const grid = locator.left (4); + result.valid = true; + result.atom = nativeGridAtom (role, grid); + result.text = role == ExchangeRole::Full + ? QStringLiteral ("599 %1").arg (grid) : grid; + return result; + } + + inline NativeMacroCompilation compileNativeMacro ( + QString const& macroTemplate, NativeMacroContext const& context) + { + NativeMacroCompilation result; + QString const normalized = normalizedMacroTemplate (macroTemplate); + int const phraseId = controlPhraseId (normalized); + if (phraseId >= 0) { + result.status = NativeMacroStatus::Native; + result.atoms.append (nativeControlAtom (phraseId)); + result.text = controlPhrase (phraseId); + return result; + } + + int const functionKey = nativeMacroFunctionKey (macroTemplate); + if (functionKey == 0) { + result.text = expandLiteralMacro (macroTemplate, context); + return result; + } + + QString const myCall = normalizedNativeCall (context.myCall); + QString const hisCall = normalizedNativeCall (context.hisCall); + auto invalid = [&result] (QString const& error) { + result.status = NativeMacroStatus::InvalidRuntime; + result.atoms.clear (); + result.text.clear (); + result.error = error; + return result; + }; + auto appendCall = [&result] (CallAction action, QString const& call) { + result.atoms.append (nativeCallAtom (action, call)); + }; + auto appendSerial = [&result, &context] { + result.atoms.append (nativeSerialAtom (context.serialNumber)); + }; + auto appendExchange = [&result, &context, &normalized] { + NativeExchangeCompilation exchange; + if (normalized.contains (QStringLiteral ("%G"))) { + ExchangeRole const role = normalized == QStringLiteral ("599 %G") + ? ExchangeRole::Full : ExchangeRole::FieldOnly; + exchange = nativeGridExchange (context, role); + } else { + exchange = nativeExchange (context); + } + if (exchange.valid) result.atoms.append (exchange.atom); + return exchange; + }; + + switch (functionKey) { + case 1: + if (!isNativeCall (myCall)) return invalid (QStringLiteral ("Configured callsign is not a native Call8 callsign")); + appendCall (CallAction::Cq, myCall); + result.text = QStringLiteral ("CQ %1 CQ").arg (myCall); + break; + case 2: + if (!isNativeCall (hisCall)) return invalid (QStringLiteral ("DX callsign is not a native Call8 callsign")); + appendCall (CallAction::Call, hisCall); + if (macroTemplate == legacyNativeMacroTemplate (2)) { + if (context.serialNumber < 0 || context.serialNumber >= (1 << 17)) { + return invalid (QStringLiteral ("Serial number must be between 0 and 131071")); + } + appendSerial (); + result.text = QStringLiteral ("%1 599 %2").arg ( + hisCall, formatSerialNumber (context.serialNumber)); + } else { + auto const exchange = appendExchange (); + if (!exchange.valid) return invalid (exchange.error); + result.text = QStringLiteral ("%1 %2").arg (hisCall, exchange.text); + } + break; + case 3: + if (!isNativeCall (hisCall)) return invalid (QStringLiteral ("DX callsign is not a native Call8 callsign")); + if (!isNativeCall (myCall)) return invalid (QStringLiteral ("Configured callsign is not a native Call8 callsign")); + appendCall (CallAction::CallTu, hisCall); + appendCall (CallAction::Cq, myCall); + result.text = QStringLiteral ("%1 TU CQ %2 CQ").arg (hisCall, myCall); + break; + case 4: + if (!isNativeCall (myCall)) return invalid (QStringLiteral ("Configured callsign is not a native Call8 callsign")); + appendCall (CallAction::Call, myCall); + result.text = myCall; + break; + case 5: + if (!isNativeCall (hisCall)) return invalid (QStringLiteral ("DX callsign is not a native Call8 callsign")); + appendCall (CallAction::Call, hisCall); + result.text = hisCall; + break; + case 6: + if (!isNativeCall (hisCall)) return invalid (QStringLiteral ("Queued callsign is not a native Call8 callsign")); + appendCall (CallAction::TuNowCall, hisCall); + if (macroTemplate == legacyNativeMacroTemplate (6)) { + if (context.serialNumber < 0 || context.serialNumber >= (1 << 17)) { + return invalid (QStringLiteral ("Serial number must be between 0 and 131071")); + } + appendSerial (); + result.text = QStringLiteral ("TU NOW %1 599 %2").arg ( + hisCall, formatSerialNumber (context.serialNumber)); + } else { + auto const exchange = appendExchange (); + if (!exchange.valid) return invalid (exchange.error); + result.text = QStringLiteral ("TU NOW %1 %2").arg (hisCall, exchange.text); + } + break; + case 7: + if (!isNativeCall (hisCall)) return invalid (QStringLiteral ("DX callsign is not a native Call8 callsign")); + appendCall (CallAction::CallAgn, hisCall); + result.text = QStringLiteral ("%1 AGN?").arg (hisCall); + break; + case 8: + if (macroTemplate == legacyNativeMacroTemplate (8)) { + if (context.serialNumber < 0 || context.serialNumber >= (1 << 17)) { + return invalid (QStringLiteral ("Serial number must be between 0 and 131071")); + } + appendSerial (); + result.text = QStringLiteral ("599 %1").arg (formatSerialNumber (context.serialNumber)); + } else { + auto const exchange = appendExchange (); + if (!exchange.valid) return invalid (exchange.error); + result.text = exchange.text; + } + break; + default: + return invalid (QStringLiteral ("Unsupported native macro")); + } + + result.status = NativeMacroStatus::Native; + return result; + } + + inline NativeMacroCompilation compileNativeMacro ( + int functionKey, QString const& macroTemplate, NativeMacroContext const& context) + { + (void) functionKey; + return compileNativeMacro (macroTemplate, context); + } + + // Resolve a JTTY message start from the WAV anchor, preserving the raw-time fallback for test-generated files. + inline QDateTime jttyLineStartTimeUtc (QDateTime const& diskDateTime, + qint32 utcDiskRaw, float tsyncSeconds) + { + QDateTime anchor = diskDateTime; + if (!anchor.isValid ()) { + QTime const t = QTime::fromString ( + QString {"%1"}.arg (utcDiskRaw, 6, 10, QLatin1Char {'0'}), "hhmmss"); + if (!t.isValid ()) return {}; + anchor = QDateTime {QDate {2000, 1, 1}, t, Qt::UTC}; + } + return anchor.addMSecs (qRound64 (1000.0 * tsyncSeconds)).toUTC (); + } + + inline QString jttyLineTimeLabel (QDateTime const& timestampUtc) + { + return timestampUtc.isValid () + ? timestampUtc.toUTC ().toString ("hhmmss") : QString {}; + } + + // "Include Time" label; falls back to utcDiskRaw as a bare time-of-day when diskDateTime doesn't parse (e.g. sjtty's dummy-date filenames). + inline QString jttyLineTimeLabel (QDateTime const& diskDateTime, + qint32 utcDiskRaw, float tsyncSeconds) + { + return jttyLineTimeLabel (jttyLineStartTimeUtc (diskDateTime, utcDiskRaw, + tsyncSeconds)); + } + + inline ParsedDecodeLine parseDecodeLine (QString const& line) + { + ParsedDecodeLine result; + QString const trimmed = line.trimmed (); + result.message = trimmed; + + int separator = 0; + while (separator < trimmed.size () && !trimmed.at (separator).isSpace ()) { + ++separator; + } + if (separator == 0) return result; + + bool frequencyOk {false}; + int const frequency = trimmed.left (separator).toInt (&frequencyOk); + if (!frequencyOk) return result; + + result.frequency = frequency; + result.message = separator < trimmed.size () + ? trimmed.mid (separator).trimmed () : QString {}; + result.valid = true; + return result; + } + + inline constexpr int maxDisplayWidth = 40; + + inline QString wrapMessage (QString const& text, int maxWidth = maxDisplayWidth) + { + if (text.size () <= maxWidth) return text; + + QString result; + int start = 0; + while (text.size () - start > maxWidth) { + int breakAt = -1; + for (int i = maxWidth; i > 0; --i) { + if (text.at (start + i) == QLatin1Char {' '}) { + breakAt = i; + break; + } + } + if (breakAt < 0) { + result += text.mid (start, maxWidth) + QLatin1String {"\n "}; + start += maxWidth; + } else { + result += text.mid (start, breakAt) + QLatin1String {"\n "}; + start += breakAt + 1; + } + } + result += text.mid (start); + return result; + } + + struct DecodeLineChange + { + bool messageChanged {false}; + bool extendsMessage {false}; + bool startsMessage {false}; + QString appendedText; + }; + + inline DecodeLineChange compareMessages (QString const& previous, + QString const& current) + { + DecodeLineChange change; + change.messageChanged = previous != current; + change.extendsMessage = change.messageChanged + && current.startsWith (previous); + change.startsMessage = previous.isEmpty () && !current.isEmpty (); + if (change.extendsMessage) { + change.appendedText = current.mid (previous.size ()); + } + return change; + } + + struct MessageUpdate + { + qint64 messageId {0}; + float frequency {0.f}; + QString text; + float sequenceStart {0.f}; + bool complete {false}; + }; + + inline bool shouldApplyToQsoHistory (bool alreadyPresent, float frequency, + float rxFrequency, float tolerance) + { + // Later frames retain their admitted message identity despite decoder frequency drift. + return alreadyPresent || std::abs (frequency - rxFrequency) < tolerance; + } + + template<typename HistoryLine, typename Factory> + bool mergeMessageUpdates (QVector<HistoryLine>& history, + QVector<MessageUpdate> const& updates, + Factory makeLine) + { + if (updates.isEmpty ()) return false; + + bool changed {false}; + bool orderChanged {false}; + for (auto const& update : updates) { + auto const known = std::find_if (history.begin (), history.end (), + [&update] (HistoryLine const& line) { + return line.messageId == update.messageId; + }); + if (known == history.end ()) { + history.append (makeLine (update)); + changed = true; + orderChanged = true; + } else { + bool const complete = known->complete || update.complete; + if (known->text != update.text || known->frequency != update.frequency + || known->complete != complete) { + changed = true; + } + known->text = update.text; + known->frequency = update.frequency; + known->complete = complete; + } + } + + if (orderChanged) { + std::sort (history.begin (), history.end (), [] (HistoryLine const& lhs, + HistoryLine const& rhs) { + if (lhs.sequenceStart != rhs.sequenceStart) { + return lhs.sequenceStart < rhs.sequenceStart; + } + return lhs.messageId < rhs.messageId; + }); + } + return changed; + } + + inline bool mergeMessageUpdates (QVector<MessageUpdate>& history, + QVector<MessageUpdate> const& updates) + { + return mergeMessageUpdates (history, updates, + [] (MessageUpdate const& update) { return update; }); + } +} + +#endif diff --git a/widgets/JttyN1mm.hpp b/widgets/JttyN1mm.hpp new file mode 100644 index 00000000..6975eb40 --- /dev/null +++ b/widgets/JttyN1mm.hpp @@ -0,0 +1,247 @@ +// -*- Mode: C++ -*- +#ifndef JTTY_N1MM_HPP +#define JTTY_N1MM_HPP + +#include <QString> +#include <QStringList> +#include <QVector> + +#include "JttyMessages.hpp" + +namespace Jtty +{ + enum class N1mmCompileStatus + { + Literal, + Native, + Error + }; + + struct N1mmCompilation + { + N1mmCompileStatus status {N1mmCompileStatus::Literal}; + QVector<NativeAtomDescriptor> atoms; + QString literalText; + QString canonicalText; + QString error; + + bool isNative () const { return status == N1mmCompileStatus::Native; } + }; + + namespace N1mmDetail + { + inline N1mmCompilation failure (QString const& reason) + { + N1mmCompilation result; + result.status = N1mmCompileStatus::Error; + result.error = reason; + return result; + } + + inline bool appendCall (QVector<NativeAtomDescriptor>& atoms, CallAction action, + QString const& call, QString& error) + { + if (!isNativeCall (call)) { + error = QStringLiteral ("invalid callsign in tagged payload"); + return false; + } + atoms.append (nativeCallAtom (action, call)); + return true; + } + + inline bool parseSerial (QString const& payload, int& serial) + { + if (!isDecimal (payload)) return false; + bool ok {false}; + serial = payload.toInt (&ok); + return ok && serial >= 0 && serial < (1 << 17); + } + + inline NativeExchangeCompilation expandedExchange ( + QString const& payload, NativeExchangeProfile profile) + { + NativeMacroContext context; + context.exchangeProfile = profile; + context.configuredExchange = payload; + + int serial {0}; + if (profile == NativeExchangeProfile::None) { + if (!parseSerial (payload, serial)) { + NativeExchangeCompilation result; + result.error = QStringLiteral ( + "serial exchange must be a decimal value between 0 and 131071"); + return result; + } + context.serialNumber = serial; + } else if (profile == NativeExchangeProfile::RttyRoundup) { + if (parseSerial (payload, serial)) { + context.serialNumber = serial; + } else if (isCanonicalBase36Token (payload)) { + NativeExchangeCompilation result; + result.valid = true; + result.atom = nativeLocationAtom ( + ExchangeRole::Full, LocationKind::StateProvince, payload); + result.text = QStringLiteral ("599 %1").arg (payload); + return result; + } else { + NativeExchangeCompilation result; + result.error = QStringLiteral ( + "tagged RTTY exchange must contain a decimal serial or state/province"); + return result; + } + } + return nativeExchange (context); + } + } + + // A tag is recognized only at the first non-space character. Its payload is + // the value text already expanded by N1MM, never N1MM macro syntax. + inline N1mmCompilation compileN1mmMessage ( + QString const& message, NativeExchangeProfile profile = NativeExchangeProfile::None) + { + int first {0}; + while (first < message.size () && message.at (first).isSpace ()) ++first; + QString const marker = QStringLiteral ("[[JTTY:"); + if (message.mid (first, marker.size ()).compare (marker, Qt::CaseInsensitive) != 0) { + QString const tagStem = QStringLiteral ("[[JTTY"); + if (message.mid (first, tagStem.size ()).compare ( + tagStem, Qt::CaseInsensitive) == 0) { + return N1mmDetail::failure (QStringLiteral ("malformed JTTY action tag")); + } + N1mmCompilation result; + result.literalText = message; + return result; + } + + int const close = message.indexOf (QStringLiteral ("]]"), first + marker.size ()); + if (close < 0) return N1mmDetail::failure (QStringLiteral ("malformed JTTY action tag")); + QString const action = message.mid (first + marker.size (), + close - first - marker.size ()).toUpper (); + if (action.isEmpty () || action.contains (QLatin1Char {'['}) + || action.contains (QLatin1Char {']'}) || action.contains (QLatin1Char {' '}) + || action.contains (QLatin1Char {'\t'})) { + return N1mmDetail::failure (QStringLiteral ("malformed JTTY action tag")); + } + + static QStringList const actions { + QStringLiteral ("CQ"), QStringLiteral ("CALL_EXCH"), + QStringLiteral ("CALL_TU_CQ"), QStringLiteral ("MYCALL"), + QStringLiteral ("HISCALL"), QStringLiteral ("TU_NOW_EXCH"), + QStringLiteral ("CALL_MY"), QStringLiteral ("CALL_TU_MY"), + QStringLiteral ("EXCH"), QStringLiteral ("GRID"), QStringLiteral ("CONTROL") + }; + if (!actions.contains (action)) { + return N1mmDetail::failure (QStringLiteral ("unknown JTTY action: %1").arg (action)); + } + + QString const payload = message.mid (close + 2).simplified ().toUpper (); + if (payload.isEmpty ()) return N1mmDetail::failure (QStringLiteral ("tagged payload is empty")); + QStringList const fields = payload.split (QLatin1Char {' '}, Qt::SkipEmptyParts); + N1mmCompilation result; + result.status = N1mmCompileStatus::Native; + QString error; + + if (action == QStringLiteral ("CQ")) { + if (fields.size () != 1 + || !N1mmDetail::appendCall (result.atoms, CallAction::Cq, + fields.value (0), error)) { + if (error.isEmpty ()) error = QStringLiteral ("CQ payload must contain one callsign"); + } else { + result.canonicalText = QStringLiteral ("CQ %1 CQ").arg (fields.first ()); + } + } else if (action == QStringLiteral ("CALL_EXCH") + || action == QStringLiteral ("TU_NOW_EXCH")) { + if (fields.size () < 2) { + error = QStringLiteral ("call/exchange payload is incomplete"); + } else { + QString const call = fields.first (); + CallAction const callAction = action == QStringLiteral ("CALL_EXCH") + ? CallAction::Call : CallAction::TuNowCall; + if (N1mmDetail::appendCall (result.atoms, callAction, call, error)) { + auto const exchange = N1mmDetail::expandedExchange ( + fields.mid (1).join (QLatin1Char {' '}), profile); + if (!exchange.valid) { + error = exchange.error; + result.atoms.clear (); + } else { + result.atoms.append (exchange.atom); + result.canonicalText = action == QStringLiteral ("CALL_EXCH") + ? call + QLatin1Char {' '} + exchange.text + : QStringLiteral ("TU NOW %1 %2").arg (call, exchange.text); + } + } + } + } else if (action == QStringLiteral ("CALL_TU_CQ")) { + if (fields.size () != 2 + || !N1mmDetail::appendCall (result.atoms, CallAction::CallTu, + fields.value (0), error) + || !N1mmDetail::appendCall (result.atoms, CallAction::Cq, + fields.value (1), error)) { + if (error.isEmpty ()) { + error = QStringLiteral ("CALL_TU_CQ payload must contain two callsigns"); + } + } else { + result.canonicalText = QStringLiteral ("%1 TU CQ %2 CQ").arg ( + fields.at (0), fields.at (1)); + } + } else if (action == QStringLiteral ("MYCALL") || action == QStringLiteral ("HISCALL")) { + if (fields.size () != 1 + || !N1mmDetail::appendCall (result.atoms, CallAction::Call, + fields.value (0), error)) { + if (error.isEmpty ()) error = QStringLiteral ("call payload must contain one callsign"); + } else { + result.canonicalText = fields.first (); + } + } else if (action == QStringLiteral ("CALL_MY") + || action == QStringLiteral ("CALL_TU_MY")) { + bool const withTu = action == QStringLiteral ("CALL_TU_MY"); + if (fields.size () != 2 + || !N1mmDetail::appendCall (result.atoms, + withTu ? CallAction::CallTu : CallAction::Call, + fields.value (0), error) + || !N1mmDetail::appendCall (result.atoms, CallAction::Call, + fields.value (1), error)) { + if (error.isEmpty ()) error = QStringLiteral ("two-call payload must contain two callsigns"); + } else { + result.canonicalText = withTu + ? QStringLiteral ("%1 TU %2").arg (fields.at (0), fields.at (1)) + : QStringLiteral ("%1 %2").arg (fields.at (0), fields.at (1)); + } + } else if (action == QStringLiteral ("EXCH")) { + auto const exchange = N1mmDetail::expandedExchange (payload, profile); + if (!exchange.valid) { + error = exchange.error; + } else { + result.atoms.append (exchange.atom); + result.canonicalText = exchange.text; + } + } else if (action == QStringLiteral ("GRID")) { + if (fields.size () != 1 || !isGrid4 (fields.first ())) { + error = QStringLiteral ("GRID payload must contain one valid four-character grid"); + } else { + result.atoms.append (nativeGridAtom (ExchangeRole::FieldOnly, fields.first ())); + result.canonicalText = fields.first (); + } + } else if (action == QStringLiteral ("CONTROL")) { + int const phraseId = controlPhraseId (payload); + if (phraseId < 0) { + error = QStringLiteral ("unknown CONTROL phrase"); + } else { + result.atoms.append (nativeControlAtom (phraseId)); + result.canonicalText = controlPhrase (phraseId); + } + } + + if (!error.isEmpty ()) return N1mmDetail::failure (error); + if (result.atoms.isEmpty ()) return N1mmDetail::failure (QStringLiteral ("tag produced no atoms")); + return result; + } + + inline N1mmCompilation compileN1mmMessage ( + QString const& message, NativeMacroContext const& context) + { + return compileN1mmMessage (message, context.exchangeProfile); + } +} + +#endif diff --git a/widgets/JttyN1mmOutput.hpp b/widgets/JttyN1mmOutput.hpp new file mode 100644 index 00000000..ad92fc23 --- /dev/null +++ b/widgets/JttyN1mmOutput.hpp @@ -0,0 +1,57 @@ +// -*- Mode: C++ -*- +#ifndef JTTY_N1MM_OUTPUT_HPP +#define JTTY_N1MM_OUTPUT_HPP + +#include <QSet> +#include <QtGlobal> + +namespace Jtty +{ + class N1mmOutput + { + public: + void submit (qint64 requestId) + { + requests_.insert (requestId); + completionPending_ = true; + } + + bool accept (qint64 requestId) + { + if (!requests_.contains (requestId)) return false; + acceptedAudio_ = true; + return true; + } + bool resolve (qint64 requestId) { return requests_.remove (requestId) != 0; } + bool pending () const { return completionPending_; } + bool finishRequested () const { return finishRequested_; } + bool startRequested () const { return startRequested_; } + void start () { finishRequested_ = false; startRequested_ = true; } + void started () { startRequested_ = false; } + void finish () + { + if (completionPending_) finishRequested_ = true; + if (requests_.isEmpty ()) startRequested_ = false; + } + void abort () { *this = N1mmOutput {}; } + + bool takeCompletion (bool audioActive, bool drained = false) + { + // Rejections can precede more TXTEXT in the same transaction. OFF + // closes an empty transaction; accepted audio completes only at drain. + if (!completionPending_ || !requests_.isEmpty () || audioActive + || (!finishRequested_ && !(drained && acceptedAudio_))) return false; + abort (); + return true; + } + + private: + QSet<qint64> requests_; + bool completionPending_ {false}; + bool finishRequested_ {false}; + bool startRequested_ {false}; + bool acceptedAudio_ {false}; + }; +} + +#endif diff --git a/widgets/MMTTYIF.cpp b/widgets/MMTTYIF.cpp new file mode 100644 index 00000000..1745db56 --- /dev/null +++ b/widgets/MMTTYIF.cpp @@ -0,0 +1,257 @@ +#include "MMTTYIF.hpp" +#include <QCoreApplication> +#include <QDateTime> +#include <QFile> +#include <QTextStream> + +namespace +{ + int constexpr maximum_header_bytes {64}; + int constexpr maximum_payload_bytes {64 * 1024}; + int constexpr maximum_frame_bytes {maximum_header_bytes + maximum_payload_bytes}; + + bool resynchronizeAt (QByteArray * buffer, int next) + { + if (next < 0) { + buffer->clear (); + return false; + } + + buffer->remove (0, next); + return true; + } + + bool resynchronize (QByteArray * buffer) + { + return resynchronizeAt (buffer, buffer->indexOf ('<', 1)); + } + + bool hasCompleteTrailingPayload (QByteArray const& command, + QByteArray const& buffer, + int payloadStart) + { + int const payloadSize = buffer.size () - payloadStart; + return payloadSize == command.size () + && buffer.mid (payloadStart, payloadSize).compare (command, Qt::CaseInsensitive) == 0; + } +} + +MMTTYIF::MMTTYIF(QObject *parent) : QObject(parent), + m_socket(new QTcpSocket(this)), + m_retryTimer(new QTimer(this)) { + m_retryTimer->setSingleShot(true); + m_socket->setReadBufferSize(maximum_frame_bytes); + + connect(m_socket, &QTcpSocket::readyRead, this, &MMTTYIF::onReadyRead); + connect(m_socket, &QTcpSocket::connected, this, &MMTTYIF::onConnected); + connect(m_socket, &QTcpSocket::disconnected, this, &MMTTYIF::onDisconnected); +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) + connect(m_socket, &QTcpSocket::errorOccurred, this, &MMTTYIF::onError); +#else + connect(m_socket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), this, &MMTTYIF::onError); +#endif + + connect(m_retryTimer, &QTimer::timeout, this, &MMTTYIF::onRetryTimeout); +} + +MMTTYIF::~MMTTYIF() { + shutdown(); +} + +void MMTTYIF::initialize(quint16 port) { + m_port = port; + m_connectionRetries = 0; + + QString logStr = QString("[INIT] Starting TCP connection to 127.0.0.1:%1").arg(m_port); + emit log_message(logStr); + + m_socket->connectToHost("127.0.0.1", m_port); +} + +void MMTTYIF::onConnected() { + m_connectionRetries = 0; + QString logStr = QString("[TCP] Connected to N1MM Logger+ on port %1").arg(m_port); + emit log_message(logStr); +} + +void MMTTYIF::onDisconnected() { + QString logStr = QString("[TCP] Disconnected from N1MM Logger+"); + emit log_message(logStr); +} + +void MMTTYIF::onError(QAbstractSocket::SocketError socketError) { + Q_UNUSED(socketError) + if (m_connectionRetries < 5) { + m_connectionRetries++; + QString logStr = QString("[TCP] Connection error, retrying (%1/5) in 1s...").arg(m_connectionRetries); + emit log_message(logStr); + m_retryTimer->start(1000); + } else { + QString logStr = QString("[TCP] Failed to connect after 5 retries."); + emit log_message(logStr); + emit connection_failed(); + } +} + +void MMTTYIF::onRetryTimeout() { + m_socket->connectToHost("127.0.0.1", m_port); +} + +void MMTTYIF::onReadyRead() { + QByteArray data = m_socket->readAll(); + m_rxBuffer.append(data); + + QString logStr = QString("[TCP RCVD] %1").arg(QString::fromLatin1(data)); + emit log_message(logStr); + emit message_received(); + + parseBufferedCommands(); +} + +void MMTTYIF::parseBufferedCommands() { + while (!m_rxBuffer.isEmpty()) { + int const open = m_rxBuffer.indexOf('<'); + if (open < 0) { + emit log_message(QString("[TCP WARN] Dropping unframed data: %1") + .arg(QString::fromLatin1(m_rxBuffer))); + m_rxBuffer.clear(); + return; + } + + if (open > 0) { + emit log_message(QString("[TCP WARN] Dropping data before command: %1") + .arg(QString::fromLatin1(m_rxBuffer.left(open)))); + m_rxBuffer.remove(0, open); + } + + int const close = m_rxBuffer.indexOf('>'); + if (close < 0) { + if (m_rxBuffer.size() < maximum_header_bytes) return; + + emit log_message(QString("[TCP WARN] Command header exceeds %1-byte limit") + .arg(maximum_header_bytes)); + if (!resynchronize(&m_rxBuffer)) return; + continue; + } + + if (close + 1 > maximum_header_bytes) { + emit log_message(QString("[TCP WARN] Command header exceeds %1-byte limit") + .arg(maximum_header_bytes)); + if (!resynchronize(&m_rxBuffer)) return; + continue; + } + + QByteArray const header = m_rxBuffer.mid(1, close - 1); + int const colon = header.indexOf(':'); + QByteArray const command = (colon >= 0 ? header.left(colon) : header).toUpper(); + int payloadLength = -1; + if (colon >= 0) { + bool ok = false; + payloadLength = header.mid(colon + 1).toInt(&ok); + if (!ok || payloadLength < 0) { + emit log_message(QString("[TCP WARN] Invalid command length in <%1>") + .arg(QString::fromLatin1(header))); + if (!resynchronize (&m_rxBuffer)) return; + continue; + } + if (payloadLength > maximum_payload_bytes) { + emit log_message(QString("[TCP WARN] Command payload length exceeds %1-byte limit in <%2>") + .arg(maximum_payload_bytes) + .arg(QString::fromLatin1(header))); + if (!resynchronize (&m_rxBuffer)) return; + continue; + } + } + + int payloadStart = close + 1; + int payloadEnd = payloadStart; + if (payloadLength >= 0) { + int const availablePayload = m_rxBuffer.size() - payloadStart; + if (availablePayload < payloadLength) return; + payloadEnd = payloadStart + payloadLength; + } else { + int const next = m_rxBuffer.indexOf('<', payloadStart); + payloadEnd = next >= 0 ? next : m_rxBuffer.size(); + if (payloadEnd - payloadStart > maximum_payload_bytes) { + emit log_message(QString("[TCP WARN] Command payload exceeds %1-byte limit") + .arg(maximum_payload_bytes)); + if (!resynchronizeAt (&m_rxBuffer, next)) return; + continue; + } + if (next < 0 + && !hasCompleteTrailingPayload (command, m_rxBuffer, payloadStart)) return; + } + + QByteArray const payload = m_rxBuffer.mid(payloadStart, payloadEnd - payloadStart); + m_rxBuffer.remove(0, payloadEnd); + dispatchCommand(command, payload); + } +} + +void MMTTYIF::dispatchCommand(QByteArray const& command, QByteArray const& payload) { + QString const content = QString::fromLatin1(payload); + + if (command == "TXTEXT") { + emit app_tx_string(content.toUpper()); + } else if (command == "XMIT") { + if (content.startsWith("ON", Qt::CaseInsensitive)) { + emit app_start_tx(); + } else if (content.startsWith("OFF", Qt::CaseInsensitive)) { + emit app_stop_tx(); + } + } else if (command == "ABORT") { + emit app_abort_tx(); + } else if (command == "CLOSE") { + emit app_is_quitting(); + } else { + emit log_message(QString("[TCP WARN] Ignoring unknown command <%1>") + .arg(QString::fromLatin1(command))); + } +} + + +void MMTTYIF::shutdown() { + QString logStr = "[EXIT] MMTTYIF shutting down"; + emit log_message(logStr); + + if (m_socket && m_socket->isOpen()) { + m_socket->disconnectFromHost(); + } +} + +bool MMTTYIF::isConnected() const { + return m_socket->state() == QAbstractSocket::ConnectedState; +} + +void MMTTYIF::echo_message_to_n1mm(const QString &message) { + if (isConnected()) { + if (message.isEmpty()) { + QString logStr = QString("MMTTYIF::echo_message_to_n1mm - Ignoring Empty message"); + emit log_message(logStr); + return; + } + QString msgToSend = QString("<RXTEXT:%1>%2").arg(message.length()).arg(message); + m_socket->write(msgToSend.toLatin1()); + m_socket->flush(); + + QString logStr = QString("[TCP SENT] %1").arg(msgToSend); + emit log_message(logStr); + } +} + +void MMTTYIF::report_output_complete() { + if (isConnected()) { + QString msgToSend = "<OUTPUTCOMPLETE>"; + m_socket->write(msgToSend.toLatin1()); + m_socket->flush(); + + QString logStr = QString("[TCP SENT] %1").arg(msgToSend); + emit log_message(logStr); + } +} + +void MMTTYIF::report_ptt_state(bool is_on) { + if (isConnected() && !is_on) { + emit log_message("[TCP INFO] PTT off; OUTPUTCOMPLETE is sent from JTTY drain"); + } +} diff --git a/widgets/MMTTYIF.hpp b/widgets/MMTTYIF.hpp new file mode 100644 index 00000000..f29adc0d --- /dev/null +++ b/widgets/MMTTYIF.hpp @@ -0,0 +1,63 @@ +#ifndef MMTTYIF_HPP +#define MMTTYIF_HPP + +#include <QObject> +#include <QString> +#include <QTcpSocket> +#include <QTimer> +#include <QByteArray> + +class MMTTYIF : public QObject { + Q_OBJECT + +public: + explicit MMTTYIF(QObject *parent = nullptr); + ~MMTTYIF(); + + void initialize(quint16 port); + bool isConnected() const; + +signals: + void inactivity_timeout(); + void app_is_quitting(); + void app_tx_string(QString str); + void app_start_tx(); + void app_stop_tx(); + void app_abort_tx(); + + void message_received(); + void log_message(const QString &msg); + void connection_failed(); + +public slots: + void echo_message_to_n1mm(const QString &message); + void report_output_complete(); + void report_ptt_state(bool is_on); + void shutdown(); + +private slots: + void onConnected(); + void onDisconnected(); +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) + void onError(QAbstractSocket::SocketError socketError); +#else + void onError(QAbstractSocket::SocketError socketError); +#endif + void onRetryTimeout(); + void onReadyRead(); + +private: + void parseBufferedCommands(); + void dispatchCommand(QByteArray const& command, QByteArray const& payload); + + QTcpSocket *m_socket; + QTimer *m_retryTimer; + QByteArray m_rxBuffer; + int m_connectionRetries; + quint16 m_port; + + quint32 m_baudRate = 0; + quint32 m_heightWidth = 0; +}; + +#endif // MMTTYIF_HPP diff --git a/widgets/QSYMessage.cpp b/widgets/QSYMessage.cpp index 9078c774..1dac0313 100644 --- a/widgets/QSYMessage.cpp +++ b/widgets/QSYMessage.cpp @@ -5,6 +5,7 @@ #include "SettingsGroup.hpp" #include "Configuration.hpp" #include "QSYMessage.h" +#include "widgets/QSYMessageParser.h" #include "ui_QSYMessage.h" QSYMessage::QSYMessage(const QString& message,const QString& theCall, QSettings * settings, Configuration const * configuration, QWidget *parent) : @@ -59,307 +60,23 @@ void QSYMessage::on_noButton_clicked() void QSYMessage::getBandModeFreq() { - if(receivedMessage.at(0) =='$' && receivedMessage.size() >= 5) - { -#if QT_VERSION >= QT_VERSION_CHECK (5, 15, 0) - QStringList bhList = receivedMessage.split(" ",Qt::SkipEmptyParts); -#else - QStringList bhList = receivedMessage.split(" ",QString::SkipEmptyParts); -#endif - ui->label->setText(bhList[1] + " replied " +bhList[2].mid(0,2)); - ui->yesButton->hide(); - ui->noButton->hide(); - } - else if(receivedMessage.at(0) =='Z' && receivedMessage.at(1) =='A' && receivedMessage.size() >= 5) { - QString messageContent = ""; - QString text1 = ""; - QString msgNum =receivedMessage.mid(2,3); - if(msgNum == "001") { - text1 = "You are in the log"; - } else if(msgNum =="002") { - text1 = "Please call me by phone"; - } else if(msgNum =="003") { - text1 = "Check your email"; - } else if(msgNum =="004") { - text1 = "You are not in Contest Mode"; - } else if(msgNum =="005") { - text1 = "Please check your PC Clock"; - } else if(msgNum =="006") { - text1 = "You are transmitting in the wrong time slot"; - } else if(msgNum =="007") { - text1 = "Please transmit above 1000 Hz"; - } else if(msgNum =="008") { - text1 = "Your transmitter is overmodulated"; - } else if(msgNum =="009") { - text1 = "Your audio is distorted"; - } else if(msgNum =="010") { - text1 = "You are transmitting on top of a rare DX station"; - } else if(msgNum =="011") { - text1 = "Please check HB9Q Logger"; - } else if(msgNum =="012") { - text1 = "Please check Ping Jockey"; - } else if(msgNum =="013") { - text1 = "Please check ON4KST"; - } else if(msgNum =="014") { - text1 = "Please QSL via LoTW"; - } - ui->noButton->setHidden(true); - ui->yesButton->setText("OK"); - ui->label->setText(text1); - } - else if(receivedMessage.at(0).isLetter() || receivedMessage.at(0) == '9' || receivedMessage.at(0) == '4' || receivedMessage.at(0) == '7') - { - QString bandParam = ""; - QString modeParam = receivedMessage.at(0); - QString freqParam = ""; - bandParam = receivedMessage.mid(0,1); - modeParam = receivedMessage.at(1); - freqParam = receivedMessage.mid(2, 3); - QString band = ""; - QString mode = ""; - QString freq = ""; - - if (bandParam == "A") { - if (modeParam.at(0).isLetter()) { - freq = "50."; - } else { - if (modeParam =="0") { - freq = "50."; - } else if (modeParam =="1") { - freq = "51."; - } else if (modeParam =="2") { - freq = "52."; - } else if (modeParam =="3") { - freq = "53."; - } - } - } - else if (bandParam == "B") { - if (modeParam.at(0).isLetter()) { - freq = "144."; - } else { - if (modeParam =="4") { - freq = "144."; - } else if (modeParam =="5") { - freq = "145."; - } else if (modeParam =="6") { - freq = "146."; - } else if (modeParam =="7") { - freq = "147."; - } - } - } - else if (bandParam == "C") { - if (modeParam.at(0).isLetter()) { - freq = "222."; - } else { - if (modeParam =="2") { - freq = "222."; - } else if (modeParam =="3") { - freq = "223."; - } - } - } - else if (bandParam == "D") { - if (modeParam.at(0).isLetter()) { - freq = "432."; - } else { - if (configuration_->region()==2) { - if (modeParam =="0") { - freq = "440."; - } else if (modeParam =="1") { - freq = "441."; - } else if (modeParam =="2") { - freq = "442."; - } else if (modeParam =="3") { - freq = "443."; - } else if (modeParam =="4") { - freq = "444."; - } else if (modeParam =="5") { - freq = "445."; - } else if (modeParam =="6") { - freq = "446."; - } else if (modeParam =="7") { - freq = "447."; - } else if (modeParam =="8") { - freq = "448."; - } else if (modeParam =="9") { - freq = "449."; - } - } else { //not region 2 - if (modeParam =="0") { - freq = "430."; - } else if (modeParam =="1") { - freq = "431."; - } else if (modeParam =="2") { - freq = "432."; - } else if (modeParam =="3") { - freq = "433."; - } else if (modeParam =="4") { - freq = "434."; - } else if (modeParam =="5") { - freq = "435."; - } else if (modeParam =="6") { - freq = "436."; - } else if (modeParam =="7") { - freq = "437."; - } else if (modeParam =="8") { - freq = "438."; - } else if (modeParam =="9") { - freq = "439."; - } - } - } - } - else if (bandParam == "E") { - if (modeParam.at(0).isLetter()) { - freq = "1296."; - } else { - if (modeParam =="0") { - freq = "1290."; - } else if (modeParam =="1") { - freq = "1291."; - } else if (modeParam =="2") { - freq = "1292."; - } else if (modeParam =="3") { - freq = "1293."; - } else if (modeParam =="4") { - freq = "1294."; - } else if (modeParam =="5") { - freq = "1295."; - } else if (modeParam =="6") { - freq = "1296."; - } else if (modeParam =="7") { - freq = "1297."; - } else if (modeParam =="8") { - freq = "1298."; - } else if (modeParam =="9") { - freq = "1299."; - } - } - } - else if (bandParam == "F") { - freq = "2304."; - } - else if (bandParam == "G") { - freq = "3400."; - } - else if (bandParam == "H") { - freq = "5760."; - } - else if (bandParam == "I") { - freq = "10368."; - } - else if (bandParam == "J") { - if (configuration_->region()==2) { - freq = "24192."; - } else { - freq = "24048."; - } - } - else if (bandParam == "9") { - freq = "902."; - } - else if (bandParam == "K") { - freq = "903."; - } - else if (bandParam == "J") { - freq = "24192."; - } - else if (bandParam == "X") { - freq = "24048."; - } - else if (bandParam == "4") { - freq = "40."; - } - else if (bandParam == "7") { - freq = "70."; - } - else if (bandParam == "L") { - freq = "0."; - } - else if (bandParam == "M") { - freq = "1."; - } - else if (bandParam == "N") { - freq = "3."; - } - else if (bandParam == "O") { - freq = "5."; - } - else if (bandParam == "P") { - freq = "7."; - } - else if (bandParam == "Q") { - freq = "10."; - } - else if (bandParam == "R") { - freq = "14."; - } - else if (bandParam == "S") { - freq = "18."; - } - else if (bandParam == "T") { - freq = "21."; - } - else if (bandParam == "U") { - freq = "24."; - } - else if (bandParam == "V") { - freq = "28."; - } - else if (bandParam == "W") { - freq = "29."; - } else { - freq = ""; - } - - freq = freq + freqParam; - if(!modeParam.at(0).isLetter()) { - mode = "FM"; - } - else if (modeParam == 'V') { - mode = "SSB"; - } - else if (modeParam == 'J') { - mode = "FT4"; - } - else if (modeParam == 'L') { - mode = "FT8"; - } - else if (modeParam == 'K') { - mode = "MSK144"; - } - else if (modeParam == 'W') { - mode = "CW"; - } - else if (modeParam == 'A') { - mode = "JT9"; - } - else if (modeParam == 'B') { - mode = "JT65"; - } - else if (modeParam == 'C') { - mode = "FST4"; - } - else if (modeParam == 'D') { - mode = "Q65-30B"; - } - else if (modeParam == 'E') { - mode = "Q65-60C"; - } - else if (modeParam == 'F') { - mode = "Q65-60D"; - } - else if (modeParam == 'G') { - mode = "Q65-60E"; - } - else if (modeParam == 'H') { - mode = "Q65-120D"; - } - else { - mode = ""; - } - ui->label->setText("QSY to\n" + freq + " MHz\n" + "mode " + mode); + QSYMessageParser::Message const message = + QSYMessageParser::decode (receivedMessage, configuration_->region ()); + switch (message.type) { + case QSYMessageParser::Type::Reply: + ui->label->setText (message.call + " replied " + message.response); + ui->yesButton->hide (); + ui->noButton->hide (); + break; + case QSYMessageParser::Type::General: + ui->noButton->setHidden (true); + ui->yesButton->setText ("OK"); + ui->label->setText (message.text); + break; + case QSYMessageParser::Type::Frequency: + ui->label->setText ("QSY to\n" + message.frequency_mhz + " MHz\n" + "mode " + message.mode); + break; + case QSYMessageParser::Type::Invalid: + break; } } diff --git a/widgets/QSYMessageCreator.cpp b/widgets/QSYMessageCreator.cpp index 0529c876..f0e79bab 100644 --- a/widgets/QSYMessageCreator.cpp +++ b/widgets/QSYMessageCreator.cpp @@ -22,6 +22,7 @@ #include "SettingsGroup.hpp" #include "Configuration.hpp" #include "qt_helpers.hpp" +#include "widgets/QSYMessageParser.h" #include "QSYMessageCreator.h" #include "ui_QSYMessageCreator.h" @@ -859,22 +860,24 @@ void QSYMessageCreator::on_genButton_clicked() } QString QSYMessageCreator::getGenMessage() { - QString message; - if (ui->message1->isChecked()) message = "001"; - else if (ui->message2->isChecked()) message = "002"; - else if (ui->message3->isChecked()) message = "003"; - else if (ui->message4->isChecked()) message = "004"; - else if (ui->message5->isChecked()) message = "005"; - else if (ui->message6->isChecked()) message = "006"; - else if (ui->message7->isChecked()) message = "007"; - else if (ui->message8->isChecked()) message = "008"; - else if (ui->message9->isChecked()) message = "009"; - else if (ui->message10->isChecked()) message = "010"; - else if (ui->message11->isChecked()) message = "011"; - else if (ui->message12->isChecked()) message = "012"; - else if (ui->message13->isChecked()) message = "013"; - else if (ui->message14->isChecked()) message = "014"; - message = ui->DxBaseLabel->text() + ".ZA" + message; + int code = 0; + if (ui->message1->isChecked()) code = 1; + else if (ui->message2->isChecked()) code = 2; + else if (ui->message3->isChecked()) code = 3; + else if (ui->message4->isChecked()) code = 4; + else if (ui->message5->isChecked()) code = 5; + else if (ui->message6->isChecked()) code = 6; + else if (ui->message7->isChecked()) code = 7; + else if (ui->message8->isChecked()) code = 8; + else if (ui->message9->isChecked()) code = 9; + else if (ui->message10->isChecked()) code = 10; + else if (ui->message11->isChecked()) code = 11; + else if (ui->message12->isChecked()) code = 12; + else if (ui->message13->isChecked()) code = 13; + else if (ui->message14->isChecked()) code = 14; + + QString const payload = QSYMessageParser::encodeGeneral (code); + QString const message = payload.isEmpty () ? QString {} : ui->DxBaseLabel->text() + "." + payload; ui->messageLabel4->setText(message); return message; } @@ -1019,25 +1022,27 @@ void QSYMessageCreator::read_settings () QString QSYMessageCreator::WriteMessage (QString hisCall, QString band, QChar mode) { - QString message = ""; + int kHzFreq = 0; + QLabel * label = nullptr; if(ui->tabWidget->currentIndex() == 1) { - qint16 kHzFreq = ui->kHzBox->value(); - QString kHzStr = QStringLiteral("%1").arg(kHzFreq,3,10,QLatin1Char('0')); - message = hisCall + "." + band + mode + kHzStr; - ui->messageLabel->setText(message); + kHzFreq = ui->kHzBox->value(); + label = ui->messageLabel; } else if(ui->tabWidget->currentIndex() == 0) { - qint16 kHzFreq = ui->kHzBox2->value(); - QString kHzStr = QStringLiteral("%1").arg(kHzFreq,3,10,QLatin1Char('0')); - message = hisCall + "." + band + mode + kHzStr; - ui->messageLabel2->setText(message); + kHzFreq = ui->kHzBox2->value(); + label = ui->messageLabel2; } else if(ui->tabWidget->currentIndex() == 2) { - qint16 kHzFreq = ui->kHzBox3->value(); - QString kHzStr = QStringLiteral("%1").arg(kHzFreq,3,10,QLatin1Char('0')); - message = hisCall + "." + band + mode + kHzStr; - ui->messageLabel3->setText(message); + kHzFreq = ui->kHzBox3->value(); + label = ui->messageLabel3; } + + if (!label) return QString {}; + + QChar const bandChar = band.isEmpty () ? QChar {} : band.at (0); + QString const payload = QSYMessageParser::encodeFrequency (bandChar, mode, kHzFreq, configuration_->region ()); + QString const message = payload.isEmpty () ? QString {} : hisCall + "." + payload; + label->setText(message); return message; } diff --git a/widgets/QSYMessageParser.cpp b/widgets/QSYMessageParser.cpp new file mode 100644 index 00000000..f51cba7f --- /dev/null +++ b/widgets/QSYMessageParser.cpp @@ -0,0 +1,250 @@ +#include "widgets/QSYMessageParser.h" + +#include <QChar> +#include <QStringList> +#include <QtGlobal> + +namespace +{ + QStringList split_ws (QString const& s) + { +#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) + return s.split (' ', QString::SkipEmptyParts); +#else + return s.split (' ', Qt::SkipEmptyParts); +#endif + } + + bool all_digits (QString const& s) + { + if (s.isEmpty ()) return false; + for (int i = 0; i < s.size (); ++i) + if (!s.at (i).isDigit ()) return false; + return true; + } + + QString pad3 (int n) + { + return QString {"%1"}.arg (n, 3, 10, QLatin1Char ('0')); + } + + struct ModeRow { char ch; char const* name; }; + ModeRow const kModes[] = { + {'V', "SSB"}, {'W', "CW"}, {'L', "FT8"}, {'K', "MSK144"}, + {'J', "FT4"}, {'A', "JT9"}, {'B', "JT65"}, {'C', "FST4"}, + {'D', "Q65-30B"}, {'E', "Q65-60C"}, {'F', "Q65-60D"}, + {'G', "Q65-60E"}, {'H', "Q65-120D"}, + }; + + bool mode_name (QChar m, QString * out) + { + if (m.isDigit ()) { if (out) *out = QStringLiteral ("FM"); return true; } + if (!m.isLetter ()) return false; + char const c = m.toLatin1 (); + for (ModeRow const& r : kModes) + if (r.ch == c) { if (out) *out = QString::fromLatin1 (r.name); return true; } + return false; + } + + char const* const kGeneral[] = { + "You are in the log", + "Please call me by phone", + "Check your email", + "You are not in Contest Mode", + "Please check your PC Clock", + "You are transmitting in the wrong time slot", + "Please transmit above 1000 Hz", + "Your transmitter is overmodulated", + "Your audio is distorted", + "You are transmitting on top of a rare DX station", + "Please check HB9Q Logger", + "Please check Ping Jockey", + "Please check ON4KST", + "Please QSL via LoTW", + }; + int const kGeneralCount = int (sizeof kGeneral / sizeof kGeneral[0]); // 14 + + bool is_vhf_subband (char b) + { + return b == 'A' || b == 'B' || b == 'C' || b == 'D' || b == 'E'; + } + + bool fm_digit_prefix (char band, QChar m, int region, QString * out) + { + int const d = m.digitValue (); + if (d < 0) return false; + int mhz; + switch (band) + { + case 'A': if (d > 3) return false; mhz = 50 + d; break; // 50..53 + case 'B': if (d < 4 || d > 7) return false; mhz = 140 + d; break; // 144..147 + case 'C': + if (region == 2) + { + if (d < 2 || d > 3) return false; + mhz = 220 + d; + } + else + { + if (d != 0) return false; + mhz = 222; + } + break; + case 'D': mhz = (region == 2 ? 440 : 430) + d; break; // 0..9 + case 'E': mhz = 1290 + d; break; // 0..9 + default: return false; + } + if (out) *out = QString::number (mhz) + "."; + return true; + } + + bool simple_prefix (char band, int region, QString * out) + { + if (band == 'J') { if (out) *out = (region == 2 ? "24192." : "24048."); return true; } + struct Row { char ch; char const* p; }; + static Row const simple[] = { + {'F', "2304."}, {'G', "3400."}, {'H', "5760."}, {'I', "10368."}, + {'K', "903."}, {'X', "24048."},{'9', "902."}, {'4', "40."}, {'7', "70."}, + {'L', "0."}, {'M', "1."}, {'N', "3."}, {'O', "5."}, {'P', "7."}, + {'Q', "10."}, {'R', "14."}, {'S', "18."}, {'T', "21."}, {'U', "24."}, + {'V', "28."}, {'W', "29."}, + }; + for (Row const& r : simple) + if (r.ch == band) { if (out) *out = QString::fromLatin1 (r.p); return true; } + return false; + } + + bool band_prefix (QChar band, QChar mode, int region, QString * out) + { + char const b = band.toLatin1 (); + if (is_vhf_subband (b)) + { + if (mode.isLetter ()) // letter (digital) mode -> base of the band + { + int const base = (b == 'A' ? 50 : b == 'B' ? 144 : b == 'C' ? 222 + : b == 'D' ? 432 : 1296); + if (out) *out = QString::number (base) + "."; + return true; + } + return fm_digit_prefix (b, mode, region, out); + } + return simple_prefix (b, region, out); + } + + QSYMessageParser::Message decode_reply (QString const& p) + { + QSYMessageParser::Message m; + if (!p.startsWith (QLatin1Char ('$'))) return m; + QStringList const f = split_ws (p); + if (f.size () != 3) return m; + if (f.at (0) != QLatin1String ("$")) return m; + if (f.at (2) != QLatin1String ("OKQSY") && f.at (2) != QLatin1String ("NOQSY")) return m; + m.type = QSYMessageParser::Type::Reply; + m.call = f.at (1); + m.response = f.at (2).left (2); + return m; + } + + QSYMessageParser::Message decode_general (QString const& p) + { + QSYMessageParser::Message m; + if (p.size () != 5) return m; // "ZA" + exactly 3 digits + if (p.at (0) != QLatin1Char ('Z') || p.at (1) != QLatin1Char ('A')) return m; + QString const digits = p.mid (2, 3); + if (!all_digits (digits)) return m; + int const code = digits.toInt (); + if (code < 1 || code > kGeneralCount) return m; + m.type = QSYMessageParser::Type::General; + m.code = code; + m.text = QString::fromLatin1 (kGeneral[code - 1]); + return m; + } + + QSYMessageParser::Message decode_frequency (QString const& p, int region) + { + QSYMessageParser::Message m; + if (p.size () != 5) return m; // band + mode + exactly 3 digits + QChar const band = p.at (0); + QChar const mode = p.at (1); + QString const digits = p.mid (2, 3); + if (!all_digits (digits)) return m; // freq field must be numeric + QString mode_str; + if (!mode_name (mode, &mode_str)) return m; // reject non-modes (I, R, ...) + QString prefix; + if (!band_prefix (band, mode, region, &prefix)) return m; // reject bad band / combo + m.type = QSYMessageParser::Type::Frequency; + m.band = band; + m.mode_char = mode; + m.kHz = digits.toInt (); + m.frequency_mhz = prefix + digits; + m.mode = mode_str; + return m; + } +} + +namespace QSYMessageParser +{ + Message decode (QString const& payload, int region) + { + if (payload.startsWith (QLatin1Char ('$'))) return decode_reply (payload); + if (payload.startsWith (QLatin1String ("ZA"))) return decode_general (payload); + return decode_frequency (payload, region); + } + + QString encode (Message const& m) + { + switch (m.type) + { + case Type::Frequency: return QString {m.band} + m.mode_char + pad3 (m.kHz); + case Type::General: return QStringLiteral ("ZA") + pad3 (m.code); + case Type::Reply: + case Type::Invalid: break; + } + return QString {}; + } + + QString encodeFrequency (QChar band, QChar mode, int kHz, int region) + { + if (kHz < 0 || kHz > 999) return QString {}; + QString scratch; + if (!mode_name (mode, &scratch)) return QString {}; + if (!band_prefix (band, mode, region, &scratch)) return QString {}; + return QString {band} + mode + pad3 (kHz); + } + + QString encodeGeneral (int code) + { + if (code < 1 || code > kGeneralCount) return QString {}; + return QStringLiteral ("ZA") + pad3 (code); + } + + QString encodeReplyWire (bool ok) + { + return ok ? QStringLiteral ("OKQSY") : QStringLiteral ("NOQSY"); + } + + bool mightContainMessage (QString const& line) + { + return line.contains (QLatin1Char ('.')); + } + + LineResult decodeLine (QString const& line, int region) + { + LineResult result; + for (QString const& token : split_ws (line)) + { + int const dot = token.indexOf (QLatin1Char ('.')); + if (dot <= 0 || dot >= token.size () - 1) continue; + QString const payload = token.mid (dot + 1); + Message const m = decode (payload, region); + if (m) + { + result.call = token.left (dot); + result.payload = payload; + result.message = m; + return result; + } + } + return result; + } +} diff --git a/widgets/QSYMessageParser.h b/widgets/QSYMessageParser.h new file mode 100644 index 00000000..b45b5109 --- /dev/null +++ b/widgets/QSYMessageParser.h @@ -0,0 +1,62 @@ +// -*- Mode: C++ -*- +#ifndef QSYMESSAGEPARSER_H +#define QSYMESSAGEPARSER_H + +#include <QString> +// Table-driven codec for the WSJT-X QSY Message wire language. decode() is the +// single source of truth for whether a payload is valid. +// +// Payload grammar: +// payload = freq | general | reply-display +// freq = band mode-or-fmdigit kHz3 e.g. "AL125", "B5550" +// general = "ZA" NNN (NNN in 001..014) e.g. "ZA007" +// reply = "$ " CALL " " ("OKQSY"|"NOQSY") synthesized locally on RX +namespace QSYMessageParser +{ + enum class Type { Invalid, Reply, General, Frequency }; + + struct Message + { + Type type; + + // Reply + QString call; // station that replied + QString response; // "OK" | "NO" + + // General + int code; // 1..14 + QString text; // canned-message text + + // Retain wire components so aliases such as J and X still round-trip. + QChar band; // e.g. 'A' + QChar mode_char; // mode letter, or FM sub-band digit + int kHz; // 0..999 + QString frequency_mhz; // e.g. "50.125" + QString mode; // e.g. "FT8" | "FM" + + Message () : type (Type::Invalid), code (0), kHz (0) {} + bool isValid () const { return type != Type::Invalid; } + explicit operator bool () const { return isValid (); } + }; + + Message decode (QString const& payload, int region); + + // Empty QString means invalid input. encode(Message) expects a Message + // returned by decode(), or an equivalently valid table-backed Message. + QString encode (Message const& message); + QString encodeFrequency (QChar band, QChar mode, int kHz, int region); + QString encodeGeneral (int code); + QString encodeReplyWire (bool ok); + + // Cheap, high-recall pre-filter for the RX hot path. NOT authoritative: every + // real QSY line passes, but some non-QSY lines may pass too. Use only as a + // fast early-exit; decode() / decodeLine() is the source of truth. + bool mightContainMessage (QString const& line); + + // Locate a "CALL.PAYLOAD" token in a decoded line and decode the payload. + // Returns the first token whose payload decodes; message.type==Invalid if none. + struct LineResult { QString call; QString payload; Message message; }; + LineResult decodeLine (QString const& line, int region); +} + +#endif diff --git a/widgets/RoundRobinSelection.cpp b/widgets/RoundRobinSelection.cpp new file mode 100644 index 00000000..d231e7ee --- /dev/null +++ b/widgets/RoundRobinSelection.cpp @@ -0,0 +1,48 @@ +#include "RoundRobinSelection.hpp" + +#include <QComboBox> +#include <QSignalBlocker> + +namespace +{ + int constexpr minimumPresetSlotCount {2}; + int constexpr maximumPresetSlotCount {6}; +} + +namespace RoundRobinSelection +{ + void initialize (QComboBox& combo, QString const& randomLabel) + { + QSignalBlocker const blocker {&combo}; + combo.clear (); + combo.addItem (randomLabel, QStringLiteral ("random")); + // Keep the standard 2–6 presets while allowing larger custom schedules. + for (int count = minimumPresetSlotCount; count <= maximumPresetSlotCount; ++count) + { + for (int slot = 0; slot < count; ++slot) + { + auto const canonical = QString::fromStdString ( + BeaconTx::formatRoundRobinPolicy (BeaconTx::RoundRobinPolicy::fixed (slot, count))); + combo.addItem (canonical, canonical); + } + } + } + + BeaconTx::RoundRobinPolicy policy (QComboBox const& combo) + { + auto const index = combo.currentIndex (); + auto const text = combo.currentText (); + // Editing a preset leaves its index selected until the edit is committed. + auto const value = index >= 0 && text == combo.itemText (index) + && combo.itemData (index).isValid () ? combo.itemData (index).toString () : text; + return BeaconTx::parseRoundRobinPolicy (value.toStdString ()); + } + + void setPolicy (QComboBox& combo, BeaconTx::RoundRobinPolicy const& policy) + { + auto const canonical = QString::fromStdString (BeaconTx::formatRoundRobinPolicy (policy)); + auto const index = combo.findData (canonical); + if (index >= 0) combo.setCurrentIndex (index); + else combo.setEditText (canonical); + } +} diff --git a/widgets/RoundRobinSelection.hpp b/widgets/RoundRobinSelection.hpp new file mode 100644 index 00000000..8412e150 --- /dev/null +++ b/widgets/RoundRobinSelection.hpp @@ -0,0 +1,16 @@ +#ifndef ROUNDROBINSELECTION_HPP +#define ROUNDROBINSELECTION_HPP + +#include "BeaconTxController.hpp" + +class QComboBox; +class QString; + +namespace RoundRobinSelection +{ + void initialize (QComboBox& combo, QString const& randomLabel); + BeaconTx::RoundRobinPolicy policy (QComboBox const& combo); + void setPolicy (QComboBox& combo, BeaconTx::RoundRobinPolicy const& policy); +} + +#endif diff --git a/widgets/SettingsDialogLayout.cpp b/widgets/SettingsDialogLayout.cpp new file mode 100644 index 00000000..6da2ba65 --- /dev/null +++ b/widgets/SettingsDialogLayout.cpp @@ -0,0 +1,264 @@ +#include "SettingsDialogLayout.hpp" + +#include <QApplication> +#include <QDialog> +#include <QEvent> +#include <QFrame> +#include <QHeaderView> +#include <QLayout> +#include <QObject> +#include <QPointer> +#include <QScrollArea> +#include <QScrollBar> +#include <QSizePolicy> +#include <QString> +#include <QTableView> +#include <QTabBar> +#include <QTabWidget> +#include <QTimer> +#include <QVBoxLayout> +#include <QWidget> + +#include "ui_Configuration.h" + +namespace +{ + char const scroll_area_marker[] = "wsjtxSettingsPageScrollArea"; + char const wheel_forwarder_marker[] = "wsjtxSettingsWheelForwarder"; + + class WheelEventForwarder final : public QObject + { + public: + WheelEventForwarder (QWidget * source, QScrollArea * target) + : QObject {source} + , target_ {target} + { + source->installEventFilter (this); + } + + protected: + bool eventFilter (QObject * watched, QEvent * event) override + { + if (event->type () == QEvent::Wheel && target_ + && (target_->horizontalScrollBar ()->maximum () + > target_->horizontalScrollBar ()->minimum () + || target_->verticalScrollBar ()->maximum () + > target_->verticalScrollBar ()->minimum ())) + { + event->ignore (); + QApplication::sendEvent (target_->viewport (), event); + return true; + } + + return QObject::eventFilter (watched, event); + } + + private: + QPointer<QScrollArea> target_; + }; + + QScrollArea * findPageScrollArea (QWidget * page) + { + if (!page) + { + return nullptr; + } + + for (auto * scroll_area : page->findChildren<QScrollArea *> (QString {}, Qt::FindDirectChildrenOnly)) + { + if (scroll_area->property (scroll_area_marker).toBool ()) + { + return scroll_area; + } + } + + return nullptr; + } + + QScrollArea * createScrollArea (QWidget * page, QWidget * content) + { + auto * scroll_area = new QScrollArea {page}; + scroll_area->setObjectName (page->objectName () + "_scroll_area"); + scroll_area->setProperty (scroll_area_marker, true); + scroll_area->setFrameShape (QFrame::NoFrame); + scroll_area->setFocusPolicy (Qt::NoFocus); + scroll_area->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding); + scroll_area->setSizeAdjustPolicy (QAbstractScrollArea::AdjustIgnored); + scroll_area->setHorizontalScrollBarPolicy (Qt::ScrollBarAsNeeded); + scroll_area->setVerticalScrollBarPolicy (Qt::ScrollBarAsNeeded); + scroll_area->setWidgetResizable (true); + scroll_area->setWidget (content); + scroll_area->viewport ()->setFocusPolicy (Qt::NoFocus); + scroll_area->viewport ()->setBackgroundRole (page->backgroundRole ()); + scroll_area->viewport ()->setAutoFillBackground (true); + scroll_area->horizontalScrollBar ()->setFocusPolicy (Qt::NoFocus); + scroll_area->verticalScrollBar ()->setFocusPolicy (Qt::NoFocus); + + QObject::connect (qApp, &QApplication::focusChanged, scroll_area, + [scroll_area, content] (QWidget *, QWidget * focused) { + if (focused && (focused == content || content->isAncestorOf (focused))) + { + QPointer<QWidget> target {focused}; + QTimer::singleShot (0, scroll_area, [scroll_area, content, target] { + if (target && (target == content || content->isAncestorOf (target))) + { + auto const margin = qMax (4, scroll_area->fontMetrics ().height () / 2); + scroll_area->ensureWidgetVisible (target, margin, margin); + } + }); + } + }); + + return scroll_area; + } + + QWidget * createContent (QWidget * page) + { + auto * content = new QWidget; + content->setObjectName (page->objectName () + "_scroll_content"); + content->setFocusPolicy (Qt::NoFocus); + content->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding); + content->setBackgroundRole (page->backgroundRole ()); + content->setAutoFillBackground (true); + return content; + } + + QScrollArea * installPageScrollArea (QWidget * page) + { + if (!page) + { + return nullptr; + } + + if (auto * scroll_area = findPageScrollArea (page)) + { + return scroll_area; + } + + auto * content_layout = page->layout (); + if (!content_layout) + { + return nullptr; + } + + auto * content = createContent (page); + content->setLayout (content_layout); + content_layout->setSizeConstraint (QLayout::SetMinAndMaxSize); + + auto * scroll_area = createScrollArea (page, content); + + auto * page_layout = new QVBoxLayout {page}; + page_layout->setContentsMargins (0, 0, 0, 0); + page_layout->setSpacing (0); + page_layout->addWidget (scroll_area); + + return scroll_area; + } + + void keepOneTableRowVisible (QTableView * table) + { + if (!table) + { + return; + } + + auto const header_height = table->horizontalHeader ()->sizeHint ().height (); + auto const row_height = table->fontMetrics ().height () + 4; + table->setMinimumHeight (header_height + row_height + 2 * table->frameWidth ()); + } + + void forwardWheelEvents (QWidget * source, QScrollArea * target) + { + if (!source || !target || source->property (wheel_forwarder_marker).toBool ()) + { + return; + } + + source->setProperty (wheel_forwarder_marker, true); + new WheelEventForwarder {source, target}; + } +} + +void SettingsDialogLayout::install (Ui::configuration_dialog const& ui) +{ + for (auto * page : { + ui.general_tab, + ui.radio_tab, + ui.audio_tab, + ui.reporting_tab, + ui.colors_tab, + ui.advanced_tab, + ui.alerts_tab, + ui.filters_tab, + }) + { + installPageScrollArea (page); + } + + keepOneTableRowVisible (ui.frequencies_table_view); + keepOneTableRowVisible (ui.stations_table_view); + forwardWheelEvents (ui.highlighting_list_view->viewport (), + findPageScrollArea (ui.colors_tab)); + ui.configuration_tabs->tabBar ()->setUsesScrollButtons (true); +} + +QScrollArea * SettingsDialogLayout::pageScrollArea (QWidget * page) +{ + return findPageScrollArea (page); +} + +QSize SettingsDialogLayout::preferredWindowSize (QDialog& dialog, + Ui::configuration_dialog const& ui) +{ + dialog.ensurePolished (); + dialog.layout ()->activate (); + auto required_size = dialog.sizeHint (); + auto * selected_page = ui.configuration_tabs->currentWidget (); + int tallest_page = 0; + int next_tallest_page = 0; + + for (auto * page : { + ui.general_tab, + ui.radio_tab, + ui.audio_tab, + ui.reporting_tab, + ui.colors_tab, + ui.advanced_tab, + ui.alerts_tab, + ui.filters_tab, + }) + { + ui.configuration_tabs->setCurrentWidget (page); + dialog.layout ()->activate (); + auto * scroll_area = findPageScrollArea (page); + auto const chrome_size = dialog.size () - scroll_area->viewport ()->size (); + auto const page_size = scroll_area->widget ()->minimumSizeHint () + chrome_size; + required_size.setWidth (qMax (required_size.width (), + page_size.width () + + scroll_area->verticalScrollBar ()->sizeHint ().width ())); + if (page_size.height () > tallest_page) + { + next_tallest_page = tallest_page; + tallest_page = page_size.height (); + } + else + { + next_tallest_page = qMax (next_tallest_page, page_size.height ()); + } + } + + ui.configuration_tabs->setCurrentWidget (selected_page); + // The tallest page can scroll without making every other tab waste that height. + required_size.setHeight (qMax (required_size.height (), next_tallest_page)); + return required_size; +} + +QSize SettingsDialogLayout::boundedWindowSize (QSize requested, QSize available, + QMargins frame_margins) +{ + available.rwidth () -= frame_margins.left () + frame_margins.right (); + available.rheight () -= frame_margins.top () + frame_margins.bottom (); + available.setWidth (qMax (1, available.width ())); + available.setHeight (qMax (1, available.height ())); + return requested.boundedTo (available); +} diff --git a/widgets/SettingsDialogLayout.hpp b/widgets/SettingsDialogLayout.hpp new file mode 100644 index 00000000..567875a5 --- /dev/null +++ b/widgets/SettingsDialogLayout.hpp @@ -0,0 +1,24 @@ +#ifndef SETTINGS_DIALOG_LAYOUT_HPP_ +#define SETTINGS_DIALOG_LAYOUT_HPP_ + +#include <QMargins> +#include <QSize> + +class QScrollArea; +class QDialog; +class QWidget; + +namespace Ui +{ + class configuration_dialog; +} + +namespace SettingsDialogLayout +{ + void install (Ui::configuration_dialog const& ui); + QScrollArea * pageScrollArea (QWidget * page); + QSize preferredWindowSize (QDialog& dialog, Ui::configuration_dialog const& ui); + QSize boundedWindowSize (QSize requested, QSize available, QMargins frame_margins); +} + +#endif diff --git a/widgets/SpecOpLabel.cpp b/widgets/SpecOpLabel.cpp new file mode 100644 index 00000000..c869262e --- /dev/null +++ b/widgets/SpecOpLabel.cpp @@ -0,0 +1,27 @@ +#include "widgets/SpecOpLabel.h" + +#include <QCoreApplication> + +namespace SpecOpLabel +{ + QString label (SpecialOperatingActivity specialOperation, bool ncccSprint, bool superFox) + { + if (SpecialOperatingActivity::FOX == specialOperation) { + return superFox ? QCoreApplication::translate("MainWindow", "Super Fox") + : QCoreApplication::translate("MainWindow", "Fox"); + } + if (SpecialOperatingActivity::HOUND == specialOperation) { + return superFox ? QCoreApplication::translate("MainWindow", "Super Hound") + : QCoreApplication::translate("MainWindow", "Hound"); + } + if (SpecialOperatingActivity::NA_VHF == specialOperation && ncccSprint) return "NCCC Sprint"; + if (SpecialOperatingActivity::NA_VHF == specialOperation) return "NA VHF"; + if (SpecialOperatingActivity::EU_VHF == specialOperation) return "EU VHF"; + if (SpecialOperatingActivity::FIELD_DAY == specialOperation) return "Field Day"; + if (SpecialOperatingActivity::RTTY == specialOperation) return "FT RU"; + if (SpecialOperatingActivity::WW_DIGI == specialOperation) return "WW Digi"; + if (SpecialOperatingActivity::ARRL_DIGI == specialOperation) return "ARRL Digi"; + if (SpecialOperatingActivity::Q65_PILEUP == specialOperation) return "Q65 Pileup"; + return {}; + } +} diff --git a/widgets/SpecOpLabel.h b/widgets/SpecOpLabel.h new file mode 100644 index 00000000..9777e778 --- /dev/null +++ b/widgets/SpecOpLabel.h @@ -0,0 +1,13 @@ +#ifndef SPECOPLABEL_H +#define SPECOPLABEL_H + +#include <QString> + +#include "SpecialOperatingActivity.hpp" + +namespace SpecOpLabel +{ + QString label (SpecialOperatingActivity specialOperation, bool ncccSprint, bool superFox = false); +} + +#endif diff --git a/widgets/SplashScreen.cpp b/widgets/SplashScreen.cpp index 827153dc..365fbafa 100644 --- a/widgets/SplashScreen.cpp +++ b/widgets/SplashScreen.cpp @@ -4,6 +4,8 @@ #include <QVBoxLayout> #include <QCheckBox> #include <QCoreApplication> +#include <QEvent> +#include <QKeyEvent> #include "revision_utils.hpp" #include "pimpl_impl.hpp" @@ -28,7 +30,24 @@ SplashScreen::SplashScreen () : QSplashScreen {QPixmap {":/splash.png"}, Qt::WindowStaysOnTopHint} { setLayout (&m_->main_layout_); - showMessage ("<h2>" + QString {"WSJT-X v" + + + setObjectName ("SplashScreen"); + setWindowTitle (QCoreApplication::translate ("SplashScreen", "WSJT-Xâ„¢ — Welcome")); + setAccessibleName (windowTitle ()); + setAccessibleDescription ( + QCoreApplication::translate ("SplashScreen", + "WSJT-X startup information. Press Escape to close.")); + m_->checkbox_.setObjectName ("doNotShowSplashAgain"); + m_->checkbox_.setAccessibleName (m_->checkbox_.text ()); + + // A QSplashScreen is a non-activating window and never becomes the key + // window, so a key press event override would never fire. Filter the + // application instead so Escape dismisses the splash regardless of which + // window holds focus, giving keyboard and assistive-tech users a dismiss + // path that the mouse-only click-to-dismiss does not. + QCoreApplication::instance ()->installEventFilter (this); + + showMessage ("<h2>" + QString {"WSJT-Xâ„¢ v" + QCoreApplication::applicationVersion() + " " + revision ()}.simplified () + "</h2>" "Send issue reports to https://wsjtx.groups.io, and be sure to save .wav<br />" @@ -44,3 +63,14 @@ SplashScreen::SplashScreen () SplashScreen::~SplashScreen () { } + +bool SplashScreen::eventFilter (QObject * object, QEvent * event) +{ + if (isVisible () && QEvent::KeyPress == event->type () + && Qt::Key_Escape == static_cast<QKeyEvent *> (event)->key ()) + { + close (); + return true; + } + return QSplashScreen::eventFilter (object, event); +} diff --git a/widgets/SplashScreen.hpp b/widgets/SplashScreen.hpp index 2ec3238c..9c7e9771 100644 --- a/widgets/SplashScreen.hpp +++ b/widgets/SplashScreen.hpp @@ -5,6 +5,8 @@ #include "pimpl_h.hpp" +class QEvent; + class SplashScreen final : public QSplashScreen { @@ -16,6 +18,9 @@ public: Q_SIGNAL void disabled (); +protected: + bool eventFilter (QObject *, QEvent *) override; + private: class impl; pimpl<impl> m_; diff --git a/widgets/TxDriveSlider.cpp b/widgets/TxDriveSlider.cpp new file mode 100644 index 00000000..d568b89a --- /dev/null +++ b/widgets/TxDriveSlider.cpp @@ -0,0 +1,132 @@ +#include "TxDriveSlider.hpp" + +#include <QPaintEvent> +#include <QPainter> +#include <QStyle> +#include <QStyleOptionSlider> + +namespace +{ + constexpr int minor_tick_interval = 50; +} + +TxDriveSlider::TxDriveSlider (QWidget * parent) + : QSlider {parent} +{ +#if defined(Q_OS_WIN) || defined(Q_OS_MACOS) + // One-sided ticks preserve the native ticked handle and matching hit geometry. + setTickPosition (QSlider::TicksRight); + setTickInterval (minor_tick_interval); +#endif +} + +QSize TxDriveSlider::sizeHint () const +{ + auto size = QSlider::sizeHint (); +#if !defined(Q_OS_WIN) && !defined(Q_OS_MACOS) + size.rwidth () += 12; +#endif + return size; +} + +QSize TxDriveSlider::minimumSizeHint () const +{ + auto size = QSlider::minimumSizeHint (); +#if !defined(Q_OS_WIN) && !defined(Q_OS_MACOS) + size.rwidth () += 12; +#endif + return size; +} + +void TxDriveSlider::paintEvent (QPaintEvent * event) +{ +#ifdef Q_OS_WIN + if (!property ("wsjtxDarkStyle").toBool ()) + { + QSlider::paintEvent (event); + return; + } +#endif + constexpr int major_tick_interval = 100; + if (orientation () != Qt::Vertical || maximum () <= minimum ()) + { + QSlider::paintEvent (event); + return; + } + + QStyleOptionSlider option; + initStyleOption (&option); + + auto const groove = style ()->subControlRect (QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, this); +#if defined(Q_OS_WIN) || defined(Q_OS_MACOS) + // Style-reported handle endpoints keep painting aligned with interaction geometry. + auto endpoint = option; + endpoint.sliderPosition = endpoint.sliderValue = minimum (); + auto const minimum_y = style ()->subControlRect (QStyle::CC_Slider, &endpoint, QStyle::SC_SliderHandle, this).center ().y (); + endpoint.sliderPosition = endpoint.sliderValue = maximum (); + auto const maximum_y = style ()->subControlRect (QStyle::CC_Slider, &endpoint, QStyle::SC_SliderHandle, this).center ().y (); + auto const groove_top = qMin (minimum_y, maximum_y); + auto const span = qAbs (maximum_y - minimum_y); +#else + auto const handle = style ()->subControlRect (QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, this); + auto const span = qMax (0, groove.height () - handle.height ()); + auto const groove_top = groove.top () + handle.height () / 2; +#endif + if (span == 0) + { + QSlider::paintEvent (event); + return; + } + + auto const groove_x = groove.center ().x (); + auto const groove_bottom = groove_top + span; + auto const tick_gap = 4; + + QPainter painter {this}; + + auto const palette_mid = palette ().color (QPalette::Mid); + // Some application styles use an accent color for Mid. This scale conveys + // attenuation positions, not a filled level, so retain its lightness while + // removing hue and saturation. + auto const neutral_mid = QColor::fromHsl (0, 0, palette_mid.lightness ()); + auto groove_color = neutral_mid; + groove_color.setAlpha (120); + painter.setRenderHint (QPainter::Antialiasing, true); + painter.setPen (QPen {groove_color, 3, Qt::SolidLine, Qt::RoundCap}); + painter.drawLine (groove_x, groove_top, groove_x, groove_bottom); + + auto tick_color = neutral_mid; + tick_color.setAlpha (190); + painter.setRenderHint (QPainter::Antialiasing, false); + painter.setPen (QPen {tick_color, 1}); + + for (auto value = minimum (); value <= maximum (); value += minor_tick_interval) + { + auto const position = QStyle::sliderPositionFromValue (minimum (), maximum (), value, span, option.upsideDown); + auto const y = groove_top + position; + auto const is_major_tick = value % major_tick_interval == 0; + auto const tick_length = is_major_tick ? 5 : 3; + painter.drawLine (groove_x - tick_gap - tick_length, y, groove_x - tick_gap, y); +#if !defined(Q_OS_WIN) && !defined(Q_OS_MACOS) + painter.drawLine (groove_x + tick_gap, y, groove_x + tick_gap + tick_length, y); +#endif + } + + option.subControls = QStyle::SC_SliderHandle; +#if !defined(Q_OS_MACOS) + // QStyleSheetStyle may paint its highlighted add/sub-page even when only the + // handle subcontrol is requested. Keep that painting inside the handle so it + // cannot cover the neutral attenuation scale. + auto const handle_rect = style ()->subControlRect ( + QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, this); + painter.setClipRect (handle_rect, Qt::IntersectClip); +#else + if (property ("wsjtxDarkStyle").toBool ()) + { + auto const handle_rect = style ()->subControlRect ( + QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, this); + painter.setClipRect (handle_rect, Qt::IntersectClip); + } +#endif + style ()->drawComplexControl (QStyle::CC_Slider, &option, &painter, this); +} diff --git a/widgets/TxDriveSlider.hpp b/widgets/TxDriveSlider.hpp new file mode 100644 index 00000000..73815f31 --- /dev/null +++ b/widgets/TxDriveSlider.hpp @@ -0,0 +1,21 @@ +// -*- Mode: C++ -*- +#ifndef TXDRIVESLIDER_HPP +#define TXDRIVESLIDER_HPP + +#include <QSlider> + +class TxDriveSlider final + : public QSlider +{ + Q_OBJECT + +public: + explicit TxDriveSlider (QWidget * parent = nullptr); + QSize sizeHint () const override; + QSize minimumSizeHint () const override; + +protected: + void paintEvent (QPaintEvent * event) override; +}; + +#endif // TXDRIVESLIDER_HPP diff --git a/widgets/WaterfallScale.hpp b/widgets/WaterfallScale.hpp new file mode 100644 index 00000000..99125d96 --- /dev/null +++ b/widgets/WaterfallScale.hpp @@ -0,0 +1,129 @@ +#ifndef WATERFALL_SCALE_HPP_ +#define WATERFALL_SCALE_HPP_ + +#include <algorithm> +#include <cmath> + +#include <QString> +#include <QVector> + +class WaterfallScale +{ +public: + struct GridLayout + { + int majorSpacingHz; + double pixelsPerDivision; + int overlayDivisionCount; + int scaleDivisionCount; + double firstMajorDivisionOffset; + int verticalGridOffsetPixels; + int minorDivisionCount; + QVector<QString> labels; + }; + + int width() const { return m_width; } + void setWidth(int width) { m_width = std::max(0, width); } + + int startHz() const { return m_startHz; } + void setStartHz(int startHz) { m_startHz = startHz; } + + int binsPerPixel() const { return m_binsPerPixel; } + void setBinsPerPixel(int binsPerPixel) + { + m_binsPerPixel = std::max(1, binsPerPixel); + } + + double fftBinWidthHz() const { return m_fftBinWidthHz; } + void setFftBinWidthHz(double fftBinWidthHz) + { + m_fftBinWidthHz = fftBinWidthHz; + } + + double hzPerPixel() const + { + return m_binsPerPixel * m_fftBinWidthHz; + } + + float spanHz() const + { + return float(m_width * hzPerPixel()); + } + + int xFromFreqHz(float frequencyHz) const + { + auto const span = spanHz(); + if(!(span > 0.0f)) return 0; + + int x = int(m_width * (frequencyHz - m_startHz) / span + 0.5); + if(x < 0) return 0; + if(x > m_width) return m_width; + return x; + } + + float freqHzFromX(int x) const + { + return float(m_startHz + x * m_binsPerPixel * m_fftBinWidthHz); + } + + int maxFreqHz() const + { + return freqHzFromX(xFromFreqHz(5000.0f)); + } + + GridLayout gridLayout() const + { + auto const span = spanHz(); + int majorSpacingHz = 10; + if(span > 100) majorSpacingHz = 20; + if(span > 250) majorSpacingHz = 50; + if(span > 500) majorSpacingHz = 100; + if(span > 1000) majorSpacingHz = 200; + if(span > 2500) majorSpacingHz = 500; + + double const pixelsPerDivision = majorSpacingHz / hzPerPixel(); + int const scaleDivisionCount = divisionCount( + m_width * hzPerPixel() / majorSpacingHz); + int const overlayDivisionCount = scaleDivisionCount + 1; + + double startDivision = double(m_startHz) / majorSpacingHz; + startDivision -= int(startDivision); + int const verticalGridOffsetPixels = + startDivision * pixelsPerDivision + 0.5; + + int labelFrequency = + (m_startHz + majorSpacingHz - 1) / majorSpacingHz; + labelFrequency *= majorSpacingHz; + double const firstMajorDivisionOffset = + double(labelFrequency - m_startHz) / majorSpacingHz; + + QVector<QString> labels(scaleDivisionCount + 1); + for(int i = 0; i <= scaleDivisionCount; ++i) { + labels[i].setNum(labelFrequency); + labelFrequency += majorSpacingHz; + } + + return {majorSpacingHz, + pixelsPerDivision, + overlayDivisionCount, + scaleDivisionCount, + firstMajorDivisionOffset, + verticalGridOffsetPixels, + majorSpacingHz == 200 ? 4 : 5, + labels}; + } + +private: + static int divisionCount(double divisions) + { + constexpr double tolerance = 0.0001; + return int(std::ceil(divisions - tolerance)); + } + + int m_width {0}; + int m_startHz {0}; + int m_binsPerPixel {1}; + double m_fftBinWidthHz {1500.0 / 2048.0}; +}; + +#endif diff --git a/widgets/about.cpp b/widgets/about.cpp index 59400929..adf3ab91 100644 --- a/widgets/about.cpp +++ b/widgets/about.cpp @@ -13,23 +13,24 @@ CAboutDlg::CAboutDlg(QWidget *parent) : { ui->setupUi(this); - ui->labelTxt->setText ("<h2>" + QString {"WSJT-X v" + ui->labelTxt->setText ("<h2>" + QString {"WSJT-Xâ„¢ v" + QCoreApplication::applicationVersion () - + " " + revision ()}.simplified () + "<br />" + + " " + display_revision ()}.simplified () + "</h2>" - "WSJT-X implements a number of digital modes designed for <br />" + "WSJT-Xâ„¢ implements a number of digital modes designed for <br />" "weak-signal Amateur Radio communication. <br /><br />" "© 2001-2026 by Joe Taylor, K1JT, Bill Somerville, G4WJS, <br />" "Steve Franke, K9AN, Nico Palermo, IV3NWV, <br />" "Uwe Risse, DG2YCB, Brian Moran, N9ADG, <br />" "Roger Rehr, W3SZ, John Nelson, G4KLA, <br />" - "Charlie Suckling, DL3WDG, and Terrell Deppe, KJ5HST <br /><br />" + "Charlie Suckling, DL3WDG, Terrell Deppe, KJ5HST,<br />" + "and David Christle, KD0BTO <br /><br />" "We gratefully acknowledge contributions from AC6SL, AE4JY,<br />" "DF2ET, DJ0OT, DL3WDG, EA4AC, G4KLA, IW3RAB, JA7UDE,<br />" "K3WYC, KA1GT, KA6MAL, KA9Q, KB1ZMX, KD6EKQ, KG4IYS, KI7MT,<br />" "KK1D, ND0B, PY1ZRJ, PY2SDR, VE1SKY, VK3ACF, VK4BDJ,<br />" "VK7MO, VR2UPU, W3DJS, W4TI, W4TV, and W9MDB.<br /><br />" - "WSJT-X is licensed under the terms of Version 3 <br />" + "WSJT-Xâ„¢ 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>" diff --git a/widgets/about.ui b/widgets/about.ui index 84157c4d..47b19451 100644 --- a/widgets/about.ui +++ b/widgets/about.ui @@ -6,7 +6,7 @@ <enum>Qt::NonModal</enum> </property> <property name="windowTitle"> - <string>About WSJT-X</string> + <string>About WSJT-Xâ„¢</string> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> diff --git a/widgets/activeStations.cpp b/widgets/activeStations.cpp index 7353501c..8d7946bb 100644 --- a/widgets/activeStations.cpp +++ b/widgets/activeStations.cpp @@ -22,7 +22,7 @@ ActiveStations::ActiveStations(QSettings * settings, QFont const& font, QWidget ui->RecentStationsPlainTextEdit->setReadOnly (true); changeFont (font); read_settings (); - ui->header_label2->setText(" N Call Grid Az S/N Freq Tx Age Pts"); + setupUi(DisplayMode::Standard); connect(ui->cbReadyOnly, SIGNAL(toggled(bool)), this, SLOT(on_cbReadyOnly_toggled(bool))); connect(ui->cbWantedOnly, SIGNAL(toggled(bool)), this, SLOT(on_cbWantedOnly_toggled(bool))); connect(ui->RecentStationsPlainTextEdit, SIGNAL(cursorPositionChanged()), this, SLOT(on_textEdit_clicked())); @@ -57,7 +57,7 @@ void ActiveStations::addLine(QString line) { m_textbuffer.append(i.value()); ++i; } - this->displayRecentStations(m_mode, m_textbuffer); + this->displayRecentStations(m_displayMode, m_textbuffer); } void ActiveStations::read_settings () @@ -67,7 +67,7 @@ void ActiveStations::read_settings () ui->sbMaxRecent->setValue(settings_->value("MaxRecent",10).toInt()); ui->sbMaxAge->setValue(settings_->value("MaxAge",10).toInt()); ui->cbReadyOnly->setChecked(settings_->value("ReadyOnly",false).toBool()); - ui->cbWantedOnly->setChecked(settings_->value("# WantedOnly",false).toBool()); + ui->cbWantedOnly->setChecked(settings_->value("WantedOnly",false).toBool()); } void ActiveStations::write_settings () @@ -80,44 +80,39 @@ void ActiveStations::write_settings () settings_->setValue("WantedOnly",ui->cbWantedOnly->isChecked()); } -void ActiveStations::setupUi(QString mode) { - if(mode!=m_mode) { - m_mode=mode; - ui->cbReadyOnly->setText(" Ready only"); - if(m_mode=="Q65") { - ui->header_label2->setText(" N Frx Fsked S/N Q65 Call Grid Tx Age"); - ui->label->setText("QSOs:"); - ui->cbReadyOnly->setText("* CQ only"); - } else if(m_mode=="Q65-pileup") { - ui->header_label2->setText(" N Freq Call Grid El Age(h)"); - ui->cbWantedOnly->setText(QCoreApplication::translate("ActiveStations", "Wanted only", nullptr)); - } else if(m_mode=="Fox Mode" || m_mode=="SuperFox Mode" ) { - ui->header_label2->setText(" UTC dB DT Freq " + tr("Message")); - ui->cbWantedOnly->setText(QCoreApplication::translate("ActiveStations", "My call only", nullptr)); - this->setClickOK(true); - } else { - ui->header_label2->setText(" N Call Grid Az S/N Freq Tx Age Pts"); - ui->label->setText("Rate:"); - ui->cbWantedOnly->setText(QCoreApplication::translate("ActiveStations", "Wanted only", nullptr)); - } - bool b=(m_mode.left(3)=="Q65"); - bool is_fox_mode =(m_mode=="Fox Mode"); - ui->bandChanges->setVisible(!b && !is_fox_mode); - ui->cbReadyOnly->setVisible(m_mode != "Q65-pileup" && !is_fox_mode); - ui->cbWantedOnly->setVisible(m_mode != "Q65-pileup"); // this is used for "My call only" in Fox mode - ui->label_2->setVisible(!b && !is_fox_mode); - ui->label_3->setVisible(!b && !is_fox_mode); - ui->score->setVisible(!b && !is_fox_mode); - ui->sbMaxRecent->setVisible(!b && !is_fox_mode); - - b=(m_mode!="Q65-pileup" && !is_fox_mode); - ui->sbMaxAge->setVisible(b); - ui->label->setVisible(b); - ui->rate->setVisible(b); +void ActiveStations::setupUi(DisplayMode mode) { + if (mode != m_displayMode && mode == DisplayMode::Fox) setClickOK(true); + m_displayMode=mode; + ui->cbReadyOnly->setText(" Ready only"); + ui->cbWantedOnly->setText(tr("# Wanted only")); + ui->label->setText("Rate:"); + if(mode==DisplayMode::Q65) { + ui->header_label2->setText(" N Frx Fsked S/N Q65 Call Grid Tx Age"); + ui->label->setText("QSOs:"); + ui->cbReadyOnly->setText("* CQ only"); + } else if(mode==DisplayMode::Q65Pileup) { + ui->header_label2->setText(" N Freq Call Grid El Age(h)"); + } else if(mode==DisplayMode::Fox) { + ui->header_label2->setText(" UTC dB DT Freq " + tr("Message")); + ui->cbWantedOnly->setText(tr("My call only")); + } else { + ui->header_label2->setText(" N Call Grid Az S/N Freq Tx Age Pts"); } -} - -void ActiveStations::displayRecentStations(QString mode, QString const& t) + bool const standard = mode == DisplayMode::Standard; + bool const numbered = standard || mode == DisplayMode::Q65; + ui->bandChanges->setVisible(standard); + ui->cbReadyOnly->setVisible(numbered); + ui->cbWantedOnly->setVisible(mode != DisplayMode::Q65Pileup); + ui->label_2->setVisible(standard); + ui->label_3->setVisible(standard); + ui->score->setVisible(standard); + ui->sbMaxRecent->setVisible(standard); + ui->sbMaxAge->setVisible(numbered); + ui->label->setVisible(numbered); + ui->rate->setVisible(numbered); +} + +void ActiveStations::displayRecentStations(DisplayMode mode, QString const& t) { setupUi(mode); @@ -125,31 +120,37 @@ void ActiveStations::displayRecentStations(QString mode, QString const& t) m_clickOK=false; ui->RecentStationsPlainTextEdit->setPlainText(t); -//White background for Q65-60x decodes, yellow for Q65-30x: int i0=0; int i1=0; - int npos=0; int nlines=t.count("\n"); QTextCursor cursor=ui->RecentStationsPlainTextEdit->textCursor(); QTextCharFormat fmt; + + // Use a regular expression matcher to find the text pattern within each line bounds + QRegularExpression regex(" 30[ABCD] "); + for(int i=0; i<nlines; i++) { i1=t.indexOf("\n",i0); - npos=t.indexOf(QRegularExpression(" 30[ABCD] "), i0); - if(npos>0) { - cursor.setPosition(npos); - cursor.select(QTextCursor::LineUnderCursor); + // Isolate the current line to check for the match + QString currentLine = t.mid(i0, i1 - i0); + bool hasMatch = currentLine.contains(regex); + + // Move the cursor to the current line we are processing + cursor.setPosition(i0); + cursor.select(QTextCursor::LineUnderCursor); + + if(hasMatch) { fmt.setBackground(QBrush(Qt::yellow)); fmt.setForeground(QBrush(Qt::black)); } else { - cursor.setPosition(i0+10); - cursor.select(QTextCursor::LineUnderCursor); - fmt.clearForeground(); - fmt.clearBackground(); + // Explicitly force the background back to white + fmt.setBackground(QBrush(Qt::white)); + fmt.setForeground(QBrush(Qt::black)); } + cursor.setCharFormat(fmt); i0=i1+1; } - m_clickOK=bClickOK; } @@ -175,7 +176,7 @@ void ActiveStations::on_textEdit_clicked() if(text!="") { int nline=text.left(2).toInt(); if(QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) nline=-nline; - if ("Fox Mode" != m_mode && "SuperFox Mode" != m_mode) + if (DisplayMode::Fox != m_displayMode) emit callSandP(nline); else emit queueActiveWindowHound(text); diff --git a/widgets/activeStations.h b/widgets/activeStations.h index 60cdc700..6e3cd53c 100644 --- a/widgets/activeStations.h +++ b/widgets/activeStations.h @@ -18,10 +18,12 @@ class ActiveStations Q_OBJECT public: + enum class DisplayMode { Standard, Q65, Q65Pileup, Fox }; + explicit ActiveStations(QSettings *, QFont const&, QWidget * parent = 0); ~ActiveStations(); - void displayRecentStations(QString mode, QString const&); - void setupUi(QString display_mode); + void displayRecentStations(DisplayMode, QString const&); + void setupUi(DisplayMode); void changeFont (QFont const&); int maxRecent(); int maxAge(); @@ -51,7 +53,7 @@ private: Q_SLOT void on_cbWantedOnly_toggled(bool b); Q_SLOT void on_textEdit_clicked(); - QString m_mode=""; + DisplayMode m_displayMode = DisplayMode::Standard; QSettings * settings_; QString m_textbuffer=""; // F/H mode band decodes QMap<int, QString> m_decodes_by_frequency; // store decodes for F/H band awareness by frequency diff --git a/widgets/astro.cpp b/widgets/astro.cpp index c96eee6e..dcdbac44 100644 --- a/widgets/astro.cpp +++ b/widgets/astro.cpp @@ -1,7 +1,5 @@ #include "astro.h" -#include <stdio.h> - #include <QApplication> #include <QFile> #include <QTextStream> @@ -13,8 +11,6 @@ #include <QDebug> #include <math.h> -#include "commons.h" -#include "MessageBox.hpp" #include "Configuration.hpp" #include "SettingsGroup.hpp" #include "qt_helpers.hpp" @@ -32,7 +28,15 @@ extern "C" { int * ndop, int * ndop00, double * ramoon, double * decmoon, double * dgrd, double * poloffset, double * xnr, bool extraazel, double * techo, double * width1, double * width2, bool bTx, const char * AzElFileName, - const char * jpleph); + const char * jpleph, int * ephemeris_result); +} + +namespace +{ + constexpr int ephemeris_jpl = 0; + constexpr int ephemeris_analytic_fallback = 1; + constexpr int ephemeris_invalid_input = 2; + constexpr int ephemeris_unavailable = 3; } Astro::Astro(QSettings * settings, Configuration const * configuration, QWidget * parent) @@ -110,7 +114,7 @@ auto Astro::astroUpdate(QDateTime const& t, QString const& mygrid, QString const Frequency freq_moon {freq}; double azsun,elsun,azmoon,elmoon,azmoondx,elmoondx; double ramoon,decmoon,dgrd,poloffset,xnr,techo,width1,width2; - int ntsky; + int ntsky, ephemeris_result; QString date {t.date().toString("yyyy MMM dd").trimmed ()}; QString utc {t.time().toString().trimmed ()}; int nyear {t.date().year()}; @@ -125,15 +129,56 @@ auto Astro::astroUpdate(QDateTime const& t, QString const& mygrid, QString const auto const& jpleph = configuration_->data_dir ().absoluteFilePath ("JPLEPH"); SettingsGroup g (settings_, "Configuration"); bool extraazel=settings_->value("AzElExtraLines",false).toBool(); + + // changed argument from &dgrd to &m_dgrd added for Bob KA1GT astrosub(nyear, month, nday, uth, static_cast<double> (freq_moon), mygrid.toLatin1 ().data (), hisgrid.toLatin1().data(), &azsun, &elsun, &azmoon, &elmoon, &azmoondx, &elmoondx, &ntsky, &m_dop, &m_dop00, &ramoon, &decmoon, - &dgrd, &poloffset, &xnr, extraazel, &techo, &width1, &width2, + &m_dgrd, &poloffset, &xnr, extraazel, &techo, &width1, &width2, bTx, AzElFileName.toLocal8Bit ().constData (), - jpleph.toLocal8Bit ().constData ()); + jpleph.toLocal8Bit ().constData (), &ephemeris_result); + + auto report_ephemeris_transition = [this] (int result) + { + if (result == m_ephemeris_result) + { + return; + } + if (result == ephemeris_analytic_fallback) + { + qWarning () << "JPL ephemeris unavailable; using analytic fallback"; + } + else if (result == ephemeris_invalid_input) + { + qWarning () << "Invalid astronomical date or time"; + } + else if (result == ephemeris_unavailable) + { + qWarning () << "No valid lunar ephemeris result"; + } + else if (result == ephemeris_jpl && m_ephemeris_result >= 0) + { + qInfo () << "JPL ephemeris available again"; + } + m_ephemeris_result = result; + }; + + report_ephemeris_transition (ephemeris_result); + if (ephemeris_result == ephemeris_invalid_input) + { + ui_->text_label->setText (" " + date + "\nUTC: " + utc + + "\nEphem: Invalid input"); + return {}; + } + if (ephemeris_result == ephemeris_unavailable) + { + ui_->text_label->setText (" " + date + "\nUTC: " + utc + + "\nEphem: Unavailable"); + return {}; + } QString message; { @@ -162,12 +207,16 @@ auto Astro::astroUpdate(QDateTime const& t, QString const& mygrid, QString const "SunAz: " << azsun << "\n" "SunEl: " << elsun << "\n" "Freq: " << freq / 1.e6 << "\n"; + if (ephemeris_result == ephemeris_analytic_fallback) + { + out << "Ephem: Analytic fallback\n"; + } if(freq>=5000000ull) { //Suppress data not relevant below VHF out << "Tsky: " << ntsky << "\n" "Dpol: " << poloffset << "\n" "MNR: " << xnr << "\n" "Dist: " << int((techo*149896)) << "\n" //wdg - "Dgrd: " << dgrd; + "Dgrd: " << m_dgrd; //changed dgrd to m_dgrd added for Bob KA1GT } } ui_->text_label->setText(message); @@ -265,7 +314,14 @@ auto Astro::astroUpdate(QDateTime const& t, QString const& mygrid, QString const &dgrd, &poloffset, &xnr, extraazel, &techo, &width1, &width2, bTx, nullptr, // don't overwrite azel.dat - jpleph.toLocal8Bit ().constData ()); + jpleph.toLocal8Bit ().constData (), &ephemeris_result); + + report_ephemeris_transition (ephemeris_result); + if (ephemeris_result == ephemeris_invalid_input + || ephemeris_result == ephemeris_unavailable) + { + return {}; + } FrequencyDelta offset {0}; switch (m_DopplerMethod) @@ -303,6 +359,12 @@ auto Astro::astroUpdate(QDateTime const& t, QString const& mygrid, QString const return correction; } +//added for Bob KA1GT +double Astro::getDgrd() const +{ + return m_dgrd; +} + void Astro::check_split () { /* TEMPORARILY DISABLE diff --git a/widgets/astro.h b/widgets/astro.h index f9d09154..e8caf79e 100644 --- a/widgets/astro.h +++ b/widgets/astro.h @@ -26,7 +26,8 @@ public: explicit Astro(QSettings * settings, Configuration const *, QWidget * parent = nullptr); ~Astro (); - + double getDgrd() const; // added for Bob KA1GT + struct Correction { Correction () @@ -99,13 +100,15 @@ private: Configuration const * configuration_; QScopedPointer<Ui::Astro> ui_; - double m_skedFreq; + double m_skedFreq {1296.065}; qint32 m_DopplerMethod; int m_dop; int m_dop00; + int m_ephemeris_result {-1}; int ibShift; //int m_dx_two_way_dop; bool astroStart = true; + double m_dgrd = 0.0; // added for Bob KA1GT }; inline diff --git a/widgets/displaytext.cpp b/widgets/displaytext.cpp index 2494928a..f4b4fcba 100644 --- a/widgets/displaytext.cpp +++ b/widgets/displaytext.cpp @@ -19,6 +19,8 @@ #include <QListIterator> #include <QRegularExpression> #include <QScrollBar> +#include <QToolButton> +#include <QResizeEvent> #include "Configuration.hpp" #include "Decoder/decodedtext.h" @@ -44,14 +46,29 @@ bool play_ITUZ = false; bool play_ITUZOB = false; bool muted = false; +namespace +{ + QRegularExpression const message_73_regexp {"^(73|RR73)$"}; + QRegularExpression const grid_regexp {"\\A(?![Rr]{2}73)[A-Ra-r]{2}[0-9]{2}([A-Xa-x]{2}){0,1}\\z"}; + // Trailing #? matches Q65's "copied last Tx" flag marker (e.g. "q3#"), + // appended after the usual AP-type/averaging-count qualifier. + QRegularExpression const ap_regexp {R"((?:\?\s)?(?:a[0-9]|q[0-9][0-9*]?#?)$)"}; +} + using SpecOp = Configuration::SpecialOperatingActivity; DisplayText::DisplayText(QWidget *parent) : QTextEdit(parent) , m_config {nullptr} , erase_action_ {new QAction {tr ("&Erase"), this}} + , pressed_button_ {Qt::NoButton} + , click_state_ {ClickState::None} , high_volume_ {false} + , sticky_scroll_enabled_ {false} + , following_live_activity_ {true} , modified_vertical_scrollbar_max_ {-1} + , return_to_live_button_ {new QToolButton {viewport ()}} + , live_scroll_position_ {0} { setReadOnly (true); setUndoRedoEnabled (false); @@ -70,6 +87,49 @@ DisplayText::DisplayText(QWidget *parent) delete menu; }); connect (erase_action_, &QAction::triggered, this, &DisplayText::erase); + + return_to_live_button_->setObjectName (QStringLiteral ("returnToLiveActivityButton")); + return_to_live_button_->setText (tr ("Return to live activity")); + return_to_live_button_->setToolButtonStyle (Qt::ToolButtonTextOnly); + return_to_live_button_->setAutoRaise (false); + return_to_live_button_->setFocusPolicy (Qt::StrongFocus); + return_to_live_button_->setCursor (Qt::ArrowCursor); + return_to_live_button_->setToolTip (tr ("Return to the live activity position")); + return_to_live_button_->setAccessibleDescription ( + tr ("Live activity is paused while earlier entries are visible.")); + return_to_live_button_->hide (); + connect (return_to_live_button_, &QToolButton::clicked, this, &DisplayText::scrollToLiveActivity); + connect (verticalScrollBar (), &QScrollBar::sliderMoved, this, &DisplayText::userScrolledTo); + connect (verticalScrollBar (), &QScrollBar::actionTriggered, this, [this] (int) { + userScrolledTo (verticalScrollBar ()->sliderPosition ()); + }); + connect (verticalScrollBar (), &QScrollBar::valueChanged, this, [this] (int) { + updateReturnToLiveButton (); + }); + connect (verticalScrollBar (), &QScrollBar::rangeChanged, this, &DisplayText::scrollRangeChanged); +} + +void DisplayText::set_configuration (Configuration const * configuration, bool high_volume) +{ + disconnect (vertical_scroll_connection_); + m_config = configuration; + high_volume_ = high_volume; + sticky_scroll_enabled_ = true; + following_live_activity_ = true; + live_scroll_position_ = verticalScrollBar ()->value (); + updateReturnToLiveButton (); +} + +void DisplayText::clear () +{ + if (click_state_ == ClickState::Captured) + { + click_state_ = ClickState::Canceled; + } + following_live_activity_ = true; + live_scroll_position_ = 0; + QTextEdit::clear (); + updateReturnToLiveButton (); } void DisplayText::erase () @@ -78,11 +138,95 @@ void DisplayText::erase () Q_EMIT erased (); } +bool DisplayText::decodesFromTop () const +{ + return high_volume_ && m_config && m_config->decodes_from_top (); +} + +void DisplayText::userScrolledTo (int position) +{ + if (sticky_scroll_enabled_) + { + following_live_activity_ = position == live_scroll_position_; + updateReturnToLiveButton (); + } +} + +void DisplayText::scrollRangeChanged (int minimum, int maximum) +{ + if (sticky_scroll_enabled_) + { + if (decodesFromTop ()) + { + live_scroll_position_ = qBound (minimum, live_scroll_position_, maximum); + } + else + { + live_scroll_position_ = maximum; + if (following_live_activity_) + { + verticalScrollBar ()->setValue (live_scroll_position_); + } + } + } + updateReturnToLiveButton (); +} + +void DisplayText::scrollToLiveActivity () +{ + auto * vertical_scroll_bar = verticalScrollBar (); + live_scroll_position_ = qBound (vertical_scroll_bar->minimum (), live_scroll_position_ + , vertical_scroll_bar->maximum ()); + following_live_activity_ = true; + vertical_scroll_bar->setValue (live_scroll_position_); + updateReturnToLiveButton (); +} + +void DisplayText::updateReturnToLiveButton () +{ + auto const * vertical_scroll_bar = verticalScrollBar (); + auto const hint = return_to_live_button_->sizeHint (); + auto const margin = 3; + auto const available_width = qMax (0, viewport ()->width () - 2 * margin); + auto const available_height = qMax (0, viewport ()->height () - 2 * margin); + auto const button_height = qMin (qMax (hint.height (), qMax (20, vertical_scroll_bar->sizeHint ().width ())) + , available_height); + auto const button_width = qMin (hint.width () + 8, available_width); + return_to_live_button_->resize (button_width, button_height); + return_to_live_button_->move (qMax (margin, viewport ()->width () - button_width - margin) + , qMax (margin, viewport ()->height () - button_height - margin)); + auto const wanted = sticky_scroll_enabled_ + && vertical_scroll_bar->maximum () > vertical_scroll_bar->minimum () + && !following_live_activity_ + && button_width > 0 + && button_height > 0; + if (wanted) + { + return_to_live_button_->raise (); + } + return_to_live_button_->setVisible (wanted); +} + +void DisplayText::resizeEvent (QResizeEvent * e) +{ + QTextEdit::resizeEvent (e); + updateReturnToLiveButton (); +} + void DisplayText::setContentFont(QFont const& font) { + auto const preserve_view = sticky_scroll_enabled_ && !following_live_activity_; + QTextCursor view_anchor; + int anchor_offset {0}; + if (preserve_view) + { + view_anchor = cursorForPosition (QPoint {1, 1}); + anchor_offset = cursorRect (view_anchor).top (); + } + char_font_ = font; - selectAll (); - auto cursor = textCursor (); + QTextCursor cursor {document ()}; + cursor.select (QTextCursor::Document); cursor.beginEditBlock (); auto char_format = cursor.charFormat (); char_format.setFont (char_font_); @@ -95,16 +239,66 @@ void DisplayText::setContentFont(QFont const& font) cursor.movePosition (QTextCursor::StartOfLine); cursor.endEditBlock (); - if (!high_volume_ || !m_config || !m_config->decodes_from_top ()) + auto * vertical_scroll_bar = verticalScrollBar (); + if (!sticky_scroll_enabled_ || following_live_activity_) { - setTextCursor (cursor); - ensureCursorVisible (); + if (!decodesFromTop ()) + { + setTextCursor (cursor); + ensureCursorVisible (); + } + if (sticky_scroll_enabled_) + { + live_scroll_position_ = vertical_scroll_bar->value (); + } + } + else + { + vertical_scroll_bar->setValue (vertical_scroll_bar->value () + + cursorRect (view_anchor).top () - anchor_offset); + if (!decodesFromTop ()) + { + live_scroll_position_ = vertical_scroll_bar->maximum (); + } } + updateReturnToLiveButton (); } -void DisplayText::mouseDoubleClickEvent(QMouseEvent *e) +void DisplayText::captureClick (QMouseEvent const * event) { - Q_EMIT selectCallsign(e->modifiers ()); + auto cursor = cursorForPosition (event->pos ()); + pressed_line_ = cursor.block ().text (); + cursor.select (QTextCursor::WordUnderCursor); + pressed_word_ = cursor.selectedText (); + pressed_button_ = event->button (); + click_state_ = ClickState::Captured; +} + +void DisplayText::mousePressEvent (QMouseEvent * event) +{ + captureClick (event); + QTextEdit::mousePressEvent (event); +} + +void DisplayText::mouseDoubleClickEvent (QMouseEvent * event) +{ + if (click_state_ == ClickState::Canceled) + { + pressed_button_ = Qt::NoButton; + click_state_ = ClickState::None; + return; + } + + if (click_state_ == ClickState::None || pressed_button_ != event->button ()) + { + captureClick (event); + } + + auto const line = pressed_line_; + auto const word = pressed_word_; + pressed_button_ = Qt::NoButton; + click_state_ = ClickState::None; + Q_EMIT selectCallsign (line, word, event->modifiers ()); } void DisplayText::insertLineSpacer(QString const& line) @@ -149,6 +343,15 @@ namespace void DisplayText::insertText(QString const& text, QColor bg, QColor fg , QString const& call1, QString const& call2, QTextCursor::MoveOperation location) { + auto const preserve_view = sticky_scroll_enabled_ && !following_live_activity_; + QTextCursor view_anchor; + int anchor_offset {0}; + if (preserve_view) + { + view_anchor = cursorForPosition (QPoint {1, 1}); + anchor_offset = cursorRect (view_anchor).top (); + } + auto cursor = textCursor (); cursor.movePosition (location); auto block_format = cursor.blockFormat (); @@ -208,7 +411,7 @@ void DisplayText::insertText(QString const& text, QColor bg, QColor fg { temp_format = format; cursor.insertText(text.mid (text_index, call_index - text_index), format); - if (pos.value ().second.isValid ()) + if (pos.value ().first.isValid ()) { temp_format.setBackground (pos.value ().first); } @@ -225,12 +428,31 @@ void DisplayText::insertText(QString const& text, QColor bg, QColor fg // position so viewport scrolled to left cursor.movePosition (QTextCursor::StartOfLine); - if (!high_volume_ || !m_config || !m_config->decodes_from_top ()) + if ((!sticky_scroll_enabled_ || following_live_activity_) && !decodesFromTop ()) { setTextCursor (cursor); ensureCursorVisible (); } document ()->setMaximumBlockCount (document ()->maximumBlockCount ()); + auto * vertical_scroll_bar = verticalScrollBar (); + if (preserve_view) + { + vertical_scroll_bar->setValue (vertical_scroll_bar->value () + + cursorRect (view_anchor).top () - anchor_offset); + } + if (sticky_scroll_enabled_) + { + if (decodesFromTop ()) + { + live_scroll_position_ = qBound (vertical_scroll_bar->minimum (), live_scroll_position_ + , vertical_scroll_bar->maximum ()); + } + else + { + live_scroll_position_ = vertical_scroll_bar->maximum (); + } + } + updateReturnToLiveButton (); } void DisplayText::extend_vertical_scrollbar (int min, int max) @@ -252,6 +474,15 @@ void DisplayText::extend_vertical_scrollbar (int min, int max) void DisplayText::new_period () { + auto const preserve_view = sticky_scroll_enabled_ && !following_live_activity_; + QTextCursor view_anchor; + int anchor_offset {0}; + if (preserve_view) + { + view_anchor = cursorForPosition (QPoint {0, 0}); + anchor_offset = cursorRect (view_anchor).top (); + } + if (m_config->decodes_from_top ()) { document ()->setMaximumBlockCount (4800); document ()->setMaximumBlockCount (5000); @@ -275,13 +506,31 @@ void DisplayText::new_period () extend_vertical_scrollbar (min, max ); }); } - verticalScrollBar ()->setSliderPosition (verticalScrollBar ()->maximum ()); + auto * vertical_scroll_bar = verticalScrollBar (); + if (sticky_scroll_enabled_) + { + live_scroll_position_ = vertical_scroll_bar->maximum (); + } + if (!sticky_scroll_enabled_ || following_live_activity_) + { + vertical_scroll_bar->setSliderPosition (vertical_scroll_bar->maximum ()); + if (sticky_scroll_enabled_) + { + live_scroll_position_ = vertical_scroll_bar->value (); + } + } + else + { + vertical_scroll_bar->setValue (vertical_scroll_bar->value () + + cursorRect (view_anchor).top () - anchor_offset); + } + updateReturnToLiveButton (); } QString DisplayText::appendWorkedB4 (QString message, QString call, QString const& grid, QColor * bg, QColor * fg, LogBook const& logBook, QString const& currentBand, QString const& currentMode, - QString extra) + QString extra, QString const& state, bool entityMismatch) { QString countryName; bool callB4; @@ -413,30 +662,25 @@ QString DisplayText::appendWorkedB4 (QString message, QString call, QString cons { extra += looked_up.primary_prefix; } + else if (!state.isEmpty () || entityMismatch) + { + // A grid-derived U.S. state overrides the callsign's own DXCC + // entity name here: KL7YY operating from DM78 should be shown + // with "U.S.A." (matching the state that follows when GridMap() + // is on), not "Alaska" -- the entity his callsign happens to be + // licensed under, not where he's actually transmitting from. + // entityMismatch catches this even with GridMap() off (no state + // code follows, but the entity name itself still shouldn't lie); + // state alone catches it whenever GridMap() is on, including the + // case where the call genuinely is in its home entity (KL7UW + // really in Alaska still reads "U.S.A. AK", not "Alaska AK"). + // Worked-before/DXCC credit above is unaffected; this only + // changes what's shown. + extra += "U.S.A."; + } else { - auto countryName = looked_up.entity_name; - - // do some obvious abbreviations - countryName.replace ("Islands", "Is."); - countryName.replace ("Island", "Is."); - countryName.replace ("North ", "N. "); - countryName.replace ("Northern ", "N. "); - countryName.replace ("South ", "S. "); - countryName.replace ("East ", "E. "); - countryName.replace ("Eastern ", "E. "); - countryName.replace ("West ", "W. "); - countryName.replace ("Western ", "W. "); - countryName.replace ("Central ", "C. "); - countryName.replace (" and ", " & "); - countryName.replace ("Republic", "Rep."); - countryName.replace ("United States of America", "U.S.A."); - countryName.replace ("United States", "U.S.A."); - countryName.replace ("Fed. Rep. of ", ""); - countryName.replace ("French ", "Fr."); - countryName.replace ("Asiatic", "AS"); - countryName.replace ("European", "EU"); - countryName.replace ("African", "AF"); + auto countryName = looked_up.abbreviated_entity_name; // assign WAE entities to the correct DXCC when "Include extra WAE entities" is not selected if (!(m_config->include_WAE_entities())) { @@ -448,7 +692,6 @@ QString DisplayText::appendWorkedB4 (QString message, QString call, QString cons countryName.replace ("AF Turkey", "Turkey"); countryName.replace ("EU Turkey", "Turkey"); } - extra += countryName; } } @@ -483,7 +726,7 @@ QString DisplayText::leftJustifyAppendage (QString message, QString const& appen return message; } -void DisplayText::displayDecodedText(DecodedText const& decodedText, QString const& myCall, +bool DisplayText::displayDecodedText(DecodedText const& decodedText, QString const& myCall, QString const& mode, bool displayDXCCEntity, LogBook const& logBook, QString const& currentBand, bool ppfx, bool bCQonly, @@ -497,7 +740,7 @@ void DisplayText::displayDecodedText(DecodedText const& decodedText, QString con QColor bg; QColor fg; bool CQcall = false; - auto is_73 = decodedText.messageWords().filter (QRegularExpression {"^(73|RR73)$"}).size(); + auto is_73 = decodedText.messageWords().filter (message_73_regexp).size(); if (decodedText.string ().contains (" CQ ")) { if (m_config->alert_CQ()) { if (!muted) play_CQ = true; @@ -512,24 +755,66 @@ void DisplayText::displayDecodedText(DecodedText const& decodedText, QString con } else { - if (bCQonly) return; + if (bCQonly) return false; } auto message = decodedText.string(); QString dxCall; QString dxGrid; decodedText.deCallAndGrid (/*out*/ dxCall, dxGrid); - QRegularExpression grid_regexp {"\\A(?![Rr]{2}73)[A-Ra-r]{2}[0-9]{2}([A-Xa-x]{2}){0,1}\\z"}; if(!dxGrid.contains(grid_regexp)) dxGrid=""; message = message.left (message.indexOf (QChar::Nbsp)).trimmed (); // strip appended info QString extra; - QString state; // NJ0A + QString state; // NJ0A -- populated only when GridMap() is enabled; drives + // both the entity-name override below and the trailing + // state code appended at the end of this function. - if (displayDXCCEntity && dxGrid.length() > 0 && logBook.countries ()->lookup (dxCall).primary_prefix == "K") { - //std::cout << dxCall << " -> " << dxGrid << " " << logBook.countries ()->lookup (dxCall).primary_prefix <<"\n"; - if (m_config->GridMap()) { - if (CQcall || is_73 || m_config->GridMapAll()) { - state = logBook.countries ()->findState(dxGrid); - } + // K (contiguous US), KL (Alaska), KH6 (Hawaii), KH0 (Mariana Is.), + // KH2 (Guam), KH8 (American Samoa), KP2 (US Virgin Is.), KP4 (Puerto + // Rico), and KG4 (Guantanamo Bay) are all separate DXCC entities that + // license under the same K/N/W/A callsign blocks (e.g. a WP3 call + // resolves to the KP4 entity via lookup() below, same as KP4 itself). + // cty.dat already exact-matches ordinary stateside KG4-suffix calls back + // to primary_prefix "K", so primary_prefix "KG4" here only ever means a + // genuine Guantanamo Bay call. Any of these can genuinely be transmitting + // from one of the 50 states (e.g. KL7YY portable from Colorado, or KP4 + // portable from Nebraska), so all are eligible for grid-based state + // mapping, not just plain "K" calls. The remaining K/N/W/A-administered + // entities (Baker & Howland, Palmyra & Jarvis, Wake, Navassa, Desecheo, + // Swains, plus the deleted Johnston and Midway) are intentionally + // omitted: they have no resident ham population, so they're never + // genuinely "home" to a callsign the way the entities above are -- + // activations are DXpeditions using calls issued for the trip. + static QStringList const us_family_prefixes { + "K", "KL", "KH6", "KH0", "KH2", "KH8", "KP2", "KP4", "KG4"}; + // KL and KH6 are the only entities in that set with their own recognized + // "state" code in grid.dat (Alaska and Hawaii are modelled there like + // states). If a KL/KH6 call's grid resolves to exactly that code, the + // call really is where its callsign says -- no entity-name mismatch, even + // with GridMap() off. The other entities (KH0/KH2/KH8/KP2/KP4) have no + // such code, since their home territories aren't in grid.dat at all, + // so any resolved state for one of those always indicates the operator + // is actually transmitting from the mainland. + static QHash<QString, QString> const home_state_for_entity { + {"KL", "AK"}, {"KH6", "HI"}}; + auto const& dxRecord = logBook.countries ()->lookup (dxCall); + bool const usFamilyEntity = us_family_prefixes.contains (dxRecord.primary_prefix); + + // entityMismatch answers "does this call's grid contradict its own DXCC + // entity" independently of GridMap()/GridMapAll(), so the entity-name + // choice below can be corrected (KL7YY operating from DM78 should not be + // labelled "Alaska") even when the operator hasn't enabled the separate + // "show the state code too" feature that state/GridMap() controls. + QString rawState; + bool entityMismatch = false; + if (dxGrid.length() > 0 && usFamilyEntity) { + rawState = logBook.countries ()->findState (dxGrid); + if (rawState == "**") rawState.clear (); + entityMismatch = !rawState.isEmpty () + && rawState != home_state_for_entity.value (dxRecord.primary_prefix); + } + if (dxGrid.length() > 0 && usFamilyEntity && m_config->GridMap()) { + if (CQcall || is_73 || m_config->GridMapAll()) { + state = rawState; } } //NJ0A @@ -538,7 +823,7 @@ void DisplayText::displayDecodedText(DecodedText const& decodedText, QString con { extra += QString {"%1"}.arg (fSpread, 5, 'f', fSpread < 0.95 ? 3 : 2) + QChar {' '}; } - auto ap_pos = message.lastIndexOf (QRegularExpression {R"((?:\?\s)?(?:a[0-9]|q[0-9][0-9*]?)$)"}); + auto ap_pos = message.lastIndexOf (ap_regexp); if (ap_pos >= 0) { extra += message.mid (ap_pos) + QChar {' '}; @@ -554,7 +839,7 @@ void DisplayText::displayDecodedText(DecodedText const& decodedText, QString con // preformated text line t1 auto currentMode = mode; message = appendWorkedB4 (message, dxCall, dxGrid, &bg, &fg - , logBook, currentBand, currentMode, extra); + , logBook, currentBand, currentMode, extra, state, entityMismatch); } else { @@ -572,32 +857,15 @@ void DisplayText::displayDecodedText(DecodedText const& decodedText, QString con if (m_config->show_country_names()) { auto const& looked_up = logBook.countries ()->lookup (dxCall); - auto countryName = looked_up.entity_name; + auto countryName = looked_up.abbreviated_entity_name; if (m_bPrincipalPrefix) { extra += looked_up.primary_prefix; + } else if (!state.isEmpty () || entityMismatch) { + // Same reasoning as the CQ-line case above: a grid-derived + // U.S. state overrides the callsign's own DXCC entity name. + extra += "U.S.A."; } else { - // do some obvious abbreviations - countryName.replace ("Islands", "Is."); - countryName.replace ("Island", "Is."); - countryName.replace ("North ", "N. "); - countryName.replace ("Northern ", "N. "); - countryName.replace ("South ", "S. "); - countryName.replace ("East ", "E. "); - countryName.replace ("Eastern ", "E. "); - countryName.replace ("West ", "W. "); - countryName.replace ("Western ", "W. "); - countryName.replace ("Central ", "C. "); - countryName.replace (" and ", " & "); - countryName.replace ("Republic", "Rep."); - countryName.replace ("United States of America", "U.S.A."); - countryName.replace ("United States", "U.S.A."); - countryName.replace ("Fed. Rep. of ", ""); - countryName.replace ("French ", "Fr."); - countryName.replace ("Asiatic", "AS"); - countryName.replace ("European", "EU"); - countryName.replace ("African", "AF"); - // assign WAE entities to the correct DXCC when "Include extra WAE entities" is not selected if (!(m_config->include_WAE_entities())) { countryName.replace ("Bear Is.", "Svalbard"); @@ -694,6 +962,7 @@ void DisplayText::displayDecodedText(DecodedText const& decodedText, QString con } insertText (message.trimmed (), bg, fg, decodedText.call (), dxCall); + return true; } void DisplayText::displayTransmittedText(QString text, QString modeTx, qint32 txFreq, @@ -872,7 +1141,7 @@ void DisplayText::highlight_callsign (QString const& callsign, QColor const& bg, } else { - auto pos = highlighted_calls_.find (callsign); + auto pos = highlighted_calls_.find (callsign.toUpper ()); if (bg.isValid () || fg.isValid ()) { auto colours = qMakePair (bg, fg); @@ -918,7 +1187,7 @@ void DisplayText::AudioAlerts() #ifdef WIN32 if(m_config->alert_Enabled()) { QAudioOutput info(QAudioDeviceInfo::defaultOutputDevice()); - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config->voicesPath() + "/"; + QString audioPath = m_config->voice_directory ().absolutePath () + QChar {'/'}; QAudioFormat format; format.setCodec("audio/pcm"); format.setSampleRate (48000); @@ -930,8 +1199,9 @@ void DisplayText::AudioAlerts() connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State))); #else if(m_config->alert_Enabled()) { - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config->voicesPath() + "/"; + QString audioPath = m_config->voice_directory ().absolutePath () + QChar {'/'}; #endif +#ifdef WIN32 QFile *effect2 = new QFile(this); QFile *effect3 = new QFile(this); QFile *effect4 = new QFile(this); @@ -956,6 +1226,7 @@ void DisplayText::AudioAlerts() effect11->setFileName(QString("%1/%2").arg(audioPath, "Grid.wav")); effect12->setFileName(QString("%1/%2").arg(audioPath, "GridOnBand.wav")); effect13->setFileName(QString("%1/%2").arg(audioPath, "CQ.wav")); +#endif static int startIndex = 0; int nextStartIndex = startIndex +1; switch (startIndex) { diff --git a/widgets/displaytext.h b/widgets/displaytext.h index 26b3b2a8..8a948b6c 100644 --- a/widgets/displaytext.h +++ b/widgets/displaytext.h @@ -10,6 +10,8 @@ #include <QTimer> class QAction; +class QResizeEvent; +class QToolButton; class Configuration; class LogBook; class DecodedText; @@ -20,15 +22,11 @@ class DisplayText Q_OBJECT public: explicit DisplayText(QWidget *parent = nullptr); - void set_configuration (Configuration const * configuration, bool high_volume = false) - { - disconnect (vertical_scroll_connection_); - m_config = configuration; - high_volume_ = high_volume; - } + void set_configuration (Configuration const * configuration, bool high_volume = false); void setContentFont (QFont const&); + QFont contentFont () const {return char_font_;} void insertLineSpacer(QString const&); - void displayDecodedText(DecodedText const& decodedText, QString const& myCall, QString const& mode, + bool displayDecodedText(DecodedText const& decodedText, QString const& myCall, QString const& mode, bool displayDXCCEntity, LogBook const& logBook, QString const& currentBand=QString {}, bool ppfx=false, bool bCQonly=false, bool haveFSpread = false, float fSpread = 0.0, bool bDisplayPoints=false, @@ -43,21 +41,30 @@ public: qint32 m_points; bool m_bDisplayPoints; - Q_SIGNAL void selectCallsign (Qt::KeyboardModifiers); + Q_SIGNAL void selectCallsign (QString const& line, QString const& word, Qt::KeyboardModifiers); Q_SIGNAL void erased (); Q_SLOT void insertText (QString const& text, QColor bg = QColor {}, QColor fg = QColor {} , QString const& call1 = QString {}, QString const& call2 = QString {}, QTextCursor::MoveOperation location=QTextCursor::End); + Q_SLOT void clear (); Q_SLOT void erase (); + Q_SLOT void scrollToLiveActivity (); Q_SLOT void highlight_callsign (QString const& callsign, QColor const& bg, QColor const& fg, bool last_period_only); private: void AudioAlerts(); QTimer alertsTimer; QString leftJustifyAppendage (QString message, QString const& appendage) const; + void captureClick (QMouseEvent const *); + void mousePressEvent (QMouseEvent *) override; void mouseDoubleClickEvent (QMouseEvent *) override; + void resizeEvent (QResizeEvent *) override; + bool decodesFromTop () const; void extend_vertical_scrollbar (int min, int max); + void scrollRangeChanged (int minimum, int maximum); + void userScrolledTo (int position); + void updateReturnToLiveButton (); Configuration const * m_config; bool m_bPrincipalPrefix; @@ -65,14 +72,30 @@ private: QString appendWorkedB4(QString message, QString callsign , QString const& grid, QColor * bg, QColor * fg , LogBook const& logBook, QString const& currentBand - , QString const& currentMode, QString extra); + , QString const& currentMode, QString extra + , QString const& state = QString {} + , bool entityMismatch = false); QFont char_font_; QAction * erase_action_; + enum class ClickState + { + None, + Captured, + Canceled, + }; + QString pressed_line_; + QString pressed_word_; + Qt::MouseButton pressed_button_; + ClickState click_state_; QHash<QString, QPair<QColor, QColor>> highlighted_calls_; bool high_volume_; + bool sticky_scroll_enabled_; + bool following_live_activity_; QMetaObject::Connection vertical_scroll_connection_; long long modified_vertical_scrollbar_max_; + QToolButton * return_to_live_button_; + int live_scroll_position_; }; #endif // DISPLAYTEXT_H diff --git a/widgets/echograph.cpp b/widgets/echograph.cpp index 94ccb7aa..d39cbc3c 100644 --- a/widgets/echograph.cpp +++ b/widgets/echograph.cpp @@ -6,6 +6,7 @@ #include "echoplot.h" #include "ui_echograph.h" #include "moc_echograph.cpp" +#include "PerformanceTrace.hpp" #define NSMAX2 1366 @@ -14,6 +15,7 @@ EchoGraph::EchoGraph(QSettings * settings, QWidget *parent) : m_settings (settings), ui(new Ui::EchoGraph) { + PerformanceTrace::Phase construction {"echograph.construct"}; ui->setupUi(this); setWindowTitle (QApplication::applicationName () + " - " + tr ("Echo Graph")); installEventFilter(parent); //Installing the filter diff --git a/widgets/echoplot.cpp b/widgets/echoplot.cpp index 65feb7a8..039c9e5f 100644 --- a/widgets/echoplot.cpp +++ b/widgets/echoplot.cpp @@ -1,13 +1,13 @@ #include "echoplot.h" #include "commons.h" +#include <algorithm> #include <math.h> #include <QPainter> #include <QPen> +#include <QPolygon> #include <QDebug> #include "moc_echoplot.cpp" -#define MAX_SCREENSIZE 2048 - EPlotter::EPlotter(QWidget *parent) : //EPlotter Constructor QFrame(parent) @@ -33,6 +33,7 @@ EPlotter::EPlotter(QWidget *parent) : //EPlotter Constructor m_TxFreq = 1500; m_line = 0; m_dBStepSize=10; + m_bBaseline=false; } EPlotter::~EPlotter() { } // Destructor @@ -81,7 +82,7 @@ void EPlotter::paintEvent(QPaintEvent *) // paintEvent() void EPlotter::draw() //draw() { int i,j,y; - float blue[4096],red[4096]; + float blue[4096] {},red[4096] {}; float gain = pow(10.0,(m_plotGain/20.0)); QPen penBlue(QColor(0,255,255),1); QPen penRed(Qt::red,1); @@ -100,13 +101,10 @@ void EPlotter::draw() //draw() painter2D.drawLine(0,0,m_w,0); } - QPoint LineBuf[MAX_SCREENSIZE]; - - if(m_binsPerPixel==0) m_binsPerPixel=1; + m_binsPerPixel=std::max(1,std::min(4096,m_binsPerPixel)); + int compressedCount=4096/m_binsPerPixel; j=0; - for(i=0; i<4096/m_binsPerPixel; i++) { - blue[i]=0.0; - red[i]=0.0; + for(i=0; i<compressedCount; i++) { for(int k=0; k<m_binsPerPixel; k++) { blue[i]+=echocom_.blue[j]; red[i]+=echocom_.red[j]; @@ -115,24 +113,23 @@ void EPlotter::draw() //draw() } if(m_smooth>0) { for(i=0; i<m_smooth; i++) { - int n4096=4096; - smo121_(blue,&n4096); - smo121_(red,&n4096); + smo121_(blue,&compressedCount); + smo121_(red,&compressedCount); } } -// check i0 value! ... int i0=2048/m_binsPerPixel + int(m_StartFreq/(m_fftBinWidth*m_binsPerPixel)); + int const firstPixel=std::max(0,-i0); + int const lastPixel=std::min(m_w,compressedCount-i0); + QPolygon lineBuf; + lineBuf.reserve(std::max(0,lastPixel-firstPixel)); if(m_blue) { painter2D.setPen(penBlue); - j=0; - for(i=0; i<m_w; i++) { + for(i=firstPixel; i<lastPixel; i++) { y = 0.9*m_h2 - gain*(m_h/10.0)*blue[i0+i] - 0.01*m_h2*m_plotZero; - LineBuf[j].setX(i); - LineBuf[j].setY(y); - j++; + lineBuf.append(QPoint {i,y}); } - painter2D.drawPolyline(LineBuf,j); + painter2D.drawPolyline(lineBuf); } switch (m_nColor) { case 0: painter2D.setPen(penRed); break; @@ -143,14 +140,12 @@ void EPlotter::draw() //draw() case 5: painter2D.setPen(penBlack2); break; } - j=0; - for(int i=0; i<m_w; i++) { + lineBuf.clear(); + for(int i=firstPixel; i<lastPixel; i++) { y = 0.9*m_h2 - gain*(m_h/10.0)*red[i0+i] - 0.01*m_h2*m_plotZero; - LineBuf[j].setX(i); - LineBuf[j].setY(y); - j++; + lineBuf.append(QPoint {i,y}); } - painter2D.drawPolyline(LineBuf,j); + painter2D.drawPolyline(lineBuf); if(m_bBaseline) { // Draw the baseline diff --git a/widgets/fastgraph.cpp b/widgets/fastgraph.cpp index 9efe5fc6..c9eddd01 100644 --- a/widgets/fastgraph.cpp +++ b/widgets/fastgraph.cpp @@ -6,6 +6,7 @@ #include <QKeyEvent> #include "fastplot.h" #include "SettingsGroup.hpp" +#include "PerformanceTrace.hpp" #include "ui_fastgraph.h" #include "moc_fastgraph.cpp" @@ -20,6 +21,7 @@ FastGraph::FastGraph(QSettings * settings, QWidget *parent) : m_ave {40}, ui {new Ui::FastGraph} { + PerformanceTrace::Phase construction {"fastgraph.construct"}; ui->setupUi(this); setWindowTitle (QApplication::applicationName () + " - " + tr ("Fast Graph")); installEventFilter(parent); //Installing the filter @@ -98,7 +100,11 @@ void FastGraph::on_pbAutoLevel_clicked() for(int i=0; i<=fast_jh; i++) { sum += fast_green[i]; } - m_ave=sum/fast_jh; + if (fast_jh == 0) { + m_ave=0.0; + } else { + m_ave=sum/fast_jh; + } ui->gainSlider->setValue(127-int(2.2*m_ave)); ui->zeroSlider->setValue(int(m_ave)+20); ui->greenZeroSlider->setValue(160-int(3.3*m_ave)); diff --git a/widgets/logqso.cpp b/widgets/logqso.cpp index 35f04b13..5a81f145 100644 --- a/widgets/logqso.cpp +++ b/widgets/logqso.cpp @@ -3,7 +3,6 @@ #include <QLocale> #include <QString> #include <QSettings> -#include <QStandardPaths> #include <QStringList> #include <QDir> #include <QTimer> @@ -16,6 +15,8 @@ #include "models/Bands.hpp" #include "models/CabrilloLog.hpp" #include "validators/MaidenheadLocatorValidator.hpp" +#include "qt_helpers.hpp" +#include "PerformanceTrace.hpp" #include "ui_logqso.h" #include "moc_logqso.cpp" @@ -88,12 +89,12 @@ LogQSO::LogQSO(QString const& programTitle, QSettings * settings , m_config {config} , m_log {log} { + PerformanceTrace::Phase construction {"logqso.construct"}; ui->setupUi(this); setWindowTitle(programTitle + " - Log QSO"); ui->comboBoxSatellite->addItem ("", ""); - QString sat_file_location; - QDir dataPath {QStandardPaths::writableLocation (QStandardPaths::DataLocation)}; - sat_file_location = dataPath.exists(sat_file_name) ? dataPath.absoluteFilePath(sat_file_name) : m_config->data_dir ().absoluteFilePath (sat_file_name); + auto const& sat_file_location = writable_override_or_installed_file_path (m_config->writeable_data_dir (), + m_config->data_dir (), sat_file_name); QFile file {sat_file_location}; QStringList wordList; QTextStream stream(&file); @@ -169,8 +170,8 @@ void LogQSO::loadSettings () ui->cbFreqRx->setChecked (m_settings->value ("SaveFreqRx", false).toBool ()); QString comments_location; // load the content of comments.txt file to the comments combo box - QDir dataPath {QStandardPaths::writableLocation (QStandardPaths::DataLocation)}; - comments_location = dataPath.exists("comments.txt") ? dataPath.absoluteFilePath("comments.txt") : m_config->data_dir ().absoluteFilePath ("comments.txt"); + comments_location = writable_override_or_installed_file_path (m_config->writeable_data_dir (), + m_config->data_dir (), "comments.txt"); QFile file2 {comments_location}; QTextStream stream2(&file2); if(file2.open (QIODevice::ReadOnly | QIODevice::Text)) { @@ -216,8 +217,8 @@ void LogQSO::initLogQSO(QString const& hisCall, QString const& hisGrid, QString QDateTime const& dateTimeOn, QDateTime const& dateTimeOff, Radio::Frequency dialFreq, bool noSuffix, QString xSent, QString xRcvd) { - if(!isHidden()) return; + if(!isHidden()) return; QPushButton* okBtn = ui->buttonBox->button(QDialogButtonBox::Ok); okBtn->setAutoDefault(true); okBtn->setDefault(true); @@ -376,8 +377,8 @@ void LogQSO::accept() m_txPower = ui->txPower->text (); auto strDialFreq = QString::number (m_dialFreq / 1.e6,'f',6); auto operator_call = ui->loggedOperator->text (); - auto xsent = ui->exchSent->text (); - auto xrcvd = ui->exchRcvd->text (); + auto xsent = ui->exchSent->text ().trimmed (); + auto xrcvd = ui->exchRcvd->text ().trimmed (); using SpOp = Configuration::SpecialOperatingActivity; auto special_op = m_config->special_op_id (); @@ -387,20 +388,22 @@ void LogQSO::accept() } if ((special_op == SpOp::RTTY and xsent!="" and xrcvd!="")) { - if(rptSent=="" or !xsent.contains(rptSent+" ")) rptSent=xsent.split(" " + auto xsent_words = xsent.split(" " #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) - , QString::SkipEmptyParts + , QString::SkipEmptyParts #else - , Qt::SkipEmptyParts + , Qt::SkipEmptyParts #endif - ).at(0); - if(rptRcvd=="" or !xrcvd.contains(rptRcvd+" ")) rptRcvd=xrcvd.split(" " + ); + auto xrcvd_words = xrcvd.split(" " #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) - , QString::SkipEmptyParts + , QString::SkipEmptyParts #else - , Qt::SkipEmptyParts + , Qt::SkipEmptyParts #endif - ).at(0); + ); + if(rptSent=="" or !xsent.contains(rptSent+" ")) rptSent=xsent_words.at(0); + if(rptRcvd=="" or !xrcvd.contains(rptRcvd+" ")) rptRcvd=xrcvd_words.at(0); } // validate @@ -433,7 +436,8 @@ void LogQSO::accept() } m_freqRx = ui->freqRx->text (); //Log this QSO to file "wsjtx.log" - static QFile f {QDir {QStandardPaths::writableLocation (QStandardPaths::DataLocation)}.absoluteFilePath ("wsjtx.log")}; + QFile f {writable_file_path (m_config->writeable_data_dir (), "wsjtx.log")}; + ensure_parent_directory (f.fileName ()); if(!f.open(QIODevice::Text | QIODevice::Append)) { MessageBox::warning_message (this, tr ("Log file error"), tr ("Cannot open \"%1\" for append").arg (f.fileName ()), diff --git a/widgets/mainwindow.cpp b/widgets/mainwindow.cpp index d58a98be..596cb0e0 100644 --- a/widgets/mainwindow.cpp +++ b/widgets/mainwindow.cpp @@ -1,31 +1,38 @@ //---------------------------------------------------------- MainWindow #include "mainwindow.h" +#include "RoundRobinSelection.hpp" +#include "FastDecode.hpp" +#include <array> #include <QAudio> #include <QAudioOutput> #include <QSound> #include <QCoreApplication> -#include <cinttypes> #include <cstring> #include <cmath> +#include <iostream> #include <limits> #include <functional> -#include <fstream> -#include <iterator> #include <algorithm> #include <fftw3.h> -#include <thread> // TCI #include <QApplication> #include <QStringListModel> #include <QSettings> #include <QKeyEvent> +#include <QPaintEvent> #include <QWheelEvent> #include <QProcessEnvironment> #include <QSharedMemory> #include <QFileDialog> #include <QTextBlock> #include <QProgressBar> +#include <QStyle> #include <QLineEdit> +#include <QFocusEvent> +#include <QFocusFrame> +#include <QFrame> +#include <QWidget> +#include <QTabBar> #include <QRegExpValidator> #include <QRegExp> #include <QRegularExpression> @@ -38,14 +45,19 @@ #include <QDir> #include <QDebug> #include <QtConcurrent/QtConcurrentRun> -#include <QProgressDialog> #include <QHostInfo> +#include <QMutexLocker> #include <QVector> #include <QCursor> #include <QToolTip> #include <QAction> #include <QButtonGroup> #include <QActionGroup> +#include <QSignalBlocker> +#include <QMetaMethod> +#include <QGridLayout> +#include <QHBoxLayout> +#include <QVBoxLayout> #include <QSplashScreen> #include <QUdpSocket> #include <QAbstractItemView> @@ -56,18 +68,33 @@ #include <QRandomGenerator> #endif +#include <memory> +#include <vector> + #include "itoneAndicw.h" // TCI #include "helper_functions.h" +#include "PerformanceTrace.hpp" #include "revision_utils.hpp" #include "qt_helpers.hpp" +#include "CompactButtonSize.hpp" #include "Network/NetworkAccessManager.hpp" +#include "Network/DecodedTime.hpp" #include "Audio/soundout.h" #include "Audio/soundin.h" +#include "Audio/AudioInputSource.hpp" #include "Modulator/Modulator.hpp" #include "Detector/Detector.hpp" +#include "DecDataMutex.hpp" +#include "DecoderIpc.hpp" +#include "qmap/qmap_ipc.h" +#include "qmap/qmap_decode_record.h" +#include "qmap/qmap_click_policy.h" +#include "TxStartPolicy.hpp" +#include "WaitFeaturePolicy.hpp" +#include "ActiveStationList.hpp" +#include "widgets/SpecOpLabel.h" #include "plotter.h" -#include "echoplot.h" #include "echograph.h" #include "fastplot.h" #include "fastgraph.h" @@ -77,7 +104,6 @@ #include "activeStations.h" #include "colorhighlighting.h" #include "widegraph.h" -#include "sleep.h" #include "logqso.h" #include "Decoder/decodedtext.h" #include "Radio.hpp" @@ -91,10 +117,10 @@ #include "signalmeter.h" #include "HelpTextWindow.hpp" #include "SampleDownloader.hpp" -#include "Audio/BWFFile.hpp" #include "MultiSettings.hpp" #include "validators/MaidenheadLocatorValidator.hpp" #include "validators/CallsignValidator.hpp" +#include "validators/LiveCQCallsign.hpp" #include "EqualizationToolsDialog.hpp" #include "Network/LotWUsers.hpp" #include "logbook/AD1CCty.hpp" @@ -105,17 +131,184 @@ #include "ExportCabrillo.h" #include "Network/Cloudlog.hpp" #include "ui_mainwindow.h" +#include "qmap/decode_ipc.h" +#include "qmap/shared_memory_key.h" #include "moc_mainwindow.cpp" +#include "MessageFilter.hpp" +#include "MessageFilterLogic.hpp" +#include "JttyMessages.hpp" +#include "PrefixSuffix.hpp" +#include "HelpText.hpp" +#include "HighlightingRules.hpp" +#include "Rr73Policy.hpp" +#include "Audio/WavInputLoader.hpp" +#include "Audio/WavFile.hpp" +#include "WSJTXLogging.hpp" #include "Logger.hpp" +#include "FoxGuardBands.hpp" +#include "FoxOperatorActions.hpp" +#include "DecodedMessageReaction.hpp" +#include "DecodeOutputPlan.hpp" +#include "SuperFoxTxPlanner.h" #include "widgets/QSYMessage.h" #include "widgets/QSYMessageCreator.h" +#include "widgets/QSYMessageParser.h" #include "widgets/qsymonitor.h" #include "Network/eqsl.h" #define FCL fortran_charlen_t extern "C" { + void sfox_pack_(char* line, char* ckey, bool* more_cqs, bool* send_msg, + char* free_text_msg, qint8 xin[], int* pack_error, + FCL line_len, FCL ckey_len, FCL free_text_msg_len); +} + +namespace { + int const ReferenceSpectrumMeasureSeconds = 7; + // Bit 7 is unused by the legacy nexp_decode contest packing. + int constexpr q65PileupDecodeFlag = 1 << 7; + + QString decodeHeadingText(QString const& headings) + { + return headings.simplified(); + } + + QString decodeLineDescription(QString const& headings) + { + if (headings.isEmpty ()) return QString {"No column headings are shown."}; + return QString {"Columns: %1."}.arg (headings); + } + + void set_style_sheet_if_changed(QWidget * widget, QString const& style_sheet) + { + if (widget->styleSheet() != style_sheet) widget->setStyleSheet(style_sheet); + } + + void set_style_sheet_if_changed(QWidget& widget, QString const& style_sheet) + { + set_style_sheet_if_changed(&widget, style_sheet); + } + + void set_button_style_state_if_changed(QWidget * widget, char const * state) + { + if (widget->property("wsjtxState").toString() != QLatin1String {state}) + { + widget->setProperty("wsjtxState", state); + widget->style()->unpolish(widget); + widget->style()->polish(widget); + widget->update(); + } + } + + QRegularExpression const four_digit_regexp {"\\d\\d\\d\\d"}; + QRegularExpression const cq_or_qrz_message_regexp {"^(CQ|QRZ) "}; + QRegularExpression const leading_r_report_regexp {"^R(?!R73|RR)"}; + QRegularExpression const roger_ack_regexp {"^RR(?:R|73)$"}; + QRegularExpression const reply_cq_or_qrz_regexp {R"(^(CQ |CQDX |QRZ ))"}; + + void clearFoxTxMessages() + { + foxcom_.nslots = 0; + std::memset(foxcom_.i3bit, 0, sizeof foxcom_.i3bit); + std::memset(foxcom_.cmsg, 0, sizeof foxcom_.cmsg); + } + + struct SuperFoxTxMessage + { + int slot; + QString text; + }; + + QVector<SuperFoxTxMessage> superFoxTxMessages() + { + int constexpr maxFoxTxMessages = 5; + int constexpr foxTxMessageChars = 37; + // C index 38 is Fortran cmsg(n)(39:39), the SuperFox free-text flag. + int constexpr superFoxFreeTextFlagIndex = 38; + // foxgen_() appends SuperFox free text as an extra slot by mutating nslots. + int const nslots = qBound(0, foxcom_.nslots, maxFoxTxMessages); + QVector<SuperFoxTxMessage> messages; + messages.reserve(nslots); + + for(int i = 0; i < nslots; i++) { + char const * const row=foxcom_.cmsg[i]; + bool const freeTextRow = foxcom_.bSendMsg && i == nslots - 1 && + row[superFoxFreeTextFlagIndex] == '1'; + if(freeTextRow) continue; + + QString const text = QString::fromLatin1(row, foxTxMessageChars) + .trimmed(); + if(text.isEmpty()) continue; + messages.push_back({i + 1, text}); + } + + return messages; + } + + int const SuperFoxReportMin = -18; + int const SuperFoxReportMax = 12; + int const SuperFoxHoundCallMax = 6; + + // Must match the SFOX_PACK_* parameters in lib/superfox/sfox_pack.f90. + enum SuperFoxPackError { + SuperFoxPackOk = 0, + SuperFoxPackBadToken = 1, + SuperFoxPackBadOtp = 2, + SuperFoxPackBadCq = 3, + SuperFoxPackBadCall = 4, + SuperFoxPackBadReport = 5, + SuperFoxPackBadFreeText = 6, + }; + + QString superFoxTxReport(QString report) + { + bool ok {false}; + int value = report.toInt(&ok); + if(ok) { + report=QString::number(qBound(SuperFoxReportMin,value, + SuperFoxReportMax)); + } + if(report.mid(0,1) != "-" and report.mid(0,1) != "+") report="+" + report; + if(report.length()==2) report=report.mid(0,1) + "0" + report.mid(1,1); + return report; + } + + int superFoxPackError(QString const& message) + { + QByteArray line = message.left(120).leftJustified(120, ' ').toLatin1(); + QByteArray ckey = QByteArray {"0000000000"}; + QByteArray freeTextMsg(26, ' '); + std::array<qint8, 50> xin {}; + bool moreCqs {false}; + bool sendMsg {false}; + int packError {0}; + + sfox_pack_(line.data(), ckey.data(), &moreCqs, &sendMsg, + freeTextMsg.data(), xin.data(), &packError, + (FCL)line.size(), (FCL)ckey.size(), (FCL)freeTextMsg.size()); + return packError; + } + + bool superFoxQueueableHound(QString const& foxBaseCall, + QString const& houndCall, + QString const& report) + { + // SuperFox Fox replies are staged through foxgen2/sfox_assemble, which + // transmits the Hound as a 6-character base call in a c28 slot. + QString const houndBaseCall = Radio::base_callsign(houndCall); + if(houndBaseCall.length() > SuperFoxHoundCallMax) return false; + QString const message = QString {"%1 %2 %3"}.arg(foxBaseCall, + houndBaseCall, superFoxTxReport(report)); + return superFoxPackError(message) == SuperFoxPackOk; + } +} + +extern "C" { //----------------------------------------------------- C and Fortran routines + + bool stdmsg_(char const * msg, fortran_charlen_t); + void symspec_(struct dec_data *, int* k, int* nsps, int* ingain, bool* bLowSidelobes, int* minw, float* px, float s[], float* df3, int* nhsym, int* npts8, float *m_pxmax, int* npct); @@ -127,6 +320,11 @@ extern "C" { float s[], int* jh, float *pxmax, float *rmsNoGain, char line[], fortran_charlen_t, fortran_charlen_t, fortran_charlen_t, fortran_charlen_t); + void genjtty_(char const * msg, int itone[], int* nsym, fortran_charlen_t); + + void gen_jttywave_(int itone[], int* nsym, int* nsps, float* bt, float* fsample, float* f0, + float xjunk[], float wave[], int* icmplx, int* nwave); + void gen_echocall_(char* basecall, int itone[], fortran_charlen_t); void genft8_(char* msg, int* i3, int* n3, char* msgsent, char ft8msgbits[], @@ -161,10 +359,10 @@ extern "C" { void gen65(char* msg, int* ichk, char msgsent[], int itone[], int* itext); - void gen_cw_wave_(char* msg, int* ifreq, float wave[], fortran_charlen_t); + void gen_cw_wave_(char const * msg, int* ifreq, float wave[], fortran_charlen_t); void genq65_(char* msg, int* ichk, char* msgsent, int itone[], - int* i3, int* n3, fortran_charlen_t, fortran_charlen_t); + int* i3, int* n3, int* iflag, fortran_charlen_t, fortran_charlen_t); void genwspr_(char* msg, char* msgsent, int itone[], fortran_charlen_t, fortran_charlen_t); @@ -181,19 +379,14 @@ extern "C" { void save_echo_params_(int* ndoptotal, int* ndop, int* nfrit, float* f1, float* fspread, int* toneSpacing, volatile int itone[], short id2[], int* idir); - void avecho_( short id2[], int* dop, int* nfrit, int* nauto, int* ndf, int* navg, + void avecho_( short id2[], int* dop, int* nfrit, int* nauto, int* navg, int* nqual, float* f1, float* level, float* sigdb, float* snr, float* dfreq, float* width, bool* bDiskData, bool* bEchoCall, char const * txcall, char rxcall[], FCL len1, FCL len2); - void fast_decode_(short id2[], int narg[], double * trperiod, - char msg[], char mycall[], char hiscall[], - fortran_charlen_t, fortran_charlen_t, fortran_charlen_t); void degrade_snr_(short d2[], int* n, float* db, float* bandwidth); - void wav12_(short d2[], short d1[], int* nbytes, short* nbitsam2); - - void refspectrum_(short int d2[], bool* bclearrefspec, + void refspectrum_(short int d2[], int* ninput, bool* bclearrefspec, bool* brefspec, bool* buseref, const char* c_fname, fortran_charlen_t); void freqcal_(short d2[], int* k, int* nkhz,int* noffset, int* ntol, @@ -206,16 +399,12 @@ extern "C" { void sfox_wave_gfsk_(); - void sftx_sub_(char const * otp_key, FCL len1); + void sftx_sub_(char const * otp_key, int* pack_error, FCL len1); void plotsave_(float swide[], int* m_w , int* m_h1, int* irow); void chk_samples_(int* m_ihsym,int* k, int* m_hsymStop); - void save_dxbase_(char* dxbase, FCL len); - - void indexx_(float arr[], int* n, int indx[]); - void get_q3list_(char* fname, bool* bDiskData, int* nlist, char* list, FCL len1, FCL len2); void rm_q3list_(char* callsign, FCL len); @@ -226,7 +415,8 @@ QList<FoxVerifier *> m_verifications; int volatile itone[MAX_NUM_SYMBOLS]; //Audio tones for all Tx symbols int volatile itone0[MAX_NUM_SYMBOLS]; //Dummy array, data not actually used int volatile icw[NUM_CW_SYMBOLS]; //Dits for CW ID -dec_data_t dec_data; //For sharing with Fortran +dec_data_t& dec_data = *new dec_data_t{}; + int outBufSize; int rc; qint32 g_iptt {0}; @@ -243,7 +433,6 @@ QVector<QColor> g_ColorTbl; using SpecOp = Configuration::SpecialOperatingActivity; -bool verified = false; bool blocked = false; bool m_displayBand = false; bool wait_and_call = false; @@ -259,16 +448,9 @@ bool not_erase = false; bool first_Fox_alert = true; bool second_Fox_alert = true; bool no_Fox_alert = false; -int Dpoints=0; -int maxDPoints=0; -int dBpoints=-28; -int dBpoints2=99; -int maxdBPoints=-28; -int mindBPoints=99; bool pounce = false; bool filtered = false; bool ignored = false; -bool selected = false; bool keepTx5 = false; bool no_logging = false; bool BlankLineInserted = false; @@ -288,29 +470,23 @@ QString ALLCALL7 = ""; QString m_hisCall0 = ""; QString earlyDecodes = ""; //ft8md -QSharedMemory mem_qmap("mem_qmap"); //Memory segment to be shared (optionally) with QMAP -struct { - int ndecodes; //Number of QMAP decodes available (so far) - int ncand; //Number of QMAP candidates considered for decoding - int nQDecoderDone; //QMAP decoder is finished (0 or 1) - int nWDecoderBusy; //WSJT-X decoder is busy (0 or 1) - int nWTransmitting; //WSJT-X is transmitting (0 or 1) - int kHzRequested; //Integer kHz dial frequency requested from QMAP - char result[50][72]; //Decodes as character*72 arrays -} qmapcom; -int* ipc_qmap; +QSharedMemory mem_qmap; //Memory segment to be shared (optionally) with QMAP +QMapDecodeBlock qmapcom {}; +QMapSharedMemory * ipc_qmap {nullptr}; +bool qmap_decoder_region_available {false}; +bool qmap_click_mailbox_available {false}; namespace { Radio::Frequency constexpr default_frequency {14074000}; - QRegExp message_alphabet {"[- @A-Za-z0-9+./?#<>;$]*"}; - // grid exact match excluding RR73 - QRegularExpression grid_regexp {"\\A(?![Rr]{2}73)[A-Ra-r]{2}[0-9]{2}([A-Xa-x]{2}){0,1}\\z"}; - QRegularExpression non_r_db_regexp {"\\A[-+]{1}[0-9]{1,2}\\z"}; auto quint32_max = std::numeric_limits<quint32>::max (); - constexpr int N_WIDGETS {38}; + constexpr int standard_messages_tab_index {0}; + constexpr int fox_queue_tab_index {1}; constexpr int default_rx_audio_buffer_frames {-1}; // lets Qt decide constexpr int default_tx_audio_buffer_frames {-1}; // lets Qt decide + // Type 5 EU VHF messages carry an 11-bit serial number. + constexpr int eu_vhf_type5_serial_max {2047}; + constexpr int default_serial_number_max {4095}; bool message_is_73 (int type, QStringList const& msg_parts) { @@ -329,27 +505,43 @@ namespace } } +QRegExp const MainWindow::message_alphabet {"[- @A-Za-z0-9+./?#<>;$]*"}; +QRegularExpression const MainWindow::grid_regexp {"\\A(?![Rr]{2}73)[A-Ra-r]{2}[0-9]{2}([A-Xa-x]{2}){0,1}\\z"}; +QRegularExpression const MainWindow::non_r_db_regexp {"\\A[-+]{1}[0-9]{1,2}\\z"}; +constexpr int MainWindow::MaxActiveStationRows; +constexpr int MainWindow::MaxQ65PileupCallers; + //--------------------------------------------------- MainWindow constructor MainWindow::MainWindow(QDir const& temp_directory, bool multiple, MultiSettings * multi_settings, QSharedMemory *shdmem, unsigned downSampleFactor, - QSplashScreen * splash, QProcessEnvironment const& env, QWidget *parent) : + QSplashScreen * splash, QProcessEnvironment const& env, + bool automated_test, + QString base_style_sheet, + std::unique_ptr<AudioInputSource> audio_input_source, + std::unique_ptr<SoundOutput> sound_output, + QString decoder_data_path, + QWidget *parent) : MultiGeometryWidget {parent}, + m_startup_trace_run {PerformanceTrace::current_run ()}, m_env {env}, m_network_manager {this}, m_valid {true}, m_splash {splash}, m_revision {revision ()}, m_multiple {multiple}, + m_automated_test {automated_test}, m_multi_settings {multi_settings}, m_configurations_button {0}, m_settings {multi_settings->settings ()}, + m_base_style_sheet {std::move (base_style_sheet)}, ui(new Ui::MainWindow), m_config {&m_network_manager, temp_directory, m_settings, &m_logBook, this}, + m_decoderDataDir {decoder_data_path.isEmpty () + ? m_config.data_dir () : QDir {decoder_data_path}}, m_logBook {&m_config}, m_cloudlog {&m_config, &m_network_manager}, m_WSPR_band_hopping {m_settings, &m_config, this}, - m_WSPR_tx_next {false}, m_rigErrorMessageBox {MessageBox::Critical, tr ("Rig Control Error") , MessageBox::Cancel | MessageBox::Ok | MessageBox::Retry}, m_wideGraph (new WideGraph(m_settings)), @@ -361,17 +553,20 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, m_dialFreqRxWSPR {0}, m_detector {new Detector {RX_SAMPLE_RATE, double(NTMAX), downSampleFactor}}, m_FFTSize {6192 / 2}, // conservative value to avoid buffer overruns - m_soundInput {new SoundInput}, + m_soundInput {audio_input_source + ? audio_input_source.release () + : static_cast<AudioInputSource *> (new SoundInput)}, m_modulator {new Modulator {TX_SAMPLE_RATE, NTMAX}}, - m_soundOutput {new SoundOutput}, + m_jttyTxQueue {new TxAudioQueue}, + m_jttyTxStream {new JttyTxStream {*m_jttyTxQueue}}, + m_soundOutput {sound_output ? sound_output.release () : new SoundOutput}, m_rx_audio_buffer_frames {0}, m_tx_audio_buffer_frames {0}, m_msErase {0}, m_secBandChanged {0}, m_msDecStarted {0}, //ft8md - m_freqNominal {0}, + m_operatingFrequency {default_frequency}, m_freqNominalPeriod {0}, - m_freqTxNominal {0}, m_mslastTX {0}, //ft8md m_nlasttx {0}, //ft8md m_lapmyc {0}, //ft8md @@ -395,7 +590,6 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, m_sec0 {-1}, m_RxLog {1}, //Write Date and Time to RxLog m_nutc0 {999999}, - m_ntr {0}, m_tx {0}, m_mslastMon {0}, m_delay {0}, @@ -416,6 +610,7 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, m_txFirst {false}, m_auto {false}, m_restart {false}, + m_generated_message_error {false}, m_startAnother {false}, m_skipTx1 {false}, //ft8md m_filter {false}, //ft8md @@ -431,7 +626,7 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, m_saveAll {false}, m_widebandDecode {false}, m_dataAvailable {false}, - m_decodedText2 {false}, + m_bDecoded {false}, m_sentFirst73 {false}, m_tci_mod_active {false}, // TCI m_tci {false}, // TCI @@ -440,15 +635,13 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, m_lastMessageType {-1}, m_bShMsgs {false}, m_bSWL {false}, - m_uploading {false}, m_grid6 {false}, - m_tuneup {false}, m_bTxTime {false}, - m_rxDone {true}, m_bSimplex {false}, m_bEchoTxOK {false}, m_bTransmittedEcho {false}, m_bEchoTxed {false}, + m_bFast9 {false}, m_bFastDecodeCalled {false}, m_bDoubleClickAfterCQnnn {false}, m_bRefSpec {false}, @@ -473,61 +666,9 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, m_cqStr {""}, m_palette {"Linrad"}, m_mode {"FT8"}, - m_modeTx {"FT8"}, m_rpt {"-15"}, - m_pfx { - "1A", "1S", - "3A", "3B6", "3B8", "3B9", "3C", "3C0", "3D2", "3D2C", - "3D2R", "3DA", "3V", "3W", "3X", "3Y", "3YB", "3YP", - "4J", "4L", "4S", "4U1I", "4U1U", "4W", "4X", - "5A", "5B", "5H", "5N", "5R", "5T", "5U", "5V", "5W", "5X", "5Z", - "6W", "6Y", - "7O", "7P", "7Q", "7X", - "8P", "8Q", "8R", - "9A", "9G", "9H", "9J", "9K", "9L", "9M2", "9M6", "9N", - "9Q", "9U", "9V", "9X", "9Y", - "A2", "A3", "A4", "A5", "A6", "A7", "A9", "AP", - "BS7", "BV", "BV9", "BY", - "C2", "C3", "C5", "C6", "C9", "CE", "CE0X", "CE0Y", - "CE0Z", "CE9", "CM", "CN", "CP", "CT", "CT3", "CU", - "CX", "CY0", "CY9", - "D2", "D4", "D6", "DL", "DU", - "E3", "E4", "E5", "EA", "EA6", "EA8", "EA9", "EI", "EK", - "EL", "EP", "ER", "ES", "ET", "EU", "EX", "EY", "EZ", - "F", "FG", "FH", "FJ", "FK", "FKC", "FM", "FO", "FOA", - "FOC", "FOM", "FP", "FR", "FRG", "FRJ", "FRT", "FT5W", - "FT5X", "FT5Z", "FW", "FY", - "M", "MD", "MI", "MJ", "MM", "MU", "MW", - "H4", "H40", "HA", "HB", "HB0", "HC", "HC8", "HH", - "HI", "HK", "HK0", "HK0M", "HL", "HM", "HP", "HR", - "HS", "HV", "HZ", - "I", "IS", "IS0", - "J2", "J3", "J5", "J6", "J7", "J8", "JA", "JDM", - "JDO", "JT", "JW", "JX", "JY", - "K", "KC4", "KG4", "KH0", "KH1", "KH2", "KH3", "KH4", "KH5", - "KH5K", "KH6", "KH7", "KH8", "KH9", "KL", "KP1", "KP2", - "KP4", "KP5", - "LA", "LU", "LX", "LY", "LZ", - "OA", "OD", "OE", "OH", "OH0", "OJ0", "OK", "OM", "ON", - "OX", "OY", "OZ", - "P2", "P4", "PA", "PJ2", "PJ7", "PY", "PY0F", "PT0S", "PY0T", "PZ", - "R1F", "R1M", - "S0", "S2", "S5", "S7", "S9", "SM", "SP", "ST", "SU", - "SV", "SVA", "SV5", "SV9", - "T2", "T30", "T31", "T32", "T33", "T5", "T7", "T8", "T9", "TA", - "TF", "TG", "TI", "TI9", "TJ", "TK", "TL", "TN", "TR", "TT", - "TU", "TY", "TZ", - "UA", "UA2", "UA9", "UK", "UN", "UR", - "V2", "V3", "V4", "V5", "V6", "V7", "V8", "VE", "VK", "VK0H", - "VK0M", "VK9C", "VK9L", "VK9M", "VK9N", "VK9W", "VK9X", "VP2E", - "VP2M", "VP2V", "VP5", "VP6", "VP6D", "VP8", "VP8G", "VP8H", - "VP8O", "VP8S", "VP9", "VQ9", "VR", "VU", "VU4", "VU7", - "XE", "XF4", "XT", "XU", "XW", "XX9", "XZ", - "YA", "YB", "YI", "YJ", "YK", "YL", "YN", "YO", "YS", "YU", "YV", "YV0", - "Z2", "Z3", "ZA", "ZB", "ZC4", "ZD7", "ZD8", "ZD9", "ZF", "ZK1N", - "ZK1S", "ZK2", "ZK3", "ZL", "ZL7", "ZL8", "ZL9", "ZP", "ZS", "ZS8" - }, - m_sfx {"P", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A"}, + m_pfx {Radio::PrefixSuffix::type1Prefixes()}, + m_sfx {Radio::PrefixSuffix::type1Suffixes()}, mem_jt9 {shdmem}, m_downSampleFactor (downSampleFactor), m_audioThreadPriority (QThread::HighPriority), @@ -538,46 +679,85 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, m_transmitting {false}, m_tune {false}, m_tx_watchdog {false}, + m_jttyTxActive {false}, + m_jttyTxUsesTciAudio {false}, + m_jttyTxQueueEpoch {}, + m_jttyTxQueueProgress {}, + m_jttyTxRequestId {0}, + m_jttyTciEnqueueId {0}, m_block_pwr_tooltip {false}, m_PwrBandSetOK {true}, - m_lastMonitoredFrequency {default_frequency}, m_toneSpacing {0.}, - m_firstDecode {0}, - m_optimizingProgress {"Optimizing decoder FFTs for your CPU.\n" - "Please be patient,\n" - "this may take a few minutes", QString {}, 0, 1, this}, m_messageClient {new MessageClient {QApplication::applicationName (), version (), revision (), m_config.udp_server_name (), m_config.udp_server_port (), m_config.udp_interface_names (), m_config.udp_TTL (), this}}, - m_psk_Reporter {&m_config, QString {"WSJT-X v" + version()}.simplified()}, + m_psk_Reporter {&m_config, QString {"WSJT-X v" + version() + " " + m_revision}.simplified()}, m_manual {&m_network_manager}, m_block_udp_status_updates {false}, m_useDarkStyle {false} { + PerformanceTrace::milestone (m_startup_trace_run, "mainwindow.members_ready"); + PerformanceTrace::Phase ui_initialize {m_startup_trace_run, "mainwindow.ui_initialize"}; + programStart = true; + qApp->setFont (m_config.text_font ()); ui->setupUi(this); + configureModeControlsLayout (); + connect (ui->Tx_Message, &QLineEdit::textChanged, this, + [this] { m_jttyDraftAcceptanceTracker.noteDraftChanged (); }); + connect (this, &MainWindow::jttyTextAccepted, this, [this] (qint64 requestId) { + if (m_jttyDraftAcceptanceTracker.accept (requestId)) { + ui->Tx_Message->clear (); + } + }); + connect (this, &MainWindow::jttyTextRejected, this, + [this] (qint64 requestId, JttyTxRejectReason) { + m_jttyDraftAcceptanceTracker.reject (requestId); + }); + m_tx_message_button_group = new QButtonGroup {this}; + m_tx_message_button_group->addButton (ui->txrb1, 1); + m_tx_message_button_group->addButton (ui->txrb2, 2); + m_tx_message_button_group->addButton (ui->txrb3, 3); + m_tx_message_button_group->addButton (ui->txrb4, 4); + m_tx_message_button_group->addButton (ui->txrb5, 5); + m_tx_message_button_group->addButton (ui->txrb6, 6); + m_main_window_focus_frame = new QFocusFrame {this}; + m_main_window_focus_frame->hide (); + m_message_selector_focus_frame = new QFrame {ui->tabWidget->tabBar ()}; + m_message_selector_focus_frame->setAttribute (Qt::WA_TransparentForMouseEvents); + m_message_selector_focus_frame->setStyleSheet ( + "QFrame { border: 2px solid #0a84ff; border-radius: 4px; background: transparent; }"); + m_message_selector_focus_frame->setGeometry (ui->tabWidget->tabBar ()->rect ()); + m_message_selector_focus_frame->hide (); setUnifiedTitleAndToolBarOnMac (true); createStatusBar(); + updateMainWindowAccessibility(); + registerMainWindowFocusControls(); + m_event_filter_ready = true; add_child_to_event_filter (this); ui->dxGridEntry->setValidator (new MaidenheadLocatorValidator {this}); ui->dxCallEntry->setValidator (new CallsignValidator {this}); + ui->leEchoMessage->setValidator (new CallsignValidator {this, false}); ui->sbTR->values ({5, 10, 15, 30, 60, 120, 300, 900, 1800}); ui->sbTR_FST4W->values ({120, 300, 900, 1800}); ui->decodedTextBrowser->set_configuration (&m_config, true); ui->decodedTextBrowser2->set_configuration (&m_config); - m_optimizingProgress.setWindowModality (Qt::WindowModal); - m_optimizingProgress.setAutoReset (false); - m_optimizingProgress.setMinimumDuration (15000); // only show after 15s delay - //Attach or create a memory segment to be shared with QMAP. - int memSize=4096; + auto const memSize=static_cast<int>(QMapSharedMemorySize); + mem_qmap.setKey (qmap_decode_ipc::shared_memory_key ()); if(!mem_qmap.attach()) mem_qmap.create(memSize); - ipc_qmap = (int*)mem_qmap.data(); - mem_qmap.lock(); - memset(ipc_qmap,0,memSize); //Zero all of QMAP 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_qmap = qmap_decoder_region_available + ? static_cast<QMapSharedMemory *> (mem_qmap.data ()) : nullptr; + if (ipc_qmap && mem_qmap.lock ()) { + clearQMapSharedMemory (ipc_qmap, mappedSize); + mem_qmap.unlock (); + } // Closedown. connect (ui->actionExit, &QAction::triggered, this, &QMainWindow::close); @@ -589,8 +769,10 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, // start audio thread and hook up slots & signals for shutdown management // these objects need to be in the audio thread so that invoking // their slots is done in a thread safe way + Q_ASSERT (!m_soundInput->parent ()); m_soundOutput->moveToThread (&m_audioThread); m_modulator->moveToThread (&m_audioThread); + m_jttyTxStream->moveToThread (&m_audioThread); m_soundInput->moveToThread (&m_audioThread); m_detector->moveToThread (&m_audioThread); bool ok; @@ -611,31 +793,138 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, connect (this, &MainWindow::transmitFrequency, m_modulator, &Modulator::setFrequency); connect (this, &MainWindow::endTransmitMessage, m_modulator, &Modulator::stop); connect (this, &MainWindow::tune, m_modulator, &Modulator::tune); - connect (this, &MainWindow::sendMessage, m_modulator, &Modulator::start); + connect (this, &MainWindow::sendMessage, m_modulator, &Modulator::start, + Qt::QueuedConnection); + connect (m_modulator, &Modulator::txSourceCommitted, + this, &MainWindow::recordTxSourceCommit, Qt::QueuedConnection); +#if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) + connect (m_modulator, &Modulator::constrainedStartDecided, + this, [this] (qint64 sessionId, qint64 generation, + qint64 windowOpenMs, + bool accepted, qint64 actualStartMs) { + if (sessionId != m_liveAudioTestFt8StartSessionId + || generation != m_liveAudioTestFt8StartGeneration) + { + return; + } + m_liveAudioTestFt8StartSessionId = -1; + m_liveAudioTestFt8StartGeneration = -1; + if (!accepted) + { + m_tx_when_ready = false; + ptt1Timer.stop (); + stopTx (); + } + Q_EMIT liveAudioTestFt8TransmitStartDecided ( + sessionId, generation, windowOpenMs, accepted, actualStartMs); + }, Qt::QueuedConnection); +#endif + connect (m_soundOutput, &SoundOutput::rawTxPlayoutSnapshot, + this, &MainWindow::recordRawTxPlayout, Qt::QueuedConnection); connect (&m_audioThread, &QThread::finished, m_modulator, &QObject::deleteLater); + // hook up the JTTY async transmit stream slots and disposal + connect (this, &MainWindow::startJttyStream, m_jttyTxStream, &JttyTxStream::start, + Qt::QueuedConnection); + connect (m_jttyTxStream, &JttyTxStream::txSourceCommitted, + this, &MainWindow::recordTxSourceCommit, Qt::QueuedConnection); + connect (this, &MainWindow::endJttyStream, m_jttyTxStream, &JttyTxStream::stop); + connect (m_jttyTxStream, &JttyTxStream::drained, this, &MainWindow::onJttyBackendDrained); + connect (&m_audioThread, &QThread::finished, m_jttyTxStream, &QObject::deleteLater); + // hook up the audio input stream signals, slots and disposal - connect (this, &MainWindow::startAudioInputStream, m_soundInput, &SoundInput::start); - connect (this, &MainWindow::suspendAudioInputStream, m_soundInput, &SoundInput::suspend); - connect (this, &MainWindow::resumeAudioInputStream, m_soundInput, &SoundInput::resume); - connect (this, &MainWindow::reset_audio_input_stream, m_soundInput, &SoundInput::reset); - connect (this, &MainWindow::finished, m_soundInput, &SoundInput::stop); - connect(m_soundInput, &SoundInput::error, this, &MainWindow::showSoundInError); - connect(m_soundInput, &SoundInput::error, &m_config, &Configuration::invalidate_audio_input_device); - // connect(m_soundInput, &SoundInput::status, this, &MainWindow::showStatusMessage); + connect (this, &MainWindow::startAudioInputStream, m_soundInput, &AudioInputSource::start); + connect (this, &MainWindow::suspendAudioInputStream, m_soundInput, &AudioInputSource::suspend); + connect (this, &MainWindow::resumeAudioInputStream, m_soundInput, &AudioInputSource::resume); + connect (this, &MainWindow::stopAudioInputStream, m_soundInput, &AudioInputSource::stop); + connect (this, &MainWindow::reset_audio_input_stream, m_soundInput, &AudioInputSource::reset); + connect (this, &MainWindow::finished, m_soundInput, &AudioInputSource::stop); + connect (m_soundInput, &AudioInputSource::streamDescriptorChanged, + m_detector, &Detector::setStreamDescriptor); + connect (m_soundInput, &AudioInputSource::streamDescriptorChanged, this, + [this] (AudioStreamDescriptor const&) { + if (!m_startup_audio_reported) + { + m_startup_audio_reported = true; + PerformanceTrace::milestone (m_startup_trace_run, "audio.input_ready"); + } + }); + if (!m_automated_test) + { + connect(m_soundInput, &AudioInputSource::error, this, &MainWindow::showSoundInError); + } + connect(m_soundInput, &AudioInputSource::error, &m_config, &Configuration::invalidate_audio_input_device); + // connect(m_soundInput, &AudioInputSource::status, this, &MainWindow::showStatusMessage); connect (&m_audioThread, &QThread::finished, m_soundInput, &QObject::deleteLater); connect (this, &MainWindow::finished, this, &MainWindow::close); // hook up the detector signals, slots and disposal connect (this, &MainWindow::FFTSize, m_detector, &Detector::setBlockSize); - connect(m_detector, &Detector::framesWritten, this, &MainWindow::dataSink); + auto const live_data_sink = [this] (ReceiveAudio audio) { + m_receiveQueue.enqueue (std::move (audio)); + // decode() may dispatch GUI events. Queue nested deliveries until the + // current DSP invocation has finished using its consumer-owned samples. + if (m_receivingAudio) return; + m_receivingAudio = true; + while (!m_receiveQueue.isEmpty ()) + { + auto const block = m_receiveQueue.dequeue (); +#if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) + if (m_automated_test) Q_EMIT liveAudioTestReceiveBlock (block); +#endif + if (m_wav_load_coordinator.isLoading () || m_diskData) + { + m_receiveConsumer.invalidate (); + continue; + } + auto const previousEpoch = m_receiveConsumer.epoch (); + if (!m_receiveConsumer.accept (block, dec_data)) + { +#if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) + if (m_automated_test) + { + Q_EMIT liveAudioTestReceiveRejected (block->end ()); + Q_EMIT liveAudioTestReceiveRange (block->epoch, block->start, block->end (), false); + } +#endif + continue; + } + if (previousEpoch != m_receiveConsumer.epoch ()) m_referenceInput.reset (); + auto const frames = block->end (); +#if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) + if (m_automated_test) + Q_EMIT liveAudioTestReceiveRange (block->epoch, block->start, frames, true); + if (m_automated_test && frames > 0 + && isSignalConnected (QMetaMethod::fromSignal ( + &MainWindow::liveAudioTestReceiveCallback))) + { + QMutexLocker lock {&dec_data_mutex ()}; + auto const currentFrames = qint64 {block->sourceFrames ()}; + auto const sample = frames <= currentFrames + ? dec_data.d2[frames - 1] : qint16 {0}; + Q_EMIT liveAudioTestReceiveCallback (frames, currentFrames, sample); + } +#endif + m_activeReceiveAudio = block; + dataSink (frames); + m_activeReceiveAudio.reset (); + } + m_receivingAudio = false; + }; + connect (m_detector, &Detector::audioBlock, this, + [this, live_data_sink] (ReceiveAudio audio) { + if (!m_tci_audio) live_data_sink (std::move (audio)); + }); connect (&m_audioThread, &QThread::finished, m_detector, &QObject::deleteLater); // setup the waterfall connect(m_wideGraph.data (), SIGNAL(freezeDecode2(int)),this,SLOT(freezeDecode(int))); connect(m_wideGraph.data (), SIGNAL(f11f12(int)),this,SLOT(bumpFqso(int))); connect(m_wideGraph.data (), SIGNAL(setXIT2(int)),this,SLOT(setXIT(int))); + connect(m_wideGraph.data (), SIGNAL(jttyDecodeAgainAt2(float)),this,SLOT(jttyDecodeAgainAt(float))); + m_wideGraph->setReferenceSpectrumAvailable( + QFile::exists(m_config.writeable_data_dir ().absoluteFilePath ("refspec.dat"))); connect (m_fastGraph.data (), &FastGraph::fastPick, this, &MainWindow::fastPick); @@ -649,6 +938,14 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, // hook up the log book connect (&m_logBook, &LogBook::finished_loading, [this] (int record_count, QString cty_version, QString const& error) { + if (!m_startup_logbook_reported) + { + m_startup_logbook_reported = true; + PerformanceTrace::milestone ( + m_startup_trace_run, "logbook.ready", + QString {"status=%1 unique_entries=%2"} + .arg (error.isEmpty () ? "ok" : "error").arg (record_count)); + } if (error.size ()) { MessageBox::warning_message (this, tr ("Error Scanning ADIF Log"), error); @@ -662,6 +959,10 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, // Network message handlers m_messageClient->enable (m_config.accept_udp_requests ()); + connect (m_messageClient, &MessageClient::tx_inhibit_command, + &m_config, &Configuration::tx_inhibit_command); + connect (m_messageClient, &MessageClient::tx_inhibit_invalid, + &m_config, &Configuration::tx_inhibit_invalid); connect (m_messageClient, &MessageClient::clear_decodes, [this] (quint8 window) { ++window; if (window & 1) @@ -688,13 +989,17 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, }); connect (m_messageClient, &MessageClient::error, this, &MainWindow::networkError); connect (m_messageClient, &MessageClient::free_text, [this] (QString const& text, bool send) { + if (!MainWindow::message_alphabet.exactMatch (text)) { + qWarning () << "Ignoring UDP FreeText request with invalid message characters"; + return; + } tx_watchdog (false); // send + non-empty text means set and send the free text // message, !send + non-empty text means set the current free // text message, send + empty text means send the current free // text message without change, !send + empty text means clear // the current free text message - if (0 == ui->tabWidget->currentIndex ()) { + if (standard_messages_tab_index == ui->tabWidget->currentIndex ()) { if (!text.isEmpty ()) { ui->tx5->setCurrentText (text); } @@ -729,6 +1034,7 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, ui->actionJT4->setActionGroup(modeGroup); ui->actionWSPR->setActionGroup(modeGroup); ui->actionEcho->setActionGroup(modeGroup); + ui->actionJTTY->setActionGroup(modeGroup); ui->actionMSK144->setActionGroup(modeGroup); ui->actionQ65->setActionGroup(modeGroup); ui->actionFreqCal->setActionGroup(modeGroup); @@ -791,6 +1097,28 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, ui->actionMT11->setActionGroup(FT8threadsGroup); ui->actionMT12->setActionGroup(FT8threadsGroup); + auto resetFt8Backpressure = [this] (QAction *) { + cancelPendingFt8Decode ("decoder setting changed"); + }; + connect (DepthGroup, &QActionGroup::triggered, this, resetFt8Backpressure); + connect (FT8CyclesGroup, &QActionGroup::triggered, this, resetFt8Backpressure); + connect (FT8RXfreqSensitivityGroup, &QActionGroup::triggered, + this, resetFt8Backpressure); + connect (FT8DecoderSensitivityGroup, &QActionGroup::triggered, + this, resetFt8Backpressure); + connect (FT8DecoderStartGroup, &QActionGroup::triggered, + this, resetFt8Backpressure); + connect (FT8threadsGroup, &QActionGroup::triggered, + this, resetFt8Backpressure); + connect (ui->actionUse_multithreaded_FT8_decoder, &QAction::toggled, + this, [this] {cancelPendingFt8Decode ("FT8 decoder changed");}); + connect (ui->actionFT8WidebandDXCallSearch, &QAction::toggled, + this, [this] {cancelPendingFt8Decode ("FT8 decoder changed");}); + connect (ui->actionHide_FT8_dupe_messages, &QAction::toggled, + this, [this] {cancelPendingFt8Decode ("FT8 decoder changed");}); + connect (ui->actionEnable_AP_FT8, &QAction::toggled, + this, [this] {cancelPendingFt8Decode ("FT8 decoder changed");}); + connect (ui->download_samples_action, &QAction::triggered, [this] () { if (!m_sampleDownloader) { @@ -815,15 +1143,8 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, MessageBox::warning_message (this, tr ("Error Loading LotW Users Data"), reason); }, Qt::QueuedConnection); - QButtonGroup* txMsgButtonGroup = new QButtonGroup {this}; - txMsgButtonGroup->addButton(ui->txrb1,1); - txMsgButtonGroup->addButton(ui->txrb2,2); - txMsgButtonGroup->addButton(ui->txrb3,3); - txMsgButtonGroup->addButton(ui->txrb4,4); - txMsgButtonGroup->addButton(ui->txrb5,5); - txMsgButtonGroup->addButton(ui->txrb6,6); set_dateTimeQSO(-1); - connect(txMsgButtonGroup,SIGNAL(buttonClicked(int)),SLOT(set_ntx(int))); + connect (m_tx_message_button_group, SIGNAL (buttonClicked (int)), SLOT (set_ntx (int))); connect (ui->decodedTextBrowser, &DisplayText::selectCallsign, this, &MainWindow::doubleClickOnCall2); connect (ui->decodedTextBrowser2, &DisplayText::selectCallsign, this, &MainWindow::doubleClickOnCall); connect (ui->houndQueueTextBrowser, &DisplayText::selectCallsign, this, &MainWindow::doubleClickOnFoxQueue); @@ -832,10 +1153,8 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, connect (ui->decodedTextBrowser2, &DisplayText::erased, this, &MainWindow::rx_frequency_activity_cleared); connect (ui->decodedTextBrowser->horizontalScrollBar(),SIGNAL(sliderMoved(int)),SLOT(ScrollBarPosition(int))); - // initialize decoded text font and hook up font change signals - // defer initialization until after construction otherwise menu fonts do not get set - // with 50 ms delay we are on the safe side - QTimer::singleShot (50, this, SLOT (initialize_fonts ())); + // Native menu fonts require a refresh after main window construction. + QTimer::singleShot (0, this, SLOT (initialize_fonts ())); connect (&m_config, &Configuration::text_font_changed, [this] (QFont const& font) { set_application_font (font); }); @@ -843,23 +1162,86 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, setDecodedTextFont (font); }); - setWindowTitle (program_title ()); + setWindowTitle (branded_program_title ()); + connect(&proc_jt9, &QProcess::started, this, [this] { + if (!m_startup_decoder_reported) + { + m_startup_decoder_reported = true; + PerformanceTrace::milestone (m_startup_trace_run, "decoder.process_started"); + } + if (Jt9ProcessPhase::InitialStarting == m_jt9ProcessPhase + || Jt9ProcessPhase::ReplacementStarting == m_jt9ProcessPhase) + { + m_decoderStartTimer.stop (); + m_decoderCompletedSinceStart = false; + m_jt9ProcessPhase = Jt9ProcessPhase::Ready; + updateDecodeControls (); + QTimer::singleShot (0, this, [this] { + auto const pendingResult = publishPendingFt8Decode (); + if (DecodePublishResult::Failed == pendingResult) + { + requestDecoderRestart ( + "pending FT8 decode publication failed after restart"); + } + }); + } + }); connect(&proc_jt9, &QProcess::readyReadStandardOutput, this, &MainWindow::readFromStdout); + connect(&proc_jt9, &QProcess::started, this, &MainWindow::decoderBackendStarted); #if QT_VERSION < QT_VERSION_CHECK (5, 6, 0) connect(&proc_jt9, static_cast<void (QProcess::*) (QProcess::ProcessError)> (&QProcess::error), [this] (QProcess::ProcessError error) { + if ((Jt9ProcessPhase::StopRequested == m_jt9ProcessPhase + || Jt9ProcessPhase::Terminating == m_jt9ProcessPhase + || Jt9ProcessPhase::Killing == m_jt9ProcessPhase) + && QProcess::Crashed == error) return; + Q_EMIT decoderBackendFailed (proc_jt9.errorString ()); subProcessError (&proc_jt9, error); }); #else connect(&proc_jt9, &QProcess::errorOccurred, [this] (QProcess::ProcessError error) { + if ((Jt9ProcessPhase::StopRequested == m_jt9ProcessPhase + || Jt9ProcessPhase::Terminating == m_jt9ProcessPhase + || Jt9ProcessPhase::Killing == m_jt9ProcessPhase) + && QProcess::Crashed == error) return; + Q_EMIT decoderBackendFailed (proc_jt9.errorString ()); subProcessError (&proc_jt9, error); }); #endif connect(&proc_jt9, static_cast<void (QProcess::*) (int, QProcess::ExitStatus)> (&QProcess::finished), [this] (int exitCode, QProcess::ExitStatus status) { - if (subProcessFailed (&proc_jt9, exitCode, status)) + if (m_closing) return; + if (decoderRestartInProgress ()) { + m_decoderShutdownTimer.stop (); + m_decoderTerminateTimer.stop (); + m_decoderKillTimer.stop (); + m_decoderStartTimer.stop (); + proc_jt9.readAllStandardOutput (); + proc_jt9.readAllStandardError (); + if (!initializeDecoderSharedMemory ()) + { + m_valid = false; + QTimer::singleShot (0, this, SLOT (close ())); + return; + } + m_jt9PayloadValid = false; + m_activeJt9Decode = {}; + m_decoderOutputFramer.reset (); + startDecoderProcess (); + return; + } + auto const failed = subProcessFailed (&proc_jt9, exitCode, status); + if (!failed && m_valid) + { + MessageBox::critical_message (this, tr ("Decoder Error"), + tr ("The decoder subprocess exited unexpectedly.")); + } + if (m_valid) + { + Q_EMIT decoderBackendFailed ( + tr ("jt9 exited unexpectedly with code %1.").arg (exitCode)); m_valid = false; // ensures exit if still // constructing QTimer::singleShot (0, this, SLOT (close ())); @@ -928,7 +1310,7 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, }); // hook up save WAV file exit handling - connect (&m_saveWAVWatcher, &QFutureWatcher<QString>::finished, [this] { + connect (&m_saveWAVWatcher, &QFutureWatcher<QString>::finished, this, [this] { // extract the promise from the future auto const& result = m_saveWAVWatcher.future ().result (); if (!result.isEmpty ()) // error @@ -945,20 +1327,33 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, auto band_validator = new LiveFrequencyValidator {ui->bandComboBox , m_config.bands () , m_config.frequencies () - , &m_freqNominal + , &m_operatingFrequency.rx () , m_config.kHz_without_k () , this}; ui->bandComboBox->setValidator (band_validator); // Hook up signals. - connect (band_validator, &LiveFrequencyValidator::valid, this, &MainWindow::band_changed); + connect (band_validator, &LiveFrequencyValidator::valid, this, [this] (Frequency frequency) { + requestBandChange (frequency, FrequencyRequestOrigin::User); + }); connect (ui->bandComboBox->lineEdit (), &QLineEdit::textEdited, [this] (QString const&) {m_bandEdited = true;}); // hook up configuration signals connect (&m_config, &Configuration::leavingSettings, this, &MainWindow::handle_leavingSettings); connect (&m_config, &Configuration::transceiver_update, this, &MainWindow::handle_transceiver_update); - connect (&m_config, &Configuration::transceiver_TCIframesWritten, this, &MainWindow::dataSink); + connect (&m_config, &Configuration::transceiverReceiveAudio, this, + [this, live_data_sink] (ReceiveAudio audio) { + if (m_tci_audio) live_data_sink (std::move (audio)); + }); connect (&m_config, &Configuration::transceiver_TCImodActive, this, &MainWindow::tci_mod_active); + connect (&m_config, &Configuration::txSourceCommitted, + this, &MainWindow::recordTxSourceCommit, Qt::QueuedConnection); + connect (&m_config, &Configuration::rawTxPlayoutSnapshot, + this, &MainWindow::recordRawTxPlayout, Qt::QueuedConnection); + connect (&m_config, &Configuration::transceiver_jtty_drained, this, &MainWindow::onJttyBackendDrained); + connect (&m_config, &Configuration::transceiver_jtty_enqueue_accepted, this, &MainWindow::onJttyBackendEnqueueAccepted); + connect (&m_config, &Configuration::transceiver_jtty_enqueue_failed, this, &MainWindow::onJttyBackendEnqueueFailed); + connect (&m_config, &Configuration::transceiver_closing, this, &MainWindow::handle_transceiver_closing); connect (&m_config, &Configuration::transceiver_failure, this, &MainWindow::handle_transceiver_failure); connect (&m_config, &Configuration::udp_server_changed, m_messageClient, &MessageClient::set_server); connect (&m_config, &Configuration::udp_server_port_changed, m_messageClient, &MessageClient::set_server_port); @@ -979,13 +1374,16 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, } if (!programStart) { // set programStart to true for 2 seconds when changing Configurations programStart = true; - QTimer::singleShot (2000, [=] {programStart=false;}); + QTimer::singleShot (2000, this, [=] {programStart=false;}); } statusUpdate (); #if defined(Q_OS_WIN) - QTimer::singleShot (250, [=] { - setRig (m_lastMonitoredFrequency); // This is needed for Hamradio Deluxe - m_msk144basefreq = m_lastMonitoredFrequency; // This is needed for Hamradio Deluxe + QTimer::singleShot (250, this, [=] { + if (requestNominalFrequencyChange ( + m_operatingFrequency.remembered (), FrequencyRequestOrigin::Automatic)) + { + m_msk144basefreq = m_operatingFrequency.remembered (); // This is needed for Hamradio Deluxe + } }); #endif }); @@ -994,12 +1392,12 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, , QMessageBox::ActionRole); // set up message text validators - ui->tx1->setValidator (new QRegExpValidator {message_alphabet, this}); - ui->tx2->setValidator (new QRegExpValidator {message_alphabet, this}); - ui->tx3->setValidator (new QRegExpValidator {message_alphabet, this}); - ui->tx4->setValidator (new QRegExpValidator {message_alphabet, this}); - ui->tx5->setValidator (new QRegExpValidator {message_alphabet, this}); - ui->tx6->setValidator (new QRegExpValidator {message_alphabet, this}); + ui->tx1->setValidator (new QRegExpValidator {MainWindow::message_alphabet, this}); + ui->tx2->setValidator (new QRegExpValidator {MainWindow::message_alphabet, this}); + ui->tx3->setValidator (new QRegExpValidator {MainWindow::message_alphabet, this}); + ui->tx4->setValidator (new QRegExpValidator {MainWindow::message_alphabet, this}); + ui->tx5->setValidator (new QRegExpValidator {MainWindow::message_alphabet, this}); + ui->tx6->setValidator (new QRegExpValidator {MainWindow::message_alphabet, this}); // Free text macros model to widget hook up. ui->tx5->setModel (m_config.macros ()); @@ -1008,6 +1406,41 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, connect(&m_guiTimer, &QTimer::timeout, this, &MainWindow::guiUpdate); m_guiTimer.start(100); //### Don't change the 100 ms! ### + m_decoderShutdownTimer.setSingleShot (true); + connect (&m_decoderShutdownTimer, &QTimer::timeout, this, [this] { + if (Jt9ProcessPhase::StopRequested != m_jt9ProcessPhase + || QProcess::NotRunning == proc_jt9.state ()) return; + m_jt9ProcessPhase = Jt9ProcessPhase::Terminating; + proc_jt9.terminate (); + m_decoderTerminateTimer.start (1000); + }); + m_decoderTerminateTimer.setSingleShot (true); + connect (&m_decoderTerminateTimer, &QTimer::timeout, this, [this] { + if (Jt9ProcessPhase::Terminating != m_jt9ProcessPhase + || QProcess::NotRunning == proc_jt9.state ()) return; + m_jt9ProcessPhase = Jt9ProcessPhase::Killing; + proc_jt9.kill (); + m_decoderKillTimer.start (2000); + }); + m_decoderKillTimer.setSingleShot (true); + connect (&m_decoderKillTimer, &QTimer::timeout, this, [this] { + if (Jt9ProcessPhase::Killing != m_jt9ProcessPhase + || QProcess::NotRunning == proc_jt9.state ()) return; + MessageBox::critical_message (this, tr ("Decoder Error"), + tr ("The decoder subprocess could not be stopped.")); + m_valid = false; + QTimer::singleShot (0, this, SLOT (close ())); + }); + m_decoderStartTimer.setSingleShot (true); + connect (&m_decoderStartTimer, &QTimer::timeout, this, [this] { + if (Jt9ProcessPhase::ReplacementStarting != m_jt9ProcessPhase + || QProcess::Running == proc_jt9.state ()) return; + MessageBox::critical_message (this, tr ("Decoder Error"), + tr ("The decoder subprocess could not be restarted.")); + m_valid = false; + QTimer::singleShot (0, this, SLOT (close ())); + }); + stopWRTimer.setSingleShot(true); connect(&stopWRTimer, &QTimer::timeout, this, &MainWindow::stopWRTimeout); @@ -1020,6 +1453,12 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, ptt1Timer.setSingleShot(true); connect(&ptt1Timer, &QTimer::timeout, this, &MainWindow::startTx2); + m_jttyTxWatchdog.setSingleShot(true); + connect(&m_jttyTxWatchdog, &QTimer::timeout, this, &MainWindow::handleJttyTxWatchdog); + + m_refSpecTimer.setInterval(1000); + connect(&m_refSpecTimer, &QTimer::timeout, this, &MainWindow::updateReferenceSpectrumCountdown); + p1Timer.setSingleShot(true); connect(&p1Timer, &QTimer::timeout, this, &MainWindow::startP1); @@ -1029,14 +1468,21 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, tuneButtonTimer.setSingleShot(true); connect(&tuneButtonTimer, &QTimer::timeout, this, &MainWindow::end_tuning); + rigTuneTimer.setSingleShot (true); + connect (&rigTuneTimer, &QTimer::timeout, this, [this] { + m_config.transceiver_tune (false); + ui->tuneButton->setChecked (false); + ui->tuneButton->setText ("Tune"); + }); + tuneATU_Timer.setSingleShot(true); connect(&tuneATU_Timer, &QTimer::timeout, this, &MainWindow::stopTuneATU); killFileTimer.setSingleShot(true); - connect(&killFileTimer, &QTimer::timeout, this, &MainWindow::killFile); + connect(&killFileTimer, &QTimer::timeout, this, &MainWindow::killWaveFile); uploadTimer.setSingleShot(true); - connect(&uploadTimer, &QTimer::timeout, [this] () {uploadWSPRSpots ();}); + connect(&uploadTimer, &QTimer::timeout, [this] () {uploadWSPRSpots ("FST4W" == m_mode);}); TxAgainTimer.setSingleShot(true); connect(&TxAgainTimer, SIGNAL(timeout()), this, SLOT(TxAgain())); @@ -1044,7 +1490,7 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, connect(m_wideGraph.data (), SIGNAL(setFreq3(int,int)),this, SLOT(setFreq4(int,int))); - decodeBusy(false); + updateDecodeControls (); m_msg[0][0]=0; @@ -1054,11 +1500,13 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, auto dBm = int ((10. * i / 3.) + .5); ui->TxPowerComboBox->addItem (QString {"%1 dBm %2"}.arg (dBm).arg (power[i]), dBm); } - ui->respondComboBox->addItem("CQ: None"); - ui->respondComboBox->addItem("CQ: First"); - ui->respondComboBox->addItem("CQ: Max Dist"); - ui->respondComboBox->addItem("CQ: Max dB"); - ui->respondComboBox->addItem("CQ: Min dB"); + ui->respondComboBox->addItem(tr ("CQ: None"), static_cast<int> (AutoRespondPolicy::None)); + ui->respondComboBox->addItem(tr ("CQ: First"), static_cast<int> (AutoRespondPolicy::First)); + ui->respondComboBox->addItem(tr ("CQ: Max Dist"), static_cast<int> (AutoRespondPolicy::MaxDistance)); + ui->respondComboBox->addItem(tr ("CQ: Max dB"), static_cast<int> (AutoRespondPolicy::MaxSignal)); + ui->respondComboBox->addItem(tr ("CQ: Min dB"), static_cast<int> (AutoRespondPolicy::MinSignal)); + + RoundRobinSelection::initialize (*ui->RoundRobin, tr ("Random")); m_dateTimeRcvdRR73=QDateTime::currentDateTimeUtc(); m_dateTimeSentTx3=QDateTime::currentDateTimeUtc(); @@ -1066,9 +1514,19 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, ui->labAz->setStyleSheet("border: 0px;"); ui->labAz->setText(""); auto t = "UTC dB DT Freq " + tr ("Message"); - ui->lh_decodes_headings_label->setText(t); - ui->rh_decodes_headings_label->setText(t); + setDecodeHeadings(t, t); + ui_initialize.finish (); + PerformanceTrace::Phase settings_restore {m_startup_trace_run, "mainwindow.settings_restore"}; readSettings(); //Restore user's setup parameters + settings_restore.finish (); + PerformanceTrace::Phase runtime_initialize {m_startup_trace_run, "mainwindow.runtime_initialize"}; + connect (ui->respondComboBox, QOverload<int>::of (&QComboBox::currentIndexChanged), this, + [this] (int) { + if (AutoRespondPolicy::None == autoRespondPolicy()) { + m_autoRespondPeriodState.disarm(); + } + check_button_color(); + }); if(m_mode=="Q65") { m_score=0; read_log(); @@ -1105,73 +1563,71 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, } } - to_jt9(0,0,0); //initialize IPC variables - - QStringList jt9_args { - "-s", QApplication::applicationName () // shared memory key, - // includes rig -#ifdef NDEBUG - , "-w", "1" //FFTW patience - release -#else - , "-w", "1" //FFTW patience - debug builds for speed -#endif - // The number of threads for FFTW specified here is chosen as - // three because that gives the best throughput of the large - // FFTs used in jt9. The count is the minimum of (the number - // available CPU threads less one) and three. This ensures that - // there is always at least one free CPU thread to run the other - // mode decoder in parallel. - , "-m", QString::number (qMin (qMax (QThread::idealThreadCount () - 1, 1), 3)) //FFTW threads - - , "-e", QDir::toNativeSeparators (m_appDir) - , "-a", QDir::toNativeSeparators (m_config.writeable_data_dir ().absolutePath ()) - , "-t", QDir::toNativeSeparators (m_config.temp_dir ().absolutePath ()) - }; - QProcessEnvironment new_env {m_env}; - new_env.insert ("OMP_STACKSIZE", "10M"); - proc_jt9.setProcessEnvironment (new_env); - proc_jt9.start(QDir::toNativeSeparators (m_appDir) + QDir::separator () + - "jt9", jt9_args, QIODevice::ReadWrite | QIODevice::Unbuffered); + { + PerformanceTrace::Phase decoder_start {m_startup_trace_run, "decoder.start_request"}; + startDecoderProcess (); + } - auto fname {QDir::toNativeSeparators(m_config.writeable_data_dir ().absoluteFilePath ("wsjtx_wisdom.dat"))}; - fftwf_import_wisdom_from_filename (fname.toLocal8Bit ()); + { + PerformanceTrace::Phase wisdom_import {m_startup_trace_run, "fft_wisdom.import"}; + auto fname {QDir::toNativeSeparators(m_config.writeable_data_dir ().absoluteFilePath ("wsjtx_wisdom.dat"))}; + fftwf_import_wisdom_from_filename (fname.toLocal8Bit ()); + } m_ntx = 6; ui->txrb6->setChecked(true); - connect (&m_wav_future_watcher, &QFutureWatcher<void>::finished, this, &MainWindow::diskDat); - - connect(&watcher3, SIGNAL(finished()),this,SLOT(fast_decode_done())); + connect (&m_wav_load_coordinator, &WavLoadCoordinator::loadingChanged, + this, [this] (bool) { + updateDecodeControls (); + }); + connect (&m_wav_load_coordinator, &WavLoadCoordinator::resultReady, + this, &MainWindow::wav_file_loaded); + + connect (&watcher3, &QFutureWatcher<FastDecodeResult>::finished, this, [this] { + auto const result = watcher3.result (); + std::copy (result.arguments.begin (), result.arguments.end (), narg); + std::memcpy (m_msg, result.messages.data (), sizeof m_msg); + m_fastDecodePending = false; + fast_decode_done (); + }); m_tci = m_config.is_tci(); m_tci_audio = (m_config.tci_audio() && m_config.is_tci()); - if (!m_tci_audio) { - if (!m_config.audio_input_device ().isNull ()) - { - Q_EMIT startAudioInputStream (m_config.audio_input_device () - , m_rx_audio_buffer_frames - , m_detector, m_downSampleFactor, m_config.audio_input_channel ()); - } - if (!m_config.audio_output_device ().isNull ()) - { - Q_EMIT initializeAudioOutputStream (m_config.audio_output_device () - , AudioDevice::Mono == m_config.audio_output_channel () ? 1 : 2 - , m_tx_audio_buffer_frames); - } - Q_EMIT transmitFrequency (ui->TxFreqSpinBox->value () - m_XIT); + { + PerformanceTrace::Phase audio_start {m_startup_trace_run, "audio.start_request"}; + if (!m_tci_audio) { + Q_EMIT startAudioInputStream (m_config.audio_input_device () + , m_rx_audio_buffer_frames + , m_detector, m_downSampleFactor, m_config.audio_input_channel ()); + if (!m_config.audio_output_device ().isNull ()) + { + Q_EMIT initializeAudioOutputStream (m_config.audio_output_device () + , AudioDevice::Mono == m_config.audio_output_channel () ? 1 : 2 + , m_tx_audio_buffer_frames); + } + Q_EMIT transmitFrequency (ui->TxFreqSpinBox->value () - m_XIT); + } } - enable_DXCC_entity (m_config.DXCC ()); // sets text window proportions and (re)inits the logbook + { + PerformanceTrace::Phase logbook_initialize {m_startup_trace_run, "logbook.initialize_request"}; + enable_DXCC_entity (m_config.DXCC ()); // sets text window proportions and (re)inits the logbook + } // this must be done before initializing the mode as some modes need // to turn off split on the rig e.g. WSPR - m_config.transceiver_online (); + { + PerformanceTrace::Phase rig_start {m_startup_trace_run, "rig.start_request"}; + m_config.transceiver_online (); + } bool vhf {m_config.enable_VHF_features ()}; ui->txFirstCheckBox->setChecked(m_txFirst); morse_(const_cast<char *> (m_config.my_callsign ().toLatin1().constData()), const_cast<int *> (icw), &m_ncw, (FCL)m_config.my_callsign().length()); + PerformanceTrace::Phase mode_initialize {m_startup_trace_run, "mode.initialize"}; on_actionWide_Waterfall_triggered(); ui->cbShMsgs->setChecked(m_bShMsgs); ui->cbSWL->setChecked(m_bSWL); @@ -1183,10 +1639,15 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, // Ensure that the correct frequency is set and displayed if(m_mode=="Echo") { - QTimer::singleShot (5000, [=] { - auto const& row = m_config.frequencies ()->best_working_frequency (m_freqNominal); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); + QTimer::singleShot (5000, this, [=] { + auto const& row = m_config.frequencies ()->best_working_frequency (m_operatingFrequency.rx ()); + Frequency frequency; + if (workingFrequencyAt (row, frequency) + && nominalFrequencyChangeAllowed (FrequencyRequestOrigin::Automatic)) + { + ui->bandComboBox->setCurrentIndex (row); + requestBandChange (frequency, FrequencyRequestOrigin::Automatic); + } if (m_monitoring) ui->monitorButton->click(); }); } @@ -1195,7 +1656,7 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, if(m_mode=="MSK144") { if (m_tci_audio) { - QTimer::singleShot (5000, [=] { + QTimer::singleShot (5000, this, [=] { if (ui->bandComboBox->currentText()!="OOB") { Q_EMIT m_config.transceiver_trfrequency(1000.0); } else { @@ -1207,7 +1668,7 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, } } else { if (m_tci_audio) { - QTimer::singleShot (5000, [=] { + QTimer::singleShot (5000, this, [=] { if (ui->bandComboBox->currentText()!="OOB") { Q_EMIT m_config.transceiver_trfrequency(ui->TxFreqSpinBox->value () - m_XIT); } else { @@ -1221,10 +1682,8 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, if(m_tci_audio) { - QTimer::singleShot (5000, [=] { - int attVal = ui->outAttenuation->value(); - ui->outAttenuation->setValue(0); - ui->outAttenuation->setValue(attVal); + QTimer::singleShot (5000, this, [=] { + sync_tci_tx_volume (true); Q_EMIT m_config.transceiver_volume(m_config.volume()); }); } @@ -1249,7 +1708,7 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, m_bNoMoreFiles=false; m_bDoubleClicked=false; m_bCallingCQ=false; - m_bCheckedContest=false; + m_contestModeHintShown=false; m_bDisplayedOnce=false; m_wait=0; m_isort=-3; @@ -1265,6 +1724,7 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, m_fastGraph->setMode(m_mode); m_wideGraph->setMode(m_mode); + mode_initialize.finish (); connect (&minuteTimer, &QTimer::timeout, this, &MainWindow::bandHoppingTimer); connect (&minuteTimer, &QTimer::timeout, this, &MainWindow::on_the_minute); @@ -1277,11 +1737,6 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, splashTimer.setSingleShot (true); splashTimer.start (20 * 1000); - if(QCoreApplication::applicationVersion().contains("-devel") or - QCoreApplication::applicationVersion().contains("-rc")) { -// QTimer::singleShot (0, this, SLOT (not_GA_warning_message ())); - } - m_bMyCallStd=stdCall(m_config.my_callsign ()); //ft8md m_bHisCallStd=stdCall(m_hisCall); //ft8md @@ -1290,24 +1745,39 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, // Starting in FT8 Hound mode needs this initialization if (m_specOp==SpecOp::HOUND) { on_ft8Button_clicked(); - QTimer::singleShot (50, [=] {ui->houndButton->click();}); + QTimer::singleShot (50, this, [=] {ui->houndButton->click();}); } - ui->labDXped->setVisible(SpecOp::NONE != m_specOp); - ui->labDXped->setStyleSheet("QLabel {background-color: red; color: white;}"); + auto const activityLabel = specOpLabel(); + ui->labDXped->setText(activityLabel); + ui->labDXped->setVisible(!activityLabel.isEmpty()); + updateHoundVerificationStyle (); ui->pbBestSP->setVisible(m_mode=="FT4"); update_foxLogWindow_rate(); // update the rate on the window check_button_color(); - read_txLog(); - read_ignoreList(); - read_ALLCALL7(); + { + PerformanceTrace::Phase tx_log_load {m_startup_trace_run, "tx_log.load"}; + read_txLog(); + } + { + PerformanceTrace::Phase ignore_list_load {m_startup_trace_run, "ignore_list.load"}; + read_ignoreList(); + } + { + PerformanceTrace::Phase allcall_load {m_startup_trace_run, "allcall.load"}; + read_ALLCALL7(); + } if (ui->actionRemove_after_30days->isChecked ()) { + PerformanceTrace::Phase saved_audio_cleanup {m_startup_trace_run, "saved_audio.cleanup"}; remove_old_files(m_config.save_directory().absolutePath(), 30); // remove saved audio files after 30 days } - QString jpleph = m_config.data_dir().absoluteFilePath("JPLEPH"); - jpl_setup_(const_cast<char *>(jpleph.toLocal8Bit().constData()),256); + { + PerformanceTrace::Phase ephemeris_initialize {m_startup_trace_run, "jpl_ephemeris.initialize"}; + QString jpleph = m_config.data_dir().absoluteFilePath("JPLEPH"); + jpl_setup_(const_cast<char *>(jpleph.toLocal8Bit().constData()),256); + } #ifdef WIN32 // backup libhamlib-4.dll file, so it is still available after the next program update @@ -1315,7 +1785,7 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, QFile f {dataPath.absolutePath() + "/" + "libhamlib-4_old.dll"}; if (!f.exists()) { QFile::copy(dataPath.absolutePath() + "/" + "libhamlib-4.dll", dataPath.absolutePath() + "/" + "libhamlib-4_old.dll"); - QTimer::singleShot (5000, [=] { //wait until hamlib has been started + QTimer::singleShot (5000, this, [=] { //wait until hamlib has been started extern char* hamlib_version2; QString hamlib = QString(QLatin1String(hamlib_version2)); m_settings->beginGroup("Configuration"); @@ -1324,26 +1794,14 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, }); } #endif - ui->sbToneSpacing->values({10, 15, 20, 25, 30}); - QTimer::singleShot (4000, [=] {programStart=false;}); + QTimer::singleShot (4000, this, [=] {programStart=false;}); // this must be the last statement of constructor + runtime_initialize.finish (); if (!m_valid) throw std::runtime_error {"Fatal initialization exception"}; } -void MainWindow::not_GA_warning_message () -{ - MessageBox::critical_message (this, - "This is a pre-release version of WSJT-X " + version (false) + " made\n" - "available for testing purposes. By design it will\n" - "be nonfunctional after Jan 15, 2025."); - auto now = QDateTime::currentDateTimeUtc (); - if (now >= QDateTime {{2025, 01, 15}, {23, 59, 59, 999}, Qt::UTC}) { - Q_EMIT finished (); - } -} - void MainWindow::handle_leavingSettings () { inSettings = false; @@ -1392,259 +1850,302 @@ void MainWindow::on_the_minute () tx_watchdog (false); } update_foxLogWindow_rate(); // update the rate on the window - if ((!verified && ui->labDXped->isVisible()) or !ui->labDXped->text().contains("Hound")) - ui->labDXped->setStyleSheet("QLabel {background-color: red; color: white;}"); - verified = false; + updateHoundVerificationStyle (); + m_houndVerified = false; if(!m_transmitting && m_mode=="FT8" && (QDateTime::currentMSecsSinceEpoch()-m_mslastTX) > 120000) m_lapmyc=0; } + + //--------------------------------------------------- MainWindow destructor MainWindow::~MainWindow() { + PerformanceTrace::Phase destructor {"mainwindow.destructor_body"}; + // wav12 shares FFT state that main() releases after this window is destroyed. + { + PerformanceTrace::Phase wav_load_wait {"wav_load.shutdown_wait"}; + m_wav_load_coordinator.waitForFinished (); + } if(m_astroWidget) m_astroWidget.reset (); if(m_QSYMessageCreatorWidget) m_QSYMessageCreatorWidget.reset (); if(m_QSYMessageWidget) m_QSYMessageWidget.reset (); if(m_qsymonitorWidget) m_qsymonitorWidget.reset (); - auto fname {QDir::toNativeSeparators(m_config.writeable_data_dir ().absoluteFilePath ("wsjtx_wisdom.dat"))}; - fftwf_export_wisdom_to_filename (fname.toLocal8Bit ()); - m_audioThread.quit (); - m_audioThread.wait (); + { + PerformanceTrace::Phase wisdom_export {"fft_wisdom.export"}; + auto fname {QDir::toNativeSeparators(m_config.writeable_data_dir ().absoluteFilePath ("wsjtx_wisdom.dat"))}; + fftwf_export_wisdom_to_filename (fname.toLocal8Bit ()); + } + { + PerformanceTrace::Phase audio_shutdown {"audio_thread.shutdown"}; + m_audioThread.quit (); + m_audioThread.wait (); + } + { + PerformanceTrace::Phase wav_save_wait {"wav_save.shutdown_wait"}; + m_saveWAVSynchronizer.waitForFinished (); + } + m_saveWAVSynchronizer.clearFutures (); remove_child_from_event_filter (this); - memset(ipc_qmap,0,4096); //Zero all of QMAP shared memory -} - -//-------------------------------------------------------- writeSettings() -void MainWindow::writeSettings() -{ - m_settings->beginGroup("MainWindow"); - if (ui->actionSWL_Mode->isChecked ()) + if (ipc_qmap && mem_qmap.isAttached () && mem_qmap.lock ()) { + clearQMapSharedMemory (ipc_qmap, + static_cast<std::size_t> (mem_qmap.size ())); + mem_qmap.unlock (); + } +// Force linking of Fortran function stdmsg(). + QString t="1234567890123456789012345678901234567"; + if(stdmsg_(const_cast <char *> (t.toLatin1().constData()),(FCL)37)) return; +} + +void MainWindow::configureModeControlsLayout() +{ + ui->lower_panel_widget->setSizePolicy (QSizePolicy::Preferred, QSizePolicy::Maximum); + ui->horizontalLayout_6->setStretch (0, 0); + ui->horizontalLayout_6->setStretch (1, 1); + ui->tabWidget->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding); + + QPushButton * compactButtons[] = { + ui->lookupButton, ui->addButton, ui->ignoreButton, + ui->txb1, ui->txb2, ui->txb3, ui->txb4, ui->txb5, ui->txb6 + }; + for (auto * button : compactButtons) button->setProperty ("wsjtxCompact", true); + + // A designer minimum of 32 overrides the font/style minimumSizeHint and + // clips FT8/JT65 at larger fonts. Let the layout use the real label hints. + for (auto * button : {ui->houndButton, ui->ft8Button, ui->ft4Button, + ui->msk144Button, ui->q65Button, ui->jt65Button}) + button->setMinimumWidth (0); + + ui->horizontalLayout_2->setSpacing (2); + ui->gridLayout_5->removeWidget (ui->label); + ui->gridLayout_5->removeWidget (ui->outAttenuation); + auto * driveLayout = new QVBoxLayout; + driveLayout->setContentsMargins (0, 0, 0, 0); + driveLayout->addWidget (ui->label, 0, Qt::AlignHCenter); + driveLayout->addWidget (ui->outAttenuation, 1); + ui->gridLayout_5->addLayout (driveLayout, 0, 7, 3, 1); + for (auto * widget : {static_cast<QWidget *> (ui->logQSOButton), + static_cast<QWidget *> (ui->stopButton), + static_cast<QWidget *> (ui->monitorButton), + static_cast<QWidget *> (ui->EraseButton), + static_cast<QWidget *> (ui->ClrAvgButton), + static_cast<QWidget *> (ui->sbEchoAvg), + static_cast<QWidget *> (ui->DecodeButton), + static_cast<QWidget *> (ui->autoButton), + static_cast<QWidget *> (ui->stopTxButton), + static_cast<QWidget *> (ui->tuneButton), + static_cast<QWidget *> (ui->cbMenus)}) { - m_settings->setValue ("SWLView", true); - m_settings->setValue ("ShowMenus", ui->cbMenus->isChecked ()); - m_settings->setValue ("geometry", geometries ()[0]); - m_settings->setValue ("SWLModeGeometry", saveGeometry ()); - m_settings->setValue ("geometryNoControls", geometries ()[2]); - } - else + ui->horizontalLayout_2->setAlignment (widget, Qt::AlignVCenter); + } + + ui->gridLayout_3->removeItem (ui->verticalLayout_14); + ui->gridLayout_3->removeItem (ui->verticalLayout_13); + + ui->verticalLayout_14->removeWidget (ui->txFirstCheckBox); + ui->verticalLayout_14->removeWidget (ui->TxFreqSpinBox); + ui->verticalLayout_14->removeItem (ui->horizontalLayout_4); + ui->verticalLayout_14->removeWidget (ui->RxFreqSpinBox); + ui->verticalLayout_14->removeWidget (ui->rptSpinBox); + ui->verticalLayout_14->removeWidget (ui->sbTR); + + ui->verticalLayout_13->removeItem (ui->submode_gridLayout); + ui->verticalLayout_13->removeWidget (ui->cbHoldTxFreq); + ui->verticalLayout_13->removeWidget (ui->opt_controls_stack); + ui->verticalLayout_13->removeWidget (ui->sbSubmode); + ui->verticalLayout_13->removeWidget (ui->syncSpinBox); + ui->verticalLayout_13->removeWidget (ui->sbMaxDrift); + + auto * panel = new QWidget {ui->QSO_controls_widget}; + panel->setObjectName (QStringLiteral ("modeParameterPanel")); + panel->setSizePolicy (QSizePolicy::Minimum, QSizePolicy::Preferred); + auto * panelLayout = new QVBoxLayout {panel}; + panelLayout->setContentsMargins (0, 0, 0, 0); + + auto * checkboxRow = m_modeCheckboxRow = new QHBoxLayout; + checkboxRow->setContentsMargins (0, 0, 0, 0); + checkboxRow->setSpacing (12); + checkboxRow->addWidget (ui->txFirstCheckBox); + checkboxRow->addWidget (ui->cbHoldTxFreq); + checkboxRow->addStretch (1); + + auto * formPanel = new QWidget {panel}; + formPanel->setSizePolicy (QSizePolicy::Maximum, QSizePolicy::Preferred); + auto * form = new QGridLayout {formPanel}; + form->setContentsMargins (0, 0, 0, 0); + auto makeLabel = [panel] (QString const& text, QWidget * buddy, char const * objectName) { - if (ui->cbMenus->isChecked()) - { - m_settings->setValue ("SWLView", ui->actionSWL_Mode->isChecked ()); - m_settings->setValue ("ShowMenus", true); - m_settings->setValue ("geometry", saveGeometry ()); - m_settings->setValue ("SWLModeGeometry", geometries ()[1]); - m_settings->setValue ("geometryNoControls", geometries ()[2]); - } - else - { - m_settings->setValue ("SWLView", ui->actionSWL_Mode->isChecked ()); - m_settings->setValue ("ShowMenus", false); - m_settings->setValue ("geometry", geometries ()[0]); - m_settings->setValue ("SWLModeGeometry", geometries ()[1]); - m_settings->setValue ("geometryNoControls", saveGeometry ()); - } + auto * label = new QLabel {text, panel}; + label->setObjectName (QString::fromLatin1 (objectName)); + label->setAlignment (Qt::AlignLeft | Qt::AlignVCenter); + label->setBuddy (buddy); + return label; + }; + + m_txFrequencyLabel = makeLabel ( + tr ("Tx ").trimmed (), ui->TxFreqSpinBox, "txFrequencyLabel"); + m_frequencyToleranceLabel = makeLabel ( + tr ("F Tol ").trimmed (), ui->sbFtol, "frequencyToleranceLabel"); + m_rxFrequencyLabel = makeLabel ( + tr ("Rx ").trimmed (), ui->RxFreqSpinBox, "rxFrequencyLabel"); + m_reportLabel = makeLabel ( + tr (" Report ").trimmed (), ui->rptSpinBox, "reportLabel"); + m_trPeriodLabel = makeLabel ( + tr ("T/R ").trimmed (), ui->sbTR, "trPeriodLabel"); + m_submodeLabel = makeLabel ( + tr ("Submode ").trimmed (), ui->sbSubmode, "submodeLabel"); + m_maxDriftLabel = makeLabel ( + tr ("Max Drift ").trimmed (), ui->sbMaxDrift, "maxDriftLabel"); + + auto makeControlRow = [] (QWidget * label, QWidget * control) + { + auto * row = new QHBoxLayout; + row->setContentsMargins (0, 0, 0, 0); + row->setSpacing (4); + row->addWidget (label); + row->addWidget (control); + return row; + }; + + m_frequencyToleranceRow = new QHBoxLayout; + m_frequencyToleranceRow->setContentsMargins (0, 0, 0, 0); + m_frequencyToleranceRow->setSpacing (4); + m_frequencyToleranceRow->addWidget (m_frequencyToleranceLabel); + m_frequencyToleranceRow->addLayout (ui->horizontalLayout_4); + m_frequencyToleranceRow->addStretch (1); + + ui->TxFreqSpinBox->setPrefix ({}); + ui->TxFreqSpinBox->setSuffix (tr (" Hz")); + ui->RxFreqSpinBox->setPrefix ({}); + ui->RxFreqSpinBox->setSuffix (tr (" Hz")); + ui->sbFtol->setPrefix ({}); + ui->rptSpinBox->setPrefix ({}); + ui->sbTR->setPrefix ({}); + ui->sbTR->setSuffix (tr (" s")); + ui->sbSubmode->setPrefix ({}); + ui->sbMaxDrift->setPrefix ({}); + + for (auto * spinBox : { + static_cast<QWidget *> (ui->TxFreqSpinBox), + static_cast<QWidget *> (ui->sbFtol), + static_cast<QWidget *> (ui->RxFreqSpinBox), + static_cast<QWidget *> (ui->rptSpinBox), + static_cast<QWidget *> (ui->sbTR), + static_cast<QWidget *> (ui->sbSubmode), + static_cast<QWidget *> (ui->sbMaxDrift)}) + { + spinBox->setSizePolicy (QSizePolicy::Fixed, QSizePolicy::Fixed); + } + + form->addLayout (makeControlRow (m_txFrequencyLabel, ui->TxFreqSpinBox), 0, 0, Qt::AlignLeft); + form->addLayout (makeControlRow (m_submodeLabel, ui->sbSubmode), 0, 1, Qt::AlignLeft); + form->addLayout (m_frequencyToleranceRow, 1, 0, 1, 2, Qt::AlignLeft); + form->addLayout (makeControlRow (m_maxDriftLabel, ui->sbMaxDrift), 2, 1, Qt::AlignLeft); + form->addLayout (makeControlRow (m_rxFrequencyLabel, ui->RxFreqSpinBox), 2, 0, Qt::AlignLeft); + form->addLayout (makeControlRow (m_reportLabel, ui->rptSpinBox), 3, 0, Qt::AlignLeft); + form->addWidget (ui->opt_controls_stack, 3, 1, Qt::AlignLeft); + form->addLayout (makeControlRow (m_trPeriodLabel, ui->sbTR), 4, 0, Qt::AlignLeft); + form->addWidget (ui->syncSpinBox, 4, 1, Qt::AlignLeft); + form->setAlignment (Qt::AlignLeft | Qt::AlignTop); + + panelLayout->addLayout (checkboxRow); + panelLayout->addWidget (formPanel, 0, Qt::AlignLeft); + panelLayout->addLayout (ui->submode_gridLayout); + panelLayout->addStretch (1); + ui->gridLayout_3->addWidget (panel, 0, 0, 1, 2); + + ui->gridLayout_3->removeItem (ui->horizontalLayout_5); + ui->horizontalLayout_5->removeWidget (ui->respondComboBox); + auto * sequencingLayout = new QVBoxLayout; + sequencingLayout->setContentsMargins (0, 0, 0, 0); + sequencingLayout->addLayout (ui->horizontalLayout_5); + ui->respondComboBox->setSizeAdjustPolicy (QComboBox::AdjustToContents); + sequencingLayout->addWidget (ui->respondComboBox, 0, Qt::AlignLeft); + ui->gridLayout_3->addLayout (sequencingLayout, 2, 0, 1, 2); + + for (auto * button : {ui->pb15A, ui->pb15C, ui->pb30B, ui->pb60C, ui->pb60D, ui->pb60E}) + { + button->setMinimumWidth (0); + button->setSizePolicy (QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); } - m_settings->setValue ("state", saveState ()); - m_settings->setValue("MRUdir", m_path); - m_settings->setValue("TxFirst",m_txFirst); - m_settings->setValue("DXcall",ui->dxCallEntry->text()); - m_settings->setValue("DXgrid",ui->dxGridEntry->text()); - m_settings->setValue("AstroDisplayed", m_astroWidget && m_astroWidget->isVisible()); - m_settings->setValue("MsgAvgDisplayed", m_msgAvgWidget && m_msgAvgWidget->isVisible ()); - m_settings->setValue("FoxLogDisplayed", m_foxLogWindow && m_foxLogWindow->isVisible ()); - m_settings->setValue("ContestLogDisplayed", m_contestLogWindow && m_contestLogWindow->isVisible ()); - m_settings->setValue("ActiveStationsDisplayed", m_ActiveStationsWidget && m_ActiveStationsWidget->isVisible ()); - m_settings->setValue("QSYMessageCreatorDisplayed", m_QSYMessageCreatorWidget && m_QSYMessageCreatorWidget->isVisible ()); - m_settings->setValue("ShowQSYMessages", ui->actionEnable_QSY_Popups->isChecked()); - m_settings->setValue("QSYMonitorDisplayed", m_qsymonitorWidget && m_qsymonitorWidget->isVisible ()); - m_settings->setValue("RespondCQ",ui->respondComboBox->currentIndex()); - m_settings->setValue("HoundSort",ui->comboBoxHoundSort->currentIndex()); - m_settings->setValue("FoxNlist",ui->sbNlist->value()); - m_settings->setValue("FoxNslots",m_Nslots0); - m_settings->setValue("SerialNumber",ui->sbSerialNumber->value ()); - m_settings->setValue("FoxTextMsg", m_freeTextMsg0); - m_settings->setValue("WorkDupes", ui->cbWorkDupes->isChecked()); - m_settings->endGroup(); - - // do this in the General group because we save the parameters from various places - if(m_mode=="JT9") { - m_settings->setValue("SubMode",ui->sbSubmode->value()); - m_settings->setValue("TRPeriod", ui->sbTR->value()); - } - if(m_mode=="MSK144") m_settings->setValue("ShMsgs_MSK144",m_bShMsgs); - if(m_mode=="Q65") m_settings->setValue("ShMsgs_Q65",m_bShMsgs); - if(m_mode=="JT65") m_settings->setValue("ShMsgs_JT65",m_bShMsgs); - if(m_mode=="JT4") m_settings->setValue("ShMsgs_JT4",m_bShMsgs); - - m_settings->beginGroup("Common"); - m_settings->setValue("Mode",m_mode); - m_settings->setValue("SaveNone",ui->actionNone->isChecked()); - m_settings->setValue("SaveDecoded",ui->actionSave_decoded->isChecked()); - m_settings->setValue("SaveAll",ui->actionSave_all->isChecked()); - m_settings->setValue("RemoveAudioFiles",ui->actionRemove_after_30days->isChecked()); - m_settings->setValue("NDepth",m_ndepth); +} - //ft8md - m_settings->setValue ("MultithreadedFT8decoder",ui->actionUse_multithreaded_FT8_decoder->isChecked() ); - m_settings->setValue("NFT8Cycles",m_nFT8Cycles); - m_settings->setValue("NFT8QSORXfreqSensitivity",m_nFT8RXfSens); - m_settings->setValue("FT8threads",m_ft8threads); - m_settings->setValue("FT8Sensitivity",m_ft8Sensitivity); - m_settings->setValue("FT8DecoderStart",m_ft8DecoderStart); - m_settings->setValue("FT8WideDXCallSearch",m_FT8WideDxCallSearch); - m_settings->setValue("HideFT8Dupes",ui->actionHide_FT8_dupe_messages->isChecked()); - //ft8md +void MainWindow::updateModeControlsLayout () +{ + if (!m_modeCheckboxRow || ui->tabWidget->currentIndex () != 0) return; + auto const bothVisible = !ui->txFirstCheckBox->isHidden () && !ui->cbHoldTxFreq->isHidden (); + auto const checkboxWidth = ui->txFirstCheckBox->sizeHint ().width () + + ui->cbHoldTxFreq->sizeHint ().width () + m_modeCheckboxRow->spacing (); + // Preserve the message editor's preferred width before reserving a single + // checkbox row. The remaining width includes tabs, Next/Now and native buttons. + auto const messageChrome = qMax (0, ui->tabWidget->width () - ui->tx1->width ()); + auto const requiredWidth = checkboxWidth + ui->horizontalLayout_6->spacing () + + messageChrome + ui->tx1->sizeHint ().width (); + auto const availableCheckboxWidth = m_modeCheckboxRow->parentWidget ()->contentsRect ().width (); + auto const direction = bothVisible && (ui->QSO_controls_widget->width () < requiredWidth + || availableCheckboxWidth < checkboxWidth) + ? QBoxLayout::TopToBottom : QBoxLayout::LeftToRight; + if (m_modeCheckboxRow->direction () != direction) + m_modeCheckboxRow->setDirection (direction); +} - m_settings->setValue("RxFreq",ui->RxFreqSpinBox->value()); - if(m_specOp!=SpecOp::FOX) m_settings->setValue("TxFreq",ui->TxFreqSpinBox->value()); - m_settings->setValue("TxFreqFox",m_TxFreqFox); - m_settings->setValue("WSPRfreq",ui->WSPRfreqSpinBox->value()); - m_settings->setValue("FST4W_RxFreq",ui->sbFST4W_RxFreq->value()); - m_settings->setValue("FST4W_FTol",ui->sbFST4W_FTol->value()); - m_settings->setValue("FST4_FLow",ui->sbF_Low->value()); - m_settings->setValue("FST4_FHigh",ui->sbF_High->value()); - m_settings->setValue("EchoToneSpacing",ui->sbToneSpacing->value()); - m_settings->setValue("EchoFixedTone",ui->rbFixedTone->isChecked()); - m_settings->setValue("EchoMessageRB",ui->rbEchoMessage->isChecked()); - m_settings->setValue("EchoCW",ui->rbEchoCW->isChecked()); - m_settings->setValue("EchoMessage",ui->leEchoMessage->text()); - m_settings->setValue("DTtol",m_DTtol); - m_settings->setValue("MinSync",m_minSync); - m_settings->setValue ("AutoSeq", ui->cbAutoSeq->isChecked ()); - m_settings->setValue ("RxAll", ui->cbRxAll->isChecked ()); -// m_settings->setValue("ShMsgs",m_bShMsgs); - m_settings->setValue("SWL",ui->cbSWL->isChecked()); - if(m_mode=="MSK144" && m_msk144basefreq > 0) { - m_settings->setValue ("DialFreq", QVariant::fromValue(m_msk144basefreq)); // MSK144 QSY - } else { - m_settings->setValue ("DialFreq", QVariant::fromValue(m_lastMonitoredFrequency)); - } - m_settings->setValue("SkedFreq",m_skedFreq); - m_settings->setValue("OutAttenuation", ui->outAttenuation->value ()); - m_settings->setValue("NoSuffix",m_noSuffix); - m_settings->setValue("GUItab",ui->tabWidget->currentIndex()); - m_settings->setValue("OutBufSize",outBufSize); - m_settings->setValue ("HoldTxFreq", ui->cbHoldTxFreq->isChecked ()); - m_settings->setValue ("CQonly", ui->cbCQonly->isChecked ()); - m_settings->setValue ("BypassFilters", ui->cbBypass->isChecked ()); - m_settings->setValue("PctTx", ui->sbTxPercent->value ()); - m_settings->setValue("RoundRobin",ui->RoundRobin->currentText()); - m_settings->setValue("dBm",m_dBm); - m_settings->setValue("RR73",m_send_RR73); - m_settings->setValue ("WSPRPreferType1", ui->WSPR_prefer_type_1_check_box->isChecked ()); - m_settings->setValue("UploadSpots",m_uploadWSPRSpots); - m_settings->setValue("NoOwnCall",ui->cbNoOwnCall->isChecked()); - m_settings->setValue ("BandHopping", ui->band_hopping_group_box->isChecked ()); - m_settings->setValue ("MaxDrift", ui->sbMaxDrift->value()); - m_settings->setValue ("TRPeriod_FST4W", ui->sbTR_FST4W->value ()); - m_settings->setValue("FastMode",m_bFastMode); - m_settings->setValue("Fast9",m_bFast9); - m_settings->setValue ("CQTxfreq", ui->sbCQTxFreq->value ()); - m_settings->setValue("pwrBandTxMemory",m_pwrBandTxMemory); - m_settings->setValue("pwrBandTuneMemory",m_pwrBandTuneMemory); - m_settings->setValue ("FT8AP", ui->actionEnable_AP_FT8->isChecked ()); - m_settings->setValue ("JT65AP", ui->actionEnable_AP_JT65->isChecked ()); - m_settings->setValue ("AutoClearAvg", ui->actionAuto_Clear_Avg->isChecked ()); - m_settings->setValue ("DisableClicksOnWaterfall", ui->actionDisable_clicks_on_waterfall->isChecked ()); - m_settings->setValue("SplitterState",ui->decodes_splitter->saveState()); - m_settings->setValue("Blanker",ui->sbNB->value()); - m_settings->setValue("Score",m_score); - m_settings->setValue("labDXpedText",ui->labDXped->text()); - m_settings->setValue("EchoAvg",ui->sbEchoAvg->value()); +bool MainWindow::decoderBackendRunning () const +{ + return proc_jt9.state () == QProcess::Running; +} + +void MainWindow::save_wave_file(QString const& name, int samples, Frequency frequency, + QString const& dgrd) +{ + int const sample_capacity = static_cast<int> (sizeof (dec_data.d2) / sizeof (dec_data.d2[0])); + if (samples <= 0 || samples > sample_capacity) { + MessageBox::critical_message (this, tr ("Error Writing WAV File"), + tr ("%1.wav: invalid sample count %2").arg (name).arg (samples)); + return; + } + + auto data = std::make_shared<std::vector<short> > (samples); { - QList<QVariant> coeffs; // suitable for QSettings - for (auto const& coeff : m_phaseEqCoefficients) - { - coeffs << coeff; - } - m_settings->setValue ("PhaseEqualizationCoefficients", QVariant {coeffs}); - } - m_settings->setValue ("bh_160m", ui->cb160m->isChecked() ); - m_settings->setValue ("bh_80m", ui->cb80m->isChecked() ); - m_settings->setValue ("bh_60m", ui->cb60m->isChecked() ); - m_settings->setValue ("bh_40m", ui->cb40m->isChecked() ); - m_settings->setValue ("bh_30m", ui->cb30m->isChecked() ); - m_settings->setValue ("bh_20m", ui->cb20m->isChecked() ); - m_settings->setValue ("bh_17m", ui->cb17m->isChecked() ); - m_settings->setValue ("bh_15m", ui->cb15m->isChecked() ); - m_settings->setValue ("bh_12m", ui->cb12m->isChecked() ); - m_settings->setValue ("bh_10m", ui->cb10m->isChecked() ); - m_settings->setValue ("bh_6m", ui->cb6m->isChecked() ); - m_settings->setValue ("bh_4m", ui->cb4m->isChecked() ); - m_settings->setValue ("bh_2m", ui->cb2m->isChecked() ); - m_settings->setValue ("bh_70cm", ui->cb70cm->isChecked() ); - m_settings->setValue ("bh_2mMSK", ui->cb2mMSK->isChecked() ); - m_settings->setValue ("bh_80mFT4", ui->cb80mFT4->isChecked() ); - m_settings->setValue ("bh_40mFT4", ui->cb40mFT4->isChecked() ); - m_settings->setValue ("bh_30mFT4", ui->cb30mFT4->isChecked() ); - m_settings->setValue ("bh_20mFT4", ui->cb20mFT4->isChecked() ); - m_settings->setValue ("bh_17mFT4", ui->cb17mFT4->isChecked() ); - m_settings->setValue ("bh_15mFT4", ui->cb15mFT4->isChecked() ); - m_settings->setValue ("bh_12mFT4", ui->cb12mFT4->isChecked() ); - m_settings->setValue ("bh_10mFT4", ui->cb10mFT4->isChecked() ); - m_settings->setValue ("bh_QRG1", ui->cbQRG1->isChecked() ); - m_settings->setValue ("bh_QRG2", ui->cbQRG2->isChecked() ); - m_settings->setValue ("bh_QRG3", ui->cbQRG3->isChecked() ); - m_settings->setValue ("bh_QRG4", ui->cbQRG4->isChecked() ); - m_settings->setValue ("bh_QRG5", ui->cbQRG5->isChecked() ); - m_settings->setValue ("bh_QRG6", ui->cbQRG6->isChecked() ); - m_settings->setValue ("bh_QRG7", ui->cbQRG7->isChecked() ); - m_settings->setValue ("bh_QRG8", ui->cbQRG8->isChecked() ); - m_settings->setValue ("QRG1", ui->sbQRG1->value ()); - m_settings->setValue ("QRG2", ui->sbQRG2->value ()); - m_settings->setValue ("QRG3", ui->sbQRG3->value ()); - m_settings->setValue ("QRG4", ui->sbQRG4->value ()); - m_settings->setValue ("QRG5", ui->sbQRG5->value ()); - m_settings->setValue ("QRG6", ui->sbQRG6->value ()); - m_settings->setValue ("QRG7", ui->sbQRG7->value ()); - m_settings->setValue ("QRG8", ui->sbQRG8->value ()); - m_settings->setValue ("reduceFalseDecodes", ui->actionReduce_false_decodes->isChecked() ); - m_settings->setValue ("HideAPInfo", ui->actionHide_AP_info->isChecked() ); - m_settings->setValue ("FullDuplexMode", ui->actionFull_Duplex_Mode->isChecked() ); - m_settings->setValue ("actionDontSplitALLTXT", ui->actionDon_t_split_ALL_TXT->isChecked() ); - m_settings->setValue ("splitAllTxtYearly", ui->actionSplit_ALL_TXT_yearly->isChecked() ); - m_settings->setValue ("splitAllTxtMonthly", ui->actionSplit_ALL_TXT_monthly->isChecked() ); - m_settings->setValue ("disableWritingOfAllTxt", ui->actionDisable_writing_of_ALL_TXT->isChecked() ); - m_settings->setValue ("DisableEventLogging", ui->actionDisable_event_logging->isChecked() ); - m_settings->setValue ("DarkStyle", ui->actionUse_Dark_Style->isChecked() ); - m_settings->setValue ("BandButtons", ui->actionBand_Buttons->isChecked() ); - m_settings->setValue ("VHFUHFButtons", ui->actionVHF_UHF_Buttons->isChecked() ); - m_settings->setValue ("tx1State", ui->tx1->isEnabled() ); - m_settings->setValue ("HighlightB4", ui->actionHighlightB4->isChecked() ); - m_settings->setValue ("HighlightToday", ui->actionHighlightToday->isChecked() ); - m_settings->setValue ("HighlightIgnored", ui->actionHighlightIgnored->isChecked() ); - m_settings->setValue ("HideB4", ui->actionHideB4->isChecked() ); - m_settings->setValue ("HideToday", ui->actionHideToday->isChecked() ); - m_settings->setValue ("HideIgnored", ui->actionHideIgnored->isChecked() ); - m_settings->setValue ("IgnoreB4", ui->actionIgnoreB4->isChecked() ); - m_settings->setValue ("IgnoreToday", ui->actionIgnoreToday->isChecked() ); - m_settings->setValue ("IgnoreIgnored", ui->actionIgnoreIgnored->isChecked() ); - m_settings->setValue ("HideTerritory1", ui->actionHideTerritory1->isChecked() ); - m_settings->setValue ("HideTerritory2", ui->actionHideTerritory2->isChecked() ); - m_settings->setValue ("HideTerritory3", ui->actionHideTerritory3->isChecked() ); - m_settings->setValue ("HideTerritory4", ui->actionHideTerritory4->isChecked() ); - m_settings->setValue ("HighlightTerritory1", ui->actionHighlightTerritory1->isChecked() ); - m_settings->setValue ("HighlightTerritory2", ui->actionHighlightTerritory2->isChecked() ); - m_settings->setValue ("HighlightTerritory3", ui->actionHighlightTerritory3->isChecked() ); - m_settings->setValue ("HighlightTerritory4", ui->actionHighlightTerritory4->isChecked() ); - m_settings->setValue ("HideEU", ui->actionHideEU->isChecked() ); - m_settings->setValue ("HideNA", ui->actionHideNA->isChecked() ); - m_settings->setValue ("HideSA", ui->actionHideSA->isChecked() ); - m_settings->setValue ("HideAS", ui->actionHideAS->isChecked() ); - m_settings->setValue ("HideAF", ui->actionHideAF->isChecked() ); - m_settings->setValue ("HideOC", ui->actionHideOC->isChecked() ); - m_settings->setValue ("HideAN", ui->actionHideAN->isChecked() ); - m_settings->setValue ("HighlightWhitelistEntries", ui->actionHighlight_Whitelist_entries->isChecked() ); - m_settings->endGroup(); + QMutexLocker lock {&dec_data_mutex ()}; + std::copy (dec_data.d2, dec_data.d2 + samples, data->begin ()); + } + + QString const file_name = name; + QString const my_callsign = m_config.my_callsign (); + QString const my_grid = m_config.my_grid (); + QString const mode = m_mode; + qint32 const sub_mode = m_nSubMode; + QString const his_call = m_hisCall; + QString const his_grid = m_hisGrid; + + auto const futures = m_saveWAVSynchronizer.futures (); + bool all_finished = true; + for (auto const& future : futures) { + if (!future.isFinished ()) { + all_finished = false; + break; + } + } + if (all_finished) { + m_saveWAVSynchronizer.clearFutures (); + } + + auto const future = QtConcurrent::run ([file_name, data, samples, my_callsign, my_grid, + mode, sub_mode, frequency, his_call, his_grid, dgrd] { + return Radio::WavFile::save (file_name, data->data (), samples, my_callsign, my_grid, + mode, sub_mode, frequency, his_call, his_grid, dgrd); + }); + m_saveWAVSynchronizer.addFuture (future); + m_saveWAVWatcher.setFuture (future); } +//-------------------------------------------------------- writeSettings() + void MainWindow::update_tx5(const QString &qsy_text) { if (m_hisCall=="") { QMessageBox::warning(this, "WSJT-X","There must be a callsign in the\n DX Call Box to send QSY Request"); } else { - QString text = qsy_text; - ui->tx6->setText(text.replace("$DX",m_hisCall)); + ui->tx6->setText(expandTxMacros(qsy_text)); ui->txb6->click(); stopWRTimer.stop(); if(!m_auto) { @@ -1669,361 +2170,6 @@ void MainWindow::setQSYMessageCreatorStatus(const bool &QSYMessageCreatorValue) } //---------------------------------------------------------- readSettings() -void MainWindow::readSettings() -{ - ui->cbAutoSeq->setVisible(false); - ui->respondComboBox->setVisible(false); - - m_settings->beginGroup("MainWindow"); - std::array<QByteArray, 3> the_geometries; - the_geometries[0] = m_settings->value ("geometry", saveGeometry ()).toByteArray (); - the_geometries[1] = m_settings->value ("SWLModeGeometry", saveGeometry ()).toByteArray (); - the_geometries[2] = m_settings->value ("geometryNoControls", saveGeometry ()).toByteArray (); - auto SWL_mode = m_settings->value ("SWLView", false).toBool (); - auto show_menus = m_settings->value ("ShowMenus", true).toBool (); - ui->actionSWL_Mode->setChecked (SWL_mode); - ui->cbMenus->setChecked (show_menus); - auto current_view_mode = SWL_mode ? 1 : show_menus ? 0 : 2; - change_layout (current_view_mode); - geometries (current_view_mode, the_geometries); - restoreState (m_settings->value ("state", saveState ()).toByteArray ()); - ui->dxCallEntry->setText (m_settings->value ("DXcall", QString {}).toString ()); - ui->dxGridEntry->setText (m_settings->value ("DXgrid", QString {}).toString ()); - m_path = m_settings->value("MRUdir", m_config.save_directory ().absolutePath ()).toString (); - m_txFirst = m_settings->value("TxFirst",false).toBool(); - auto displayAstro = m_settings->value ("AstroDisplayed", false).toBool (); - auto displayMsgAvg = m_settings->value ("MsgAvgDisplayed", false).toBool (); - auto displayFoxLog = m_settings->value ("FoxLogDisplayed", false).toBool (); - auto displayContestLog = m_settings->value ("ContestLogDisplayed", false).toBool (); - bool displayActiveStations = m_settings->value ("ActiveStationsDisplayed", false).toBool (); - bool displayQSYMessageCreator = m_settings->value ("QSYMessageCreatorDisplayed", false).toBool (); - bool displayQSYMonitor = m_settings->value("QSYMonitorDisplayed", false).toBool (); - bool enableQSYpopups = m_settings->value("ShowQSYMessages", true).toBool (); - ui->respondComboBox->setCurrentIndex(m_settings->value("RespondCQ",0).toInt()); - ui->comboBoxHoundSort->setCurrentIndex(m_settings->value("HoundSort",3).toInt()); - ui->sbNlist->setValue(m_settings->value("FoxNlist",12).toInt()); - m_Nslots=m_settings->value("FoxNslots",3).toInt(); - m_Nslots0=m_Nslots; - if(!m_config.superFox()) ui->sbNslots->setValue(m_Nslots); - ui->sbSerialNumber->setValue (m_settings->value ("SerialNumber", 1).toInt ()); - m_freeTextMsg0=m_settings->value("FoxTextMsg","").toString(); - m_freeTextMsg=m_freeTextMsg0; - ui->cbWorkDupes->setChecked(m_settings->value("WorkDupes",false).toBool()); - m_settings->endGroup(); - - m_settings->beginGroup("Common"); - m_mode=m_settings->value("Mode","FT8").toString(); - m_settings->endGroup(); - - // do this outside of settings group because it uses groups internally - ui->actionAstronomical_data->setChecked (displayAstro); - ui->actionEnable_QSY_Popups->setChecked (enableQSYpopups); - - // do this in the General group because we save the parameters from various places - if(m_mode=="JT9") { - blocked=true; - m_nSubMode=m_settings->value("SubMode",0).toInt(); - ui->sbSubmode->setValue(m_nSubMode); - ui->sbFtol->setValue (m_settings->value("Ftol_JT9", 50).toInt()); - ui->sbTR->setValue (m_settings->value ("TRPeriod", 15).toInt()); - QTimer::singleShot (50, [=] {blocked = false;}); - } - if (m_mode=="FT8") { - ui->sbFtol->setValue (m_settings->value("Ftol_SF", 50).toInt()); - } - if (m_mode=="Q65") { - m_nSubMode=m_settings->value("SubMode_Q65",0).toInt(); - ui->sbSubmode->setValue(m_nSubMode); - ui->sbFtol->setValue (m_settings->value("Ftol_Q65", 50).toInt()); - ui->sbTR->setValue (m_settings->value ("TRPeriod_Q65", 30).toInt()); - } - if (m_mode=="JT65") { - m_nSubMode=m_settings->value("SubMode_JT65",0).toInt(); - ui->sbSubmode->setValue(m_nSubMode); - ui->sbFtol->setValue (m_settings->value("Ftol_JT65", 50).toInt()); - } - if (m_mode=="JT4") { - m_nSubMode=m_settings->value("SubMode_JT4",0).toInt(); - ui->sbSubmode->setValue(m_nSubMode); - ui->sbFtol->setValue (m_settings->value("Ftol_JT4", 50).toInt()); - ui->sbTR->setValue (m_settings->value ("TRPeriod_FST4", 60).toInt()); - } - if (m_mode=="MSK144") { - ui->sbFtol->setValue (m_settings->value("Ftol_MSK144",50).toInt()); - m_msk144_tr2=m_settings->value ("TRPeriod_MSK144_2m", 30).toInt(); - m_msk144_tr6=m_settings->value ("TRPeriod_MSK144_6m", 15).toInt(); - m_msk144_tr=m_settings->value ("TRPeriod_MSK144", 30).toInt(); - QTimer::singleShot (3000, [=] { - if (m_currentBand=="2m") ui->sbTR->setValue (m_msk144_tr2); - else if (m_currentBand=="6m" or m_currentBand=="4m") ui->sbTR->setValue (m_msk144_tr6); - else ui->sbTR->setValue (m_msk144_tr); - }); - } - if (m_mode=="MSK144") m_bShMsgs=m_settings->value("ShMsgs_MSK144",false).toBool(); - if (m_mode=="Q65") m_bShMsgs=m_settings->value("ShMsgs_Q65",false).toBool(); - if (m_mode=="JT65") m_bShMsgs=m_settings->value("ShMsgs_JT65",false).toBool(); - if (m_mode=="JT4") m_bShMsgs=m_settings->value("ShMsgs_JT4",false).toBool(); - - m_settings->beginGroup("Common"); - ui->cb160m->setChecked(m_settings->value("bh_160m", false).toBool()); - ui->cb80m->setChecked(m_settings->value("bh_80m", false).toBool()); - ui->cb60m->setChecked(m_settings->value("bh_60m", false).toBool()); - ui->cb40m->setChecked(m_settings->value("bh_40m", false).toBool()); - ui->cb30m->setChecked(m_settings->value("bh_30m", false).toBool()); - ui->cb20m->setChecked(m_settings->value("bh_20m", false).toBool()); - ui->cb17m->setChecked(m_settings->value("bh_17m", false).toBool()); - ui->cb15m->setChecked(m_settings->value("bh_15m", false).toBool()); - ui->cb12m->setChecked(m_settings->value("bh_12m", false).toBool()); - ui->cb10m->setChecked(m_settings->value("bh_10m", false).toBool()); - ui->cb6m->setChecked(m_settings->value("bh_6m", false).toBool()); - ui->cb4m->setChecked(m_settings->value("bh_4m", false).toBool()); - ui->cb2m->setChecked(m_settings->value("bh_2m", false).toBool()); - ui->cb70cm->setChecked(m_settings->value("bh_70cm", false).toBool()); - ui->cb2mMSK->setChecked(m_settings->value("bh_2mMSK", false).toBool()); - ui->cb80mFT4->setChecked(m_settings->value("bh_80mFT4", false).toBool()); - ui->cb40mFT4->setChecked(m_settings->value("bh_40mFT4", false).toBool()); - ui->cb30mFT4->setChecked(m_settings->value("bh_30mFT4", false).toBool()); - ui->cb20mFT4->setChecked(m_settings->value("bh_20mFT4", false).toBool()); - ui->cb17mFT4->setChecked(m_settings->value("bh_17mFT4", false).toBool()); - ui->cb15mFT4->setChecked(m_settings->value("bh_15mFT4", false).toBool()); - ui->cb12mFT4->setChecked(m_settings->value("bh_12mFT4", false).toBool()); - ui->cb10mFT4->setChecked(m_settings->value("bh_10mFT4", false).toBool()); - ui->cbQRG1->setChecked(m_settings->value("bh_QRG1", false).toBool()); - ui->cbQRG2->setChecked(m_settings->value("bh_QRG2", false).toBool()); - ui->cbQRG3->setChecked(m_settings->value("bh_QRG3", false).toBool()); - ui->cbQRG4->setChecked(m_settings->value("bh_QRG4", false).toBool()); - ui->cbQRG5->setChecked(m_settings->value("bh_QRG5", false).toBool()); - ui->cbQRG6->setChecked(m_settings->value("bh_QRG6", false).toBool()); - ui->cbQRG7->setChecked(m_settings->value("bh_QRG7", false).toBool()); - ui->cbQRG8->setChecked(m_settings->value("bh_QRG8", false).toBool()); - ui->sbQRG1->setValue (m_settings->value ("QRG1", 3567).toInt ()); - ui->sbQRG2->setValue (m_settings->value ("QRG2", 7056).toInt ()); - ui->sbQRG3->setValue (m_settings->value ("QRG3", 10131).toInt ()); - ui->sbQRG4->setValue (m_settings->value ("QRG4", 14090).toInt ()); - ui->sbQRG5->setValue (m_settings->value ("QRG5", 18095).toInt ()); - ui->sbQRG6->setValue (m_settings->value ("QRG6", 21091).toInt ()); - ui->sbQRG7->setValue (m_settings->value ("QRG7", 24911).toInt ()); - ui->sbQRG8->setValue (m_settings->value ("QRG8", 28091).toInt ()); - ui->actionReduce_false_decodes->setChecked(m_settings->value("reduceFalseDecodes", false).toBool()); - ui->actionHide_AP_info->setChecked(m_settings->value("HideAPInfo", false).toBool()); - ui->actionFull_Duplex_Mode->setChecked(m_settings->value("FullDuplexMode", false).toBool()); - ui->labDXped->setText(m_settings->value("labDXpedText",QString {}).toString ()); - ui->actionDon_t_split_ALL_TXT->setChecked(m_settings->value("actionDontSplitALLTXT", true).toBool()); - ui->actionSplit_ALL_TXT_yearly->setChecked(m_settings->value("splitAllTxtYearly", false).toBool()); - ui->actionSplit_ALL_TXT_monthly->setChecked(m_settings->value("splitAllTxtMonthly", false).toBool()); - ui->actionDisable_writing_of_ALL_TXT->setChecked(m_settings->value("disableWritingOfAllTxt", false).toBool()); - ui->actionDisable_event_logging->setChecked(m_settings->value("DisableEventLogging", false).toBool()); - ui->actionUse_Dark_Style->setChecked(m_settings->value("DarkStyle", false).toBool()); - ui->actionBand_Buttons->setChecked(m_settings->value("BandButtons", true).toBool()); - ui->actionVHF_UHF_Buttons->setChecked(m_settings->value("VHFUHFButtons", false).toBool()); - ui->tx1->setEnabled(m_settings->value("tx1State", true).toBool()); - ui->actionHighlightB4->setChecked(m_settings->value("HighlightB4", false).toBool()); - ui->actionHighlightToday->setChecked(m_settings->value("HighlightToday", false).toBool()); - ui->actionHighlightIgnored->setChecked(m_settings->value("HighlightIgnored", false).toBool()); - ui->actionHideB4->setChecked(m_settings->value("HideB4", false).toBool()); - ui->actionHideToday->setChecked(m_settings->value("HideToday", false).toBool()); - ui->actionHideIgnored->setChecked(m_settings->value("HideIgnored", false).toBool()); - ui->actionIgnoreB4->setChecked(m_settings->value("IgnoreB4", false).toBool()); - ui->actionIgnoreToday->setChecked(m_settings->value("IgnoreToday", false).toBool()); - ui->actionIgnoreIgnored->setChecked(m_settings->value("IgnoreIgnored", false).toBool()); - ui->actionHideTerritory1->setChecked(m_settings->value("HideTerritory1", false).toBool()); - ui->actionHideTerritory2->setChecked(m_settings->value("HideTerritory2", false).toBool()); - ui->actionHideTerritory3->setChecked(m_settings->value("HideTerritory3", false).toBool()); - ui->actionHideTerritory4->setChecked(m_settings->value("HideTerritory4", false).toBool()); - ui->actionHighlightTerritory1->setChecked(m_settings->value("HighlightTerritory1", false).toBool()); - ui->actionHighlightTerritory2->setChecked(m_settings->value("HighlightTerritory2", false).toBool()); - ui->actionHighlightTerritory3->setChecked(m_settings->value("HighlightTerritory3", false).toBool()); - ui->actionHighlightTerritory4->setChecked(m_settings->value("HighlightTerritory4", false).toBool()); - ui->actionHideEU->setChecked(m_settings->value("HideEU", false).toBool()); - ui->actionHideNA->setChecked(m_settings->value("HideNA", false).toBool()); - ui->actionHideSA->setChecked(m_settings->value("HideSA", false).toBool()); - ui->actionHideAS->setChecked(m_settings->value("HideAS", false).toBool()); - ui->actionHideAF->setChecked(m_settings->value("HideAF", false).toBool()); - ui->actionHideOC->setChecked(m_settings->value("HideOC", false).toBool()); - ui->actionHideAN->setChecked(m_settings->value("HideAN", false).toBool()); - ui->actionHighlight_Whitelist_entries->setChecked(m_settings->value("HighlightWhitelistEntries", false).toBool()); -// m_mode=m_settings->value("Mode","FT8").toString(); - ui->actionNone->setChecked(m_settings->value("SaveNone",true).toBool()); - ui->actionSave_decoded->setChecked(m_settings->value("SaveDecoded",false).toBool()); - ui->actionSave_all->setChecked(m_settings->value("SaveAll",false).toBool()); - ui->actionRemove_after_30days->setChecked(m_settings->value("RemoveAudioFiles",false).toBool()); - ui->RxFreqSpinBox->setValue(0); // ensure a change is signaled - ui->RxFreqSpinBox->setValue(m_settings->value("RxFreq",1500).toInt()); - ui->sbFST4W_RxFreq->setValue(0); - ui->sbFST4W_RxFreq->setValue(m_settings->value("FST4W_RxFreq",1500).toInt()); - ui->sbF_Low->setValue(m_settings->value("FST4_FLow",600).toInt()); - ui->sbF_High->setValue(m_settings->value("FST4_FHigh",1400).toInt()); - ui->sbFST4W_FTol->setValue(m_settings->value("FST4W_FTol",100).toInt()); - ui->sbToneSpacing->setValue(m_settings->value("EchoToneSpacing",10).toInt()); - ui->rbFixedTone->setChecked(m_settings->value("EchoFixedTone",true).toBool()); - ui->rbEchoMessage->setChecked(m_settings->value("EchoMessageRB",false).toBool()); - ui->rbEchoCW->setChecked(m_settings->value("EchoCW",false).toBool()); - ui->leEchoMessage->setText(m_settings->value("EchoMessage",QString {}).toString()); - m_minSync=m_settings->value("MinSync",0).toInt(); - ui->syncSpinBox->setValue(m_minSync); - ui->cbAutoSeq->setChecked (m_settings->value ("AutoSeq", false).toBool()); - ui->cbRxAll->setChecked (m_settings->value ("RxAll", false).toBool()); -// m_bShMsgs=m_settings->value("ShMsgs",false).toBool(); - m_bSWL=m_settings->value("SWL",false).toBool(); - m_bFast9=m_settings->value("Fast9",false).toBool(); - m_bFastMode=m_settings->value("FastMode",false).toBool(); - ui->sbMaxDrift->setValue (m_settings->value ("MaxDrift",0).toInt()); - ui->sbTR_FST4W->setValue (m_settings->value ("TRPeriod_FST4W", 15).toInt()); - m_lastMonitoredFrequency = m_settings->value ("DialFreq", - QVariant::fromValue<Frequency> (default_frequency)).value<Frequency> (); - m_skedFreq=m_settings->value("SkedFreq",1296.065).toDouble(); - QTimer::singleShot (1000, [=] {if (m_astroWidget) m_astroWidget->setSkedFreq(m_skedFreq);}); - if(m_mode=="MSK144") m_msk144basefreq = m_lastMonitoredFrequency; // MSK144 QSY - ui->WSPRfreqSpinBox->setValue(0); // ensure a change is signaled - ui->WSPRfreqSpinBox->setValue(m_settings->value("WSPRfreq",1500).toInt()); - ui->TxFreqSpinBox->setValue(0); // ensure a change is signaled - if(m_specOp!=SpecOp::FOX) ui->TxFreqSpinBox->setValue(m_settings->value("TxFreq",1500).toInt()); - m_TxFreqFox=m_settings->value("TxFreqFox",300).toInt(); - if(m_specOp==SpecOp::FOX && !m_config.superFox()) ui->TxFreqSpinBox->setValue(m_TxFreqFox); - m_ndepth=m_settings->value("NDepth",3).toInt(); - - //ft8md - ui->actionUse_multithreaded_FT8_decoder->setChecked(m_settings->value("MultithreadedFT8decoder", false).toBool()); - m_multithreadFT8 = ui->actionUse_multithreaded_FT8_decoder->isChecked(); - dec_data.params.lmultift8 = m_multithreadFT8; - - m_nFT8Cycles=m_settings->value("NFT8Cycles",3).toInt(); if(!(m_nFT8Cycles>=1 && m_nFT8Cycles<=3)) m_nFT8Cycles=3; - if(m_nFT8Cycles==1) ui->actionDecFT8cycles1->setChecked(true); - else if(m_nFT8Cycles==2) ui->actionDecFT8cycles2->setChecked(true); - else if(m_nFT8Cycles==3) ui->actionDecFT8cycles3->setChecked(true); - - m_nFT8RXfSens=m_settings->value("NFT8QSORXfreqSensitivity",3).toInt(); if(!(m_nFT8RXfSens>=1 && m_nFT8RXfSens<=3)) m_nFT8RXfSens=3; - if(m_nFT8RXfSens==1) ui->actionRXfLow->setChecked(true); - else if(m_nFT8RXfSens==2) ui->actionRXfMedium->setChecked(true); - else if(m_nFT8RXfSens==3) ui->actionRXfHigh->setChecked(true); - - m_ft8threads=m_settings->value("FT8threads",0).toInt(); - if(!(m_ft8threads>=0 && m_ft8threads<25)) m_ft8threads=0; - if(m_ft8threads==0) ui->actionMTAuto->setChecked(true); - else if(m_ft8threads==1) ui->actionMT1->setChecked(true); - else if(m_ft8threads==2) ui->actionMT2->setChecked(true); - else if(m_ft8threads==3) ui->actionMT3->setChecked(true); - else if(m_ft8threads==4) ui->actionMT4->setChecked(true); - else if(m_ft8threads==5) ui->actionMT5->setChecked(true); - else if(m_ft8threads==6) ui->actionMT6->setChecked(true); - else if(m_ft8threads==7) ui->actionMT7->setChecked(true); - else if(m_ft8threads==8) ui->actionMT8->setChecked(true); - else if(m_ft8threads==9) ui->actionMT9->setChecked(true); - else if(m_ft8threads==10) ui->actionMT10->setChecked(true); - else if(m_ft8threads==11) ui->actionMT11->setChecked(true); - else if(m_ft8threads==12) ui->actionMT12->setChecked(true); - qDebug() << "m_ft8threads is " << m_ft8threads; - dec_data.params.nmt = m_ft8threads; - - ui->actionHide_FT8_dupe_messages->setChecked(m_settings->value("HideFT8Dupes",true).toBool()); - - m_ft8Sensitivity=m_settings->value("FT8Sensitivity",3).toInt(); - if(!(m_ft8Sensitivity>0 && m_ft8Sensitivity<=3)) m_ft8Sensitivity=3; - if(m_ft8Sensitivity==1) ui->actionFT8SensMin->setChecked(true); - else if(m_ft8Sensitivity==2) ui->actionlowFT8thresholds->setChecked(true); - else if(m_ft8Sensitivity==3) ui->actionFT8subpass->setChecked(true); - - m_ft8DecoderStart=m_settings->value("FT8DecoderStart",3).toInt(); - if(!(m_ft8DecoderStart>=0 && m_ft8DecoderStart<=4)) m_ft8DecoderStart=3; - if(m_ft8DecoderStart==0) ui->actionStartTwoStage->setChecked(true); - else if(m_ft8DecoderStart==1) ui->actionStartThreeStage->setChecked(true); - else if(m_ft8DecoderStart==2) ui->actionStartEarly->setChecked(true); - else if(m_ft8DecoderStart==3) ui->actionStartNormal->setChecked(true); - else if(m_ft8DecoderStart==4) ui->actionStartLate->setChecked(true); - - m_FT8WideDxCallSearch=m_settings->value("FT8WideDXCallSearch",true).toBool(); - ui->actionFT8WidebandDXCallSearch->setChecked(m_FT8WideDxCallSearch); - //ft8md - - ui->sbTxPercent->setValue (m_settings->value ("PctTx", 20).toInt ()); - on_sbTxPercent_valueChanged (ui->sbTxPercent->value ()); - ui->RoundRobin->setCurrentText(m_settings->value("RoundRobin",tr("Random")).toString()); - m_dBm=m_settings->value("dBm",37).toInt(); - m_send_RR73=m_settings->value("RR73",false).toBool(); - m_score=m_settings->value("Score",0).toInt(); - if(m_send_RR73) { - m_send_RR73=false; - on_txrb4_doubleClicked(); - } - ui->WSPR_prefer_type_1_check_box->setChecked (m_settings->value ("WSPRPreferType1", true).toBool ()); - m_uploadWSPRSpots=m_settings->value("UploadSpots",false).toBool(); - ui->cbNoOwnCall->setChecked(m_settings->value("NoOwnCall",false).toBool()); - ui->band_hopping_group_box->setChecked (m_settings->value ("BandHopping", false).toBool()); - // setup initial value of tx attenuator - m_block_pwr_tooltip = true; - ui->outAttenuation->setValue (m_settings->value ("OutAttenuation", 0).toInt ()); - m_block_pwr_tooltip = false; - ui->sbCQTxFreq->setValue (m_settings->value ("CQTxFreq", 260).toInt()); - m_noSuffix=m_settings->value("NoSuffix",false).toBool(); - int n=m_settings->value("GUItab",0).toInt(); - if (SpecOp::FOX==m_specOp) { - ui->tabWidget->setCurrentIndex(n); - } else { - // We need this to initialize the height of tab 1 correctly - ui->pbFreeText->setVisible(false); - ui->cbSendMsg->setVisible(false); - ui->tabWidget->setCurrentIndex(1); - ui->tabWidget->setCurrentIndex(n); - } - outBufSize=m_settings->value("OutBufSize",4096).toInt(); - ui->cbHoldTxFreq->setChecked (m_settings->value ("HoldTxFreq", false).toBool ()); - HoldTxFreqStatus = m_settings->value ("HoldTxFreq", false).toBool (); - ui->cbCQonly->setChecked (m_settings->value ("CQonly", false).toBool ()); - ui->cbBypass->setChecked (m_settings->value ("BypassFilters", false).toBool ()); - m_pwrBandTxMemory=m_settings->value("pwrBandTxMemory").toHash(); - m_pwrBandTuneMemory=m_settings->value("pwrBandTuneMemory").toHash(); - ui->actionEnable_AP_FT8->setChecked (m_settings->value ("FT8AP", false).toBool()); - ui->actionEnable_AP_JT65->setChecked (m_settings->value ("JT65AP", false).toBool()); - ui->actionAuto_Clear_Avg->setChecked (m_settings->value ("AutoClearAvg", false).toBool()); - ui->actionDisable_clicks_on_waterfall->setChecked (m_settings->value ("DisableClicksOnWaterfall", false).toBool()); - ui->decodes_splitter->restoreState(m_settings->value("SplitterState").toByteArray()); - ui->sbNB->setValue(m_settings->value("Blanker",0).toInt()); - ui->sbEchoAvg->setValue(m_settings->value("EchoAvg",10).toInt()); - { - auto const& coeffs = m_settings->value ("PhaseEqualizationCoefficients" - , QList<QVariant> {0., 0., 0., 0., 0.}).toList (); - m_phaseEqCoefficients.clear (); - for (auto const& coeff : coeffs) - { - m_phaseEqCoefficients.append (coeff.value<double> ()); - } - } - m_settings->endGroup(); - - // use these initialisation settings to tune the audio o/p buffer - // size and audio thread priority - m_settings->beginGroup ("Tune"); - m_audioThreadPriority = static_cast<QThread::Priority> (m_settings->value ("Audio/ThreadPriority", QThread::TimeCriticalPriority).toInt () % 8); - m_settings->endGroup (); - - m_specOp=m_config.special_op_id(); - checkMSK144ContestType(); - if (displayMsgAvg) on_actionMessage_averaging_triggered(); - if (displayFoxLog) on_fox_log_action_triggered (); - if (displayContestLog) on_contest_log_action_triggered (); - if (displayActiveStations) on_actionActiveStations_triggered(); - if (displayQSYMessageCreator) on_actionQSYMessage_Creator_triggered(); - if (displayQSYMonitor) on_actionQSY_Monitor_triggered(); - -#ifdef WIN32 - if (m_config.alert_Enabled()) { // testing and initializing the default audio device for playing audible alerts - QAudioOutput info(QAudioDeviceInfo::defaultOutputDevice()); - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config.voicesPath() + "/"; - QAudioFormat format; - format.setCodec("audio/pcm"); - format.setSampleRate (48000); - format.setChannelCount (1); - format.setSampleSize (16); - format.setSampleType(QAudioFormat::SignedInt); - QAudioOutput* audio; - audio = new QAudioOutput(format, this); - QFile *effect = new QFile(this); - effect->setFileName(QString("%1/%2").arg(audioPath, "Testing.wav")); - effect->open(QIODevice::ReadOnly); - audio->start(effect); - } -#endif -} void MainWindow::checkMSK144ContestType() { @@ -2040,105 +2186,208 @@ void MainWindow::checkMSK144ContestType() void MainWindow::set_application_font (QFont const& font) { - // check if dark style is enabled, this check is also effective during the program start - if (ui->actionUse_Dark_Style->isChecked()) { - QFile f(":qdarkstyle/style.qss"); - if (!f.exists()) { - printf("Unable to set stylesheet, file not found\n"); - } else { - qApp->setFont (font); - QString ss; - f.open(QFile::ReadOnly | QFile::Text); - QTextStream ts(&f); - qApp->setStyleSheet(ts.readAll() + "* {" + font_as_stylesheet (font) + '}'); - m_useDarkStyle = true; - m_wideGraph->setDarkStyle(m_useDarkStyle); - check_button_color(); - ui->tabWidget->setTabShape(QTabWidget::Rounded); - } - } else { - m_useDarkStyle = false; - m_wideGraph->setDarkStyle(m_useDarkStyle); - check_button_color(); - ui->tabWidget->setTabShape(QTabWidget::Triangular); - qApp->setFont (font); - // set font in the application style sheet as well in case it has - // been modified in the style sheet which has priority - QString ss; - if (qApp->styleSheet ().size ()) { - auto sheet = qApp->styleSheet (); - sheet.remove ("file:///"); - QFile sf {sheet}; - if (sf.open (QFile::ReadOnly | QFile::Text)) - { - QString tmp = sf.readAll(); - if (tmp != NULL) ss = sf.readAll () + tmp; - else qDebug() << "tmp==NULL at sf.readAll"; - } - } - qApp->setStyleSheet (ss + "* {" + font_as_stylesheet (font) + '}'); - } - - // ensure a balanced layout + applyApplicationStyle (font, ui->actionUse_Dark_Style->isChecked ()); qreal pointSize = m_config.text_font().pointSizeF(); if (m_config.PWR_and_SWR()) { ui->label->setMinimumWidth (2.8*pointSize + 8); ui->label->setAlignment(Qt::AlignCenter); ui->outAttenuation->setMinimumWidth (2.8*pointSize + 8); } - if (pointSize < 11) { -// ui->tabWidget->setMaximumHeight(210); // UR for AL - if (ui->actionUse_Dark_Style->isChecked()) { -// ui->tabWidget->setMaximumHeight(225); // UR for normal + widescreen - ui->houndButton->setMinimumWidth(50); // UR for normal + widescreen - ui->ft8Button->setMinimumWidth(50); // UR for normal + widescreen - ui->ft4Button->setMinimumWidth(50); // UR for normal + widescreen - ui->msk144Button->setMinimumWidth(50); // UR for normal + widescreen - ui->q65Button->setMinimumWidth(50); // UR for normal + widescreen - ui->jt65Button->setMinimumWidth(50); // UR for normal + widescreen - } else { -// ui->tabWidget->setMaximumHeight(225); // UR for normal + widescreen - ui->houndButton->setMaximumWidth(40); // UR for normal + widescreen - ui->ft8Button->setMaximumWidth(40); // UR for normal + widescreen - ui->ft4Button->setMaximumWidth(40); // UR for normal + widescreen - ui->msk144Button->setMaximumWidth(40); // UR for normal + widescreen - ui->q65Button->setMaximumWidth(40); // UR for normal + widescreen - ui->jt65Button->setMaximumWidth(40); // UR for normal + widescreen - ui->houndButton->setMinimumWidth(0); // UR for normal + widescreen - ui->ft8Button->setMinimumWidth(0); // UR for normal + widescreen - ui->ft4Button->setMinimumWidth(0); // UR for normal + widescreen - ui->msk144Button->setMinimumWidth(0); // UR for normal + widescreen - ui->q65Button->setMinimumWidth(0); // UR for normal + widescreen - ui->jt65Button->setMinimumWidth(0); // UR for normal + widescreen - } - } else { -// ui->tabWidget->setMaximumHeight(255); // UR for AL -// ui->tabWidget->setMaximumHeight(500); // UR for normal + widescreen - ui->houndButton->setMinimumWidth(50); // UR for normal + widescreen - ui->ft8Button->setMinimumWidth(50); // UR for normal + widescreen - ui->ft4Button->setMinimumWidth(50); // UR for normal + widescreen - ui->msk144Button->setMinimumWidth(50); // UR for normal + widescreen - ui->q65Button->setMinimumWidth(50); // UR for normal + widescreen - ui->jt65Button->setMinimumWidth(50); // UR for normal + widescreen - } - if (m_config.largerTabWidget()) ui->tabWidget->setMaximumHeight(1000); - for (auto& widget : qApp->topLevelWidgets ()) +} + +void MainWindow::applyApplicationStyle (QFont const& font, bool dark) +{ + QString darkStyleSheet; + if (dark) + { + QFile file {":qdarkstyle/style.qss"}; + if (!file.open (QFile::ReadOnly | QFile::Text)) + { + qWarning () << "Unable to load dark stylesheet"; + return; + } + QTextStream stream {&file}; + darkStyleSheet = stream.readAll (); + } + + QFont prominentFont {font}; + if (font.pointSizeF () > 0.) prominentFont.setPointSizeF (font.pointSizeF () * 1.6); + else if (font.pixelSize () > 0) prominentFont.setPixelSize (qRound (font.pixelSize () * 1.6)); + auto styleSheet = application_style_sheet ( + m_base_style_sheet, darkStyleSheet, dark, font) + + "\nQLabel#labDialFreq, QLabel#labUTC {" + font_as_stylesheet (prominentFont) + '}'; +#ifdef Q_OS_MAC + if (!dark) + { + styleSheet += "\nQPushButton[wsjtxCompact=\"true\"] {" + "border: 1px solid palette(mid); border-radius: 4px; padding: 3px 6px; " + "background-color: palette(button); color: palette(button-text);}" + "\nQPushButton[wsjtxCompact=\"true\"]:focus {border-color: palette(highlight);}" + "\nQPushButton[wsjtxCompact=\"true\"]:pressed {background-color: palette(midlight);}" + "\nQPushButton[wsjtxCompact=\"true\"]:disabled {color: palette(mid);}"; + } +#endif + if (qApp->font () != font) qApp->setFont (font); + ui->outAttenuation->setProperty ("wsjtxDarkStyle", dark); + if (qApp->styleSheet () != styleSheet) qApp->setStyleSheet (styleSheet); + m_useDarkStyle = dark; + m_wideGraph->setDarkStyle (dark); + ui->tabWidget->setTabShape (dark ? QTabWidget::Rounded : QTabWidget::Triangular); + check_button_color (); + updateMainWindowControlSizes (); + for (auto * widget : qApp->topLevelWidgets ()) widget->updateGeometry (); +} + +void MainWindow::updateMainWindowControlSizes() +{ + auto setMinimumHintWidth = [] (QWidget * widget) + { + widget->setMinimumWidth (0); + widget->ensurePolished (); + widget->setMinimumWidth (widget->minimumSizeHint ().width ()); + }; + for (auto * widget : {static_cast<QWidget *> (ui->cbCQonly), + static_cast<QWidget *> (ui->cbBypass), + static_cast<QWidget *> (ui->lookupButton), + static_cast<QWidget *> (ui->addButton), + static_cast<QWidget *> (ui->ignoreButton), + static_cast<QWidget *> (ui->genStdMsgsPushButton)}) + { + setMinimumHintWidth (widget); + } + + ui->sbFtol_2->setMinimumWidth (0); + ui->sbFtol_2->setMaximumWidth (QWIDGETSIZE_MAX); + ui->sbFtol_2->ensurePolished (); + auto const toleranceText = ui->sbFtol_2->prefix () + + QString::number (ui->sbFtol_2->maximum ()) + ui->sbFtol_2->suffix (); + auto const toleranceChrome = ui->sbFtol_2->style ()->pixelMetric ( + QStyle::PM_ScrollBarExtent, nullptr, ui->sbFtol_2) + + 2 * ui->sbFtol_2->style ()->pixelMetric ( + QStyle::PM_SpinBoxFrameWidth, nullptr, ui->sbFtol_2) + 4; + ui->sbFtol_2->setMinimumWidth (qMax ( + ui->sbFtol_2->sizeHint ().width (), + ui->sbFtol_2->fontMetrics ().horizontalAdvance (toleranceText) + toleranceChrome)); + +#if defined (Q_OS_WIN) || defined (Q_OS_LINUX) + // These short action labels are not dialog confirmation buttons. Keep their + // native decoration, but give the message editors the otherwise reserved space. + for (auto * button : {static_cast<QPushButton *> (ui->lookupButton), + static_cast<QPushButton *> (ui->addButton), + static_cast<QPushButton *> (ui->ignoreButton)}) + { + button->ensurePolished (); + // Share the callsign row without imposing the style's dialog-button size + // hint on its parent or reserving space from the message editors. + button->setMinimumWidth (compactButtonSize (button).width ()); + button->setMaximumWidth (QWIDGETSIZE_MAX); + button->setSizePolicy (QSizePolicy::Ignored, button->sizePolicy ().verticalPolicy ()); + ui->lookup_control_layout->setStretchFactor (button, 1); + } +#endif + for (auto * button : {static_cast<QPushButton *> (ui->txb1), + static_cast<QPushButton *> (ui->txb2), + static_cast<QPushButton *> (ui->txb3), + static_cast<QPushButton *> (ui->txb4), + static_cast<QPushButton *> (ui->txb5), + static_cast<QPushButton *> (ui->txb6)}) + { + button->ensurePolished (); + button->setFixedWidth (compactButtonSize (button).width ()); + } + + for (auto * button : {ui->monitorButton, ui->autoButton}) + { + button->setMinimumWidth (0); + button->ensurePolished (); + auto text = button->text (); + text.remove (QLatin1Char ('&')); + auto const horizontalRoom = 4 * button->fontMetrics ().horizontalAdvance (QStringLiteral ("M")); + button->setMinimumWidth (qMax (button->minimumSizeHint ().width (), + button->fontMetrics ().horizontalAdvance (text) + horizontalRoom)); + } + + auto const actionTextHeight = ui->DecodeButton->fontMetrics ().height (); + auto const compactActionHeight = actionTextHeight + actionTextHeight / 2; + auto const prominentActionHeight = compactActionHeight + actionTextHeight / 4; + auto setActionHeight = [] (QWidget * button, int preferredHeight) { - widget->updateGeometry (); + button->setMinimumHeight (0); + button->setMaximumHeight (QWIDGETSIZE_MAX); + button->ensurePolished (); + button->setMinimumHeight (preferredHeight); + }; + for (auto * button : {ui->logQSOButton, ui->stopButton, ui->EraseButton, + ui->ClrAvgButton, ui->DecodeButton, ui->stopTxButton, + ui->tuneButton}) + { + setActionHeight (button, compactActionHeight); + } + for (auto * button : {ui->monitorButton, ui->autoButton}) + { + setActionHeight (button, prominentActionHeight); + } + + ui->cbHoldTxFreq->setMinimumWidth (0); + ui->cbHoldTxFreq->setMinimumHeight (0); + ui->cbHoldTxFreq->ensurePolished (); + ui->cbHoldTxFreq->setMinimumWidth ( + ui->cbHoldTxFreq->minimumSizeHint ().width ()); + ui->cbHoldTxFreq->setMinimumHeight (ui->cbHoldTxFreq->minimumSizeHint ().height ()); + + constexpr int formControlSpacing = 4; + struct FormRow + { + QLabel * label; + QWidget * control; + int extraWidth; + }; + FormRow rows[] = { + {m_txFrequencyLabel, ui->TxFreqSpinBox, 0}, + {m_rxFrequencyLabel, ui->RxFreqSpinBox, 0}, + {m_reportLabel, ui->rptSpinBox, + ui->rptSpinBox->fontMetrics ().horizontalAdvance (QStringLiteral ("M"))}, + {m_trPeriodLabel, ui->sbTR, 0} + }; + + int commonRowWidth = 0; + for (auto const& row : rows) + { + row.label->ensurePolished (); + row.control->setMinimumWidth (0); + row.control->setMaximumWidth (QWIDGETSIZE_MAX); + row.control->ensurePolished (); + commonRowWidth = qMax (commonRowWidth, + row.label->sizeHint ().width () + formControlSpacing + + row.control->minimumSizeHint ().width () + row.extraWidth); + } + for (auto const& row : rows) + { + row.control->setFixedWidth (commonRowWidth - row.label->sizeHint ().width () + - formControlSpacing); } + updateFrequencyToleranceRowAlignment (); +} + +void MainWindow::updateFrequencyToleranceRowAlignment() +{ + auto const leftMargin = m_frequencyToleranceLabel->isHidden () + ? m_txFrequencyLabel->sizeHint ().width () + 4 : 0; + m_frequencyToleranceRow->setContentsMargins (leftMargin, 0, 0, 0); } void MainWindow::setDecodedTextFont (QFont const& font) { ui->decodedTextBrowser->setContentFont (font); ui->decodedTextBrowser2->setContentFont (font); + ui->Tx_Message->setFont (font); ui->houndQueueTextBrowser->setContentFont(font); ui->houndQueueTextBrowser->displayHoundToBeCalled(" "); - ui->houndQueueTextBrowser->setText(""); + ui->houndQueueTextBrowser->clear(); ui->foxTxListTextBrowser->setContentFont(font); ui->foxTxListTextBrowser->displayHoundToBeCalled(" "); - ui->foxTxListTextBrowser->setText(""); + ui->foxTxListTextBrowser->clear(); auto style_sheet = "QLabel {" + font_as_stylesheet (font) + '}'; ui->lh_decodes_headings_label->setStyleSheet (ui->lh_decodes_headings_label->styleSheet () + style_sheet); @@ -2188,7 +2437,7 @@ void MainWindow::fixStop() } else if (m_mode=="FreqCal"){ m_hsymStop=((int(m_TRperiod/0.288))/8)*8; } else if (m_mode=="FT8") { - if (m_multithreadFT8 && !(m_specOp==SpecOp::HOUND && m_config.superFox())) { + if (usesFt8MtdFinal ()) { if (m_ft8DecoderStart==0) m_hsymStop=49; else if (m_ft8DecoderStart==1) { m_hsymStop=50; @@ -2218,6 +2467,8 @@ void MainWindow::fixStop() } else { m_hsymStop=stop[i]; } + } else if(m_mode=="JTTY") { + m_hsymStop=620; } } @@ -2238,16 +2489,27 @@ void MainWindow::dataSink(qint64 frames) m_bUseRef=m_wideGraph->useRef(); if(!m_diskData) { - refspectrum_(&dec_data.d2[k-m_nsps/2],&m_bClearRefSpec,&m_bRefSpec, - &m_bUseRef, fname.constData (), (FCL)fname.size ()); + if (m_bClearRefSpec) + { + int count = 0; + refspectrum_ (dec_data.d2, &count, &m_bClearRefSpec, &m_bRefSpec, + &m_bUseRef, fname.constData (), (FCL) fname.size ()); + } + m_bClearRefSpec=false; + m_referenceInput.consume (dec_data.d2, k, m_bRefSpec ? 1 : m_bUseRef ? 2 : 0, + [&] (short * samples, int count) { + refspectrum_ (samples, &count, &m_bClearRefSpec, &m_bRefSpec, + &m_bUseRef, fname.constData (), (FCL) fname.size ()); + }); } - m_bClearRefSpec=false; if(m_mode=="MSK144" or m_bFast9) { fastSink(frames); if(m_bFastMode) return; } + if(m_mode=="JTTY") fastSink(frames); + // Get power, spectrum, and ihsym dec_data.params.nfa=m_wideGraph->nStartFreq(); dec_data.params.nfb=m_wideGraph->Fmax(); @@ -2270,6 +2532,14 @@ void MainWindow::dataSink(qint64 frames) m_wideGraph->dataSink2(s,m_df3,m_ihsym,m_diskData,m_px); } if(m_mode=="MSK144") return; + if(m_mode=="JTTY") { + if(m_ihsym >= m_hsymStop and (m_saveAll or m_saveDecoded)) { + monitor(false); + jtty_save_wav(); + if(!m_diskData) monitor(true); + } + return; + } fixStop(); if (m_mode == "FreqCal" @@ -2277,7 +2547,7 @@ void MainWindow::dataSink(qint64 frames) // changed frequency && !(m_ihsym % 8) && m_ihsym > 8 && m_ihsym <= m_hsymStop) { int RxFreq=ui->RxFreqSpinBox->value (); - int nkhz=(m_freqNominal+RxFreq)/1000; + int nkhz=(m_operatingFrequency.rx ()+RxFreq)/1000; int ftol = ui->sbFtol->value (); freqcal_(&dec_data.d2[0], &k, &nkhz, &RxFreq, &ftol, &line[0], (FCL)80); QString t=QString::fromLatin1(line); @@ -2310,14 +2580,12 @@ void MainWindow::dataSink(qint64 frames) } if(m_ihsym==3*m_hsymStop/4) { - m_dialFreqRxWSPR=m_freqNominal; + m_dialFreqRxWSPR=m_operatingFrequency.rx (); } if(m_mode=="FT8") { - to_jt9(m_ihsym,-1,-1); //Allow jt9 to bail out early, if necessary - if(m_ihsym==40 and m_decoderBusy) { - qDebug() << "Clearing hung decoder status"; - decodeDone(); //Clear a hung decoder status + if(m_ihsym==40 and decoderBusy ()) { + recoverDecoderAtBoundary ("FT8 symbol-40 boundary", false); } } @@ -2352,6 +2620,7 @@ void MainWindow::dataSink(qint64 frames) // end of ft8md bool bCallDecoder=false; + auto ft8Stage = Ft8MtdDecodeCoordinator::Stage::None; if(m_multithreadFT8 && m_ft8DecoderStart==1) m_earlyDecode2 = 46; // ft8md @@ -2360,6 +2629,13 @@ void MainWindow::dataSink(qint64 frames) if(m_ihsym==m_earlyDecode) bCallDecoder=true; if(m_ihsym==m_earlyDecode2 && !(m_multithreadFT8 && m_ft8DecoderStart!=1)) bCallDecoder=true; } + // Standard FT8 passes share subtraction state; only an independent MTD final can be deferred. + if (m_mode == "FT8" && !m_diskData && bCallDecoder && usesFt8MtdFinal ()) + { + if (m_ihsym == m_hsymStop) ft8Stage = Ft8MtdDecodeCoordinator::Stage::Final; + else if (m_ihsym == m_earlyDecode) ft8Stage = Ft8MtdDecodeCoordinator::Stage::EarlyOne; + else if (m_ihsym == m_earlyDecode2) ft8Stage = Ft8MtdDecodeCoordinator::Stage::EarlyTwo; + } if(bCallDecoder) { if(m_mode=="Echo") { @@ -2382,20 +2658,24 @@ void MainWindow::dataSink(qint64 frames) int ndf=0; int idir=1; if(!ui->rbFixedTone->isChecked() and !m_diskData) { - ndf=ui->sbToneSpacing->value(); + if(ui->rbEchoMessage->isChecked()) ndf=ui->sbToneSpacing->value(); save_echo_params_(&nDopTotal,&nDop,&nfrit,&f1,&width,&ndf,&itone[0],dec_data.d2,&idir); } if(m_diskData) { idir=-1; save_echo_params_(&nDopTotal,&nDop,&nfrit,&f1,&width,&ndf,&itone[0],dec_data.d2,&idir); - if(ndf==0 and ui->rbEchoMessage->isChecked()) ui->rbFixedTone->setChecked(true); + if(ndf>=10 and ndf<=30) { + ui->rbEchoMessage->setChecked(true); + } else { + ui->rbFixedTone->setChecked(true); + } } bool bEchoCall=ui->rbEchoMessage->isChecked(); - QString txcall=ui->leEchoMessage->text(); + auto const txcall = ui->leEchoMessage->text().toLatin1().leftJustified(6, ' ', true); static char crxcall[7]; - avecho_(dec_data.d2,&nDop,&nfrit,&nauto,&ndf,&navg,&nqual,&f1,&xlevel,&sigdb, - &dBerr,&dfreq,&width,&m_diskData,&bEchoCall,txcall.toLatin1().constData(), + avecho_(dec_data.d2,&nDop,&nfrit,&nauto,&navg,&nqual,&f1,&xlevel,&sigdb, + &dBerr,&dfreq,&width,&m_diskData,&bEchoCall,txcall.constData(), &crxcall[0],(FCL)6,(FCL)6); crxcall[6]=0; QString rxcall {QString::fromLatin1(crxcall)}; @@ -2427,10 +2707,23 @@ void MainWindow::dataSink(qint64 frames) m_echoRunning=true; if(ndf<0 or ndf>30) ndf=0; QString t; - t = t.asprintf("%7.4f %5.2f %7d %7.1f %5d %5d %6d %6.1f %7.1f %3d",hour,xlevel, - nDopTotal,width,echocom_.nsum,nqual,qRound(dfreq),sigdb,dBerr,ndf); - t = t0 + t + " " + rxcall; - if(!bEchoCall) t=t.left(78); + if (!m_diskData) { + if (m_astroWidget) { + auto const dgrd = QByteArray::number(m_astroWidget->getDgrd(), 'f', 1); + t = t.asprintf("%7.4f %5.2f %7d %7.1f %5s %5d %5d %6d %6.1f %7.1f %3d",hour,xlevel, + nDopTotal,width,dgrd.constData(),echocom_.nsum,nqual,qRound(dfreq),sigdb,dBerr,ndf); + t = t0 + t + " " + rxcall; + } else { + t = t.asprintf("%7.4f %5.2f",hour,xlevel); + t = t0 + t + " Astronomical Data off; Level only"; + } + } else { + t = t.asprintf("%7.4f %5.2f %7d %7.1f %5d %5d %6d %6.1f %7.1f %3d",hour,xlevel, + nDopTotal,width,echocom_.nsum,nqual,qRound(dfreq),sigdb,dBerr,ndf); + t = t0 + t + " " + rxcall; + } + + if(!bEchoCall) t=t.left(84); if(ui) ui->decodedTextBrowser->insertText(t); t=t1 + t; write_all("Rx",t); @@ -2449,7 +2742,7 @@ void MainWindow::dataSink(qint64 frames) if(m_mode=="FreqCal") return; - if(m_dialFreqRxWSPR==0) m_dialFreqRxWSPR=m_freqNominal; + if(m_dialFreqRxWSPR==0) m_dialFreqRxWSPR=m_operatingFrequency.rx (); m_dataAvailable=true; dec_data.params.npts8=(m_ihsym*m_nsps)/16; dec_data.params.newdat=1; @@ -2462,7 +2755,29 @@ void MainWindow::dataSink(qint64 frames) m_dateTime = now.toString ("yyyy-MMM-dd hh:mm"); if(m_mode!="WSPR") { if (m_mode=="FT8" && m_multithreadFT8 && m_ihsym>47) last=now; // ft8md - decode(); //Start decoder + bool deferLiveAudioTestFinal {false}; + qint64 liveAudioTestFinalPeriod {-1}; +#if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) + deferLiveAudioTestFinal = m_automated_test + && m_liveAudioTestAwaitFt8InputCompletion + && Ft8MtdDecodeCoordinator::Stage::Final == ft8Stage; + if (deferLiveAudioTestFinal) + { + m_liveAudioTestPendingFt8FinalPeriod = currentFt8DecodePeriod (); + if (m_liveAudioTestFt8InputComplete) + { + liveAudioTestFinalPeriod = m_liveAudioTestPendingFt8FinalPeriod; + m_liveAudioTestPendingFt8FinalPeriod = -1; + m_liveAudioTestAwaitFt8InputCompletion = false; + m_liveAudioTestFt8InputComplete = false; + deferLiveAudioTestFinal = false; + } + } +#endif + if (!deferLiveAudioTestFinal) + { + decode (ft8Stage, liveAudioTestFinalPeriod); //Start decoder + } } if(m_mode=="FT8" and !(m_diskData or (m_multithreadFT8 && m_ft8DecoderStart<2)) and (m_ihsym==m_earlyDecode or m_ihsym==m_earlyDecode2)) return; @@ -2484,16 +2799,20 @@ void MainWindow::dataSink(qint64 frames) } int samples=m_TRperiod*12000; if(m_mode=="FT4") samples=21*3456; - // the following is potential a threading hazard - not a good - // idea to pass pointer to be processed in another thread - m_saveWAVWatcher.setFuture (QtConcurrent::run (std::bind (&MainWindow::save_wave_file, - this, m_fnameWE, &dec_data.d2[0], samples, m_config.my_callsign(), - m_config.my_grid(), m_mode, m_nSubMode, m_freqNominalPeriod, m_hisCall, m_hisGrid))); + double dgrd_value = 0.0; + QString dgrd; + if(m_astroWidget) { + dgrd_value = m_astroWidget->getDgrd(); + dgrd = QString("%1").arg(dgrd_value, 0, 'f', 1); + } else { + dgrd = "NoVal"; + } + save_wave_file (m_fnameWE, samples, m_freqNominalPeriod, dgrd); if (m_mode=="WSPR") { auto c2name {(m_fnameWE + ".c2").toLocal8Bit ()}; int nsec=120; int nbfo=1500; - double f0m1500=m_freqNominal/1000000.0 + nbfo - 1500; + double f0m1500=m_operatingFrequency.rx ()/1000000.0 + nbfo - 1500; int err = savec2_(c2name.constData (),&nsec,&f0m1500, (FCL)c2name.size()); if (err!=0) MessageBox::warning_message (this, tr ("Error saving c2 file"), c2name); } @@ -2516,12 +2835,16 @@ void MainWindow::dataSink(qint64 frames) << QDir::toNativeSeparators (m_config.writeable_data_dir ().absolutePath()) << t2 << m_fnameWE + ".wav"; } - if (ui) ui->DecodeButton->setChecked (true); - p1Timer.start(1000); - m_decoderBusy = true; - statusUpdate (); + if (beginDecode (DecodeOwner::Wsprd)) + { + if (ui) ui->DecodeButton->setChecked (true); + p1Timer.start(1000); + } } - m_rxDone=true; + if (!m_diskData && m_beaconTxController.active ()) + { + processBeaconActions (m_beaconTxController.receiveCompleted ()); + } } } @@ -2530,49 +2853,6 @@ void MainWindow::startP1() p1.start (QDir::toNativeSeparators (QDir {QApplication::applicationDirPath ()}.absoluteFilePath ("wsprd")), m_cmndP1); } -QString MainWindow::save_wave_file (QString const& name, short const * data, int samples, - QString const& my_callsign, QString const& my_grid, QString const& mode, qint32 sub_mode, - Frequency frequency, QString const& his_call, QString const& his_grid) const -{ - // - // This member function runs in a thread and should not access - // members that may be changed in the GUI thread or any other thread - // without suitable synchronization. - // - QAudioFormat format; - format.setCodec ("audio/pcm"); - format.setSampleRate (12000); - format.setChannelCount (1); - format.setSampleSize (16); - format.setSampleType (QAudioFormat::SignedInt); - auto source = QString {"%1; %2"}.arg (my_callsign).arg (my_grid); - auto comment = QString {"Mode=%1%2; Freq=%3%4"} - .arg (mode) - .arg (QString {(mode.contains ('J') && !mode.contains ('+')) - || mode.startsWith ("FST4") || mode.startsWith ('Q') - ? QString {"; Sub Mode="} + QString::number (int (samples / 12000)) + QChar {'A' + sub_mode} - : QString {}}) - .arg (Radio::frequency_MHz_string (frequency)) - .arg (QString {mode!="WSPR" ? QString {"; DXCall=%1; DXGrid=%2"} - .arg (his_call) - .arg (his_grid).toLocal8Bit () : ""}); - BWFFile::InfoDictionary list_info { - {{{'I','S','R','C'}}, source.toLocal8Bit ()}, - {{{'I','S','F','T'}}, program_title (revision ()).simplified ().toLocal8Bit ()}, - {{{'I','C','R','D'}}, QDateTime::currentDateTimeUtc () - .toString ("yyyy-MM-ddTHH:mm:ss.zzzZ").toLocal8Bit ()}, - {{{'I','C','M','T'}}, comment.toLocal8Bit ()}, - }; - auto file_name = name + ".wav"; - BWFFile wav {format, file_name, list_info}; - if (!wav.open (BWFFile::WriteOnly) - || 0 > wav.write (reinterpret_cast<char const *> (data) - , sizeof (short) * samples)) - { - return file_name + ": " + wav.errorString (); - } - return QString {}; -} //-------------------------------------------------------------- fastSink() void MainWindow::fastSink(qint64 frames) @@ -2582,14 +2862,15 @@ void MainWindow::fastSink(qint64 frames) filtered = false; ignored = false; m_muted = false; + if(k < m_k0) { //New sequence ? memcpy(fast_green2,fast_green,4*703); //Copy fast_green[] to fast_green2[] memcpy(fast_s2,fast_s,4*703*64); //Copy fast_s[] into fast_s2[] fast_jh2=fast_jh; - if(!m_diskData) memset(dec_data.d2,0,2*30*12000); //Zero the d2[] array m_bFastDecodeCalled=false; m_bDecoded=false; } + m_k0 = k; QDateTime tnow=QDateTime::currentDateTimeUtc(); int ihr=tnow.toString("hh").toInt(); @@ -2628,6 +2909,25 @@ void MainWindow::fastSink(qint64 frames) ui->signal_meter_widget->setValue(rmsNoGain,pxmax); // Update thermometer m_fastGraph->plotSpec(m_diskData,m_UTCdisk); + if(m_mode=="JTTY") { + jtty_decode(k); +#if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) + if (m_automated_test) + { + Q_EMIT liveAudioTestJttyFramesConsumed (k); + } +#endif + int detectorFrames = dec_data.params.kin; + if (!m_diskData) + { + QMutexLocker lock {&dec_data_mutex ()}; + detectorFrames = m_activeReceiveAudio + ? m_activeReceiveAudio->sourceFrames () : k; + } + if(detectorFrames - k < 10240) fast_decode_done(); + return; + } + if(bmsk144 and (line[0]!=0)) { QString message {QString::fromLatin1 (line)}; DecodedText decodedtext {message.replace (QChar::LineFeed, "")}; @@ -2635,318 +2935,42 @@ void MainWindow::fastSink(qint64 frames) QString text = decodedtext.string().replace("<","").replace(">",""); // for Wait features // Filtering for MSK144 - QString text2 = ""; - QStringList tw=text.mid(24).split(" ",SkipEmptyParts); - if (m_config.filters_for_word2()) { - if (tw.size () < 2) { - text2 = "___"; // prevent segfault errors with free text messages - } else if (tw[1].length() == 2 && tw[1].contains(QRegularExpression{"\\w\\w"})) { // directional calls - if (tw.size () > 2) { - text2 = tw[2]; // for directional calls analyze word 3 for filtering - } else { - text2 = "___"; // prevent segfault errors with free text messages - } - } else { - text2 = tw[1]; // otherwise analyze word 2 for filtering - } - if (!(SpecOp::NONE==m_specOp && m_config.AlwaysPass () // Always pass messages with keywords from Always Pass list - && ( - (text2.startsWith(m_config.Pass1()) && (m_config.Pass1()!="")) - || (text2.startsWith(m_config.Pass2()) && (m_config.Pass2()!="")) - || (text2.startsWith(m_config.Pass3()) && (m_config.Pass3()!="")) - || (text2.startsWith(m_config.Pass4()) && (m_config.Pass4()!="")) - || (text2.startsWith(m_config.Pass5()) && (m_config.Pass5()!="")) - || (text2.startsWith(m_config.Pass6()) && (m_config.Pass6()!="")) - || (text2.startsWith(m_config.Pass7()) && (m_config.Pass7()!="")) - || (text2.startsWith(m_config.Pass8()) && (m_config.Pass8()!="")) - || (text2.startsWith(m_config.Pass9()) && (m_config.Pass9()!="")) - || (text2.startsWith(m_config.Pass10()) && (m_config.Pass10()!="")) - || (text2.startsWith(m_config.Pass11()) && (m_config.Pass11()!="")) - || (text2.startsWith(m_config.Pass12()) && (m_config.Pass12()!="")) - ))) { - - // Filtering out messages with keywords from Blacklist - if (SpecOp::NONE==m_specOp && m_config.Blacklisted () - && ( - (text2.startsWith(m_config.Blacklist1()) && (m_config.Blacklist1()!="")) - || (text2.startsWith(m_config.Blacklist2()) && (m_config.Blacklist2()!="")) - || (text2.startsWith(m_config.Blacklist3()) && (m_config.Blacklist3()!="")) - || (text2.startsWith(m_config.Blacklist4()) && (m_config.Blacklist4()!="")) - || (text2.startsWith(m_config.Blacklist5()) && (m_config.Blacklist5()!="")) - || (text2.startsWith(m_config.Blacklist6()) && (m_config.Blacklist6()!="")) - || (text2.startsWith(m_config.Blacklist7()) && (m_config.Blacklist7()!="")) - || (text2.startsWith(m_config.Blacklist8()) && (m_config.Blacklist8()!="")) - || (text2.startsWith(m_config.Blacklist9()) && (m_config.Blacklist9()!="")) - || (text2.startsWith(m_config.Blacklist10()) && (m_config.Blacklist10()!="")) - || (text2.startsWith(m_config.Blacklist11()) && (m_config.Blacklist11()!="")) - || (text2.startsWith(m_config.Blacklist12()) && (m_config.Blacklist12()!="")) - )) { - if (!ui->cbBypass->isChecked()) filtered = true; - if (!(m_config.filters_for_Wait_and_Pounce_only() or ui->cbBypass->isChecked())) return; - // reset dB score when filtered - if (pounce && (ui->respondComboBox->currentText()=="CQ: Max Dist" - or ui->respondComboBox->currentText()=="CQ: Max dB" - or ui->respondComboBox->currentText()=="CQ: Min dB")) { - Dpoints=0; - maxDPoints=0; - dBpoints=-28; - dBpoints2=99; - maxdBPoints=-28; - mindBPoints=99; - } - - // Filtering out everything but messages with keywords from Whitelist - } else if (SpecOp::NONE==m_specOp && m_config.Whitelisted () - && !(text2.startsWith(m_config.Whitelist1()) && (m_config.Whitelist1()!="")) - && !(text2.startsWith(m_config.Whitelist2()) && (m_config.Whitelist2()!="")) - && !(text2.startsWith(m_config.Whitelist3()) && (m_config.Whitelist3()!="")) - && !(text2.startsWith(m_config.Whitelist4()) && (m_config.Whitelist4()!="")) - && !(text2.startsWith(m_config.Whitelist5()) && (m_config.Whitelist5()!="")) - && !(text2.startsWith(m_config.Whitelist6()) && (m_config.Whitelist6()!="")) - && !(text2.startsWith(m_config.Whitelist7()) && (m_config.Whitelist7()!="")) - && !(text2.startsWith(m_config.Whitelist8()) && (m_config.Whitelist8()!="")) - && !(text2.startsWith(m_config.Whitelist9()) && (m_config.Whitelist9()!="")) - && !(text2.startsWith(m_config.Whitelist10()) && (m_config.Whitelist10()!="")) - && !(text2.startsWith(m_config.Whitelist11()) && (m_config.Whitelist11()!="")) - && !(text2.startsWith(m_config.Whitelist12()) && (m_config.Whitelist12()!="")) - ) { - if (!ui->cbBypass->isChecked()) filtered = true; - if (!(m_config.filters_for_Wait_and_Pounce_only() or ui->cbBypass->isChecked())) return; - // reset dB score when filtered - if (pounce && (ui->respondComboBox->currentText()=="CQ: Max Dist" - or ui->respondComboBox->currentText()=="CQ: Max dB" - or ui->respondComboBox->currentText()=="CQ: Min dB")) { - Dpoints=0; - maxDPoints=0; - dBpoints=-28; - dBpoints2=99; - maxdBPoints=-28; - mindBPoints=99; - } - } - - // search logbook for filtering - if (ui->actionHideTerritory1->isChecked() or ui->actionHideTerritory2->isChecked() or - ui->actionHideTerritory3->isChecked() or ui->actionHideTerritory4->isChecked() or - ui->actionHideB4->isChecked() or ui->actionHideEU->isChecked() or ui->actionHideAS->isChecked() or - ui->actionHideNA->isChecked() or ui->actionHideSA->isChecked() or ui->actionHideAF->isChecked() or - ui->actionHideOC->isChecked() or ui->actionHideAN->isChecked()) { - QString deCall; - QString deGrid; - decodedtext.deCallAndGrid(/*out*/deCall,deGrid); - // search for country names - if (ui->actionHideTerritory1->isChecked() or ui->actionHideTerritory2->isChecked() or - ui->actionHideTerritory3->isChecked() or ui->actionHideTerritory4->isChecked()) { - auto const& looked_up = m_logBook.countries ()->lookup (deCall); - auto countryName = looked_up.entity_name; - // do some obvious abbreviations - countryName.replace ("Islands", "Is."); - countryName.replace ("Island", "Is."); - countryName.replace ("North ", "N. "); - countryName.replace ("Northern ", "N. "); - countryName.replace ("South ", "S. "); - countryName.replace ("East ", "E. "); - countryName.replace ("Eastern ", "E. "); - countryName.replace ("West ", "W. "); - countryName.replace ("Western ", "W. "); - countryName.replace ("Central ", "C. "); - countryName.replace (" and ", " & "); - countryName.replace ("Republic", "Rep."); - countryName.replace ("United States of America", "U.S.A."); - countryName.replace ("United States", "U.S.A."); - countryName.replace ("Fed. Rep. of ", ""); - countryName.replace ("French ", "Fr."); - countryName.replace ("Asiatic", "AS"); - countryName.replace ("European", "EU"); - countryName.replace ("African", "AF"); - if (ui->actionHideTerritory1->isChecked() && countryName.contains(m_config.Territory1()) - && (m_config.Territory1()!="") && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideTerritory2->isChecked() && countryName.contains(m_config.Territory2()) - && (m_config.Territory2()!="") && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideTerritory3->isChecked() && countryName.contains(m_config.Territory3()) - && (m_config.Territory3()!="") && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideTerritory4->isChecked() && countryName.contains(m_config.Territory4()) - && (m_config.Territory4()!="") && !ui->cbBypass->isChecked()) filtered = true; - } - // search for callsigns worked B4 on band - if (ui->actionHideB4->isChecked()) { - bool callB4onBand; - bool countryB4onBand; - bool gridB4onBand; - bool continentB4onBand; - bool CQZoneB4onBand; - bool ITUZoneB4onBand; - auto const& looked_up = m_logBook.countries ()->lookup (deCall); - m_logBook.match (deCall, m_mode, deGrid, looked_up, callB4onBand, countryB4onBand, gridB4onBand, - continentB4onBand, CQZoneB4onBand, ITUZoneB4onBand, m_currentBand); - if (callB4onBand && ui->actionHideB4->isChecked() && !ui->cbBypass->isChecked()) filtered = true; - } - // search for continents - if (ui->actionHideEU->isChecked() or ui->actionHideAS->isChecked() or ui->actionHideNA->isChecked() - or ui->actionHideSA->isChecked() or ui->actionHideAF->isChecked() or ui->actionHideOC->isChecked() - or ui->actionHideAN->isChecked()) { - auto const& looked_up = m_logBook.countries ()->lookup (deCall); - QString continent = AD1CCty::continent (looked_up.continent); - if (ui->actionHideEU->isChecked() && continent == "EU" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideAS->isChecked() && continent == "AS" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideNA->isChecked() && continent == "NA" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideSA->isChecked() && continent == "SA" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideAF->isChecked() && continent == "AF" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideOC->isChecked() && continent == "OC" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideAN->isChecked() && continent == "AN" && !ui->cbBypass->isChecked()) filtered = true; - } - } - } - } else { - if (!(SpecOp::NONE==m_specOp && m_config.AlwaysPass () // Always pass messages with keywords from Always Pass list - && ( - (text.contains(m_config.Pass1()) && (m_config.Pass1()!="")) - || (text.contains(m_config.Pass2()) && (m_config.Pass2()!="")) - || (text.contains(m_config.Pass3()) && (m_config.Pass3()!="")) - || (text.contains(m_config.Pass4()) && (m_config.Pass4()!="")) - || (text.contains(m_config.Pass5()) && (m_config.Pass5()!="")) - || (text.contains(m_config.Pass6()) && (m_config.Pass6()!="")) - || (text.contains(m_config.Pass7()) && (m_config.Pass7()!="")) - || (text.contains(m_config.Pass8()) && (m_config.Pass8()!="")) - || (text.contains(m_config.Pass9()) && (m_config.Pass9()!="")) - || (text.contains(m_config.Pass10()) && (m_config.Pass10()!="")) - || (text.contains(m_config.Pass11()) && (m_config.Pass11()!="")) - || (text.contains(m_config.Pass12()) && (m_config.Pass12()!="")) - ))) { - - // Filtering out messages with keywords from Blacklist - if (SpecOp::NONE==m_specOp && m_config.Blacklisted () - && ( - (text.contains(m_config.Blacklist1()) && (m_config.Blacklist1()!="")) - || (text.contains(m_config.Blacklist2()) && (m_config.Blacklist2()!="")) - || (text.contains(m_config.Blacklist3()) && (m_config.Blacklist3()!="")) - || (text.contains(m_config.Blacklist4()) && (m_config.Blacklist4()!="")) - || (text.contains(m_config.Blacklist5()) && (m_config.Blacklist5()!="")) - || (text.contains(m_config.Blacklist6()) && (m_config.Blacklist6()!="")) - || (text.contains(m_config.Blacklist7()) && (m_config.Blacklist7()!="")) - || (text.contains(m_config.Blacklist8()) && (m_config.Blacklist8()!="")) - || (text.contains(m_config.Blacklist9()) && (m_config.Blacklist9()!="")) - || (text.contains(m_config.Blacklist10()) && (m_config.Blacklist10()!="")) - || (text.contains(m_config.Blacklist11()) && (m_config.Blacklist11()!="")) - || (text.contains(m_config.Blacklist12()) && (m_config.Blacklist12()!="")) - )) { - if (!ui->cbBypass->isChecked()) filtered = true; - if (!(m_config.filters_for_Wait_and_Pounce_only() or ui->cbBypass->isChecked())) return; - // reset dB score when filtered - if (pounce && (ui->respondComboBox->currentText()=="CQ: Max Dist" - or ui->respondComboBox->currentText()=="CQ: Max dB" - or ui->respondComboBox->currentText()=="CQ: Min dB")) { - Dpoints=0; - maxDPoints=0; - dBpoints=-28; - dBpoints2=99; - maxdBPoints=-28; - mindBPoints=99; - } - - // Filtering out everything but messages with keywords from Whitelist - } else if (SpecOp::NONE==m_specOp && m_config.Whitelisted () - && !(text.contains(m_config.Whitelist1()) && (m_config.Whitelist1()!="")) - && !(text.contains(m_config.Whitelist2()) && (m_config.Whitelist2()!="")) - && !(text.contains(m_config.Whitelist3()) && (m_config.Whitelist3()!="")) - && !(text.contains(m_config.Whitelist4()) && (m_config.Whitelist4()!="")) - && !(text.contains(m_config.Whitelist5()) && (m_config.Whitelist5()!="")) - && !(text.contains(m_config.Whitelist6()) && (m_config.Whitelist6()!="")) - && !(text.contains(m_config.Whitelist7()) && (m_config.Whitelist7()!="")) - && !(text.contains(m_config.Whitelist8()) && (m_config.Whitelist8()!="")) - && !(text.contains(m_config.Whitelist9()) && (m_config.Whitelist9()!="")) - && !(text.contains(m_config.Whitelist10()) && (m_config.Whitelist10()!="")) - && !(text.contains(m_config.Whitelist11()) && (m_config.Whitelist11()!="")) - && !(text.contains(m_config.Whitelist12()) && (m_config.Whitelist12()!="")) - ) { - if (!ui->cbBypass->isChecked()) filtered = true; - if (!(m_config.filters_for_Wait_and_Pounce_only() or ui->cbBypass->isChecked())) return; - // reset dB score when filtered - if (pounce && (ui->respondComboBox->currentText()=="CQ: Max Dist" - or ui->respondComboBox->currentText()=="CQ: Max dB" - or ui->respondComboBox->currentText()=="CQ: Min dB")) { - Dpoints=0; - maxDPoints=0; - dBpoints=-28; - dBpoints2=99; - maxdBPoints=-28; - mindBPoints=99; - } - } - - // search logbook for filtering - if (ui->actionHideTerritory1->isChecked() or ui->actionHideTerritory2->isChecked() or - ui->actionHideTerritory3->isChecked() or ui->actionHideTerritory4->isChecked() or - ui->actionHideB4->isChecked() or ui->actionHideEU->isChecked() or ui->actionHideAS->isChecked() or - ui->actionHideNA->isChecked() or ui->actionHideSA->isChecked() or ui->actionHideAF->isChecked() or - ui->actionHideOC->isChecked() or ui->actionHideAN->isChecked()) { - QString deCall; - QString deGrid; - decodedtext.deCallAndGrid(/*out*/deCall,deGrid); - // search for country names - if (ui->actionHideTerritory1->isChecked() or ui->actionHideTerritory2->isChecked() or - ui->actionHideTerritory3->isChecked() or ui->actionHideTerritory4->isChecked()) { - auto const& looked_up = m_logBook.countries ()->lookup (deCall); - auto countryName = looked_up.entity_name; - // do some obvious abbreviations - countryName.replace ("Islands", "Is."); - countryName.replace ("Island", "Is."); - countryName.replace ("North ", "N. "); - countryName.replace ("Northern ", "N. "); - countryName.replace ("South ", "S. "); - countryName.replace ("East ", "E. "); - countryName.replace ("Eastern ", "E. "); - countryName.replace ("West ", "W. "); - countryName.replace ("Western ", "W. "); - countryName.replace ("Central ", "C. "); - countryName.replace (" and ", " & "); - countryName.replace ("Republic", "Rep."); - countryName.replace ("United States of America", "U.S.A."); - countryName.replace ("United States", "U.S.A."); - countryName.replace ("Fed. Rep. of ", ""); - countryName.replace ("French ", "Fr."); - countryName.replace ("Asiatic", "AS"); - countryName.replace ("European", "EU"); - countryName.replace ("African", "AF"); - if (ui->actionHideTerritory1->isChecked() && countryName.contains(m_config.Territory1()) - && (m_config.Territory1()!="") && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideTerritory2->isChecked() && countryName.contains(m_config.Territory2()) - && (m_config.Territory2()!="") && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideTerritory3->isChecked() && countryName.contains(m_config.Territory3()) - && (m_config.Territory3()!="") && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideTerritory4->isChecked() && countryName.contains(m_config.Territory4()) - && (m_config.Territory4()!="") && !ui->cbBypass->isChecked()) filtered = true; - } - // search for callsigns worked B4 on band - if (ui->actionHideB4->isChecked()) { - bool callB4onBand; - bool countryB4onBand; - bool gridB4onBand; - bool continentB4onBand; - bool CQZoneB4onBand; - bool ITUZoneB4onBand; - auto const& looked_up = m_logBook.countries ()->lookup (deCall); - m_logBook.match (deCall, m_mode, deGrid, looked_up, callB4onBand, countryB4onBand, gridB4onBand, - continentB4onBand, CQZoneB4onBand, ITUZoneB4onBand, m_currentBand); - if (callB4onBand && ui->actionHideB4->isChecked() && !ui->cbBypass->isChecked()) filtered = true; - } - // search for continents - if (ui->actionHideEU->isChecked() or ui->actionHideAS->isChecked() or ui->actionHideNA->isChecked() - or ui->actionHideSA->isChecked() or ui->actionHideAF->isChecked() or ui->actionHideOC->isChecked() - or ui->actionHideAN->isChecked()) { - auto const& looked_up = m_logBook.countries ()->lookup (deCall); - QString continent = AD1CCty::continent (looked_up.continent); - if (ui->actionHideEU->isChecked() && continent == "EU" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideAS->isChecked() && continent == "AS" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideNA->isChecked() && continent == "NA" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideSA->isChecked() && continent == "SA" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideAF->isChecked() && continent == "AF" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideOC->isChecked() && continent == "OC" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideAN->isChecked() && continent == "AN" && !ui->cbBypass->isChecked()) filtered = true; - } - } - } - } + MessageFilterLogic::FilterContext ctx; + ctx.specOp = m_specOp; + ctx.bypass = ui->cbBypass->isChecked(); + ctx.filtersForWord2 = m_config.filters_for_word2(); + ctx.filtersForWaitAndPounceOnly = m_config.filters_for_Wait_and_Pounce_only(); + ctx.alwaysPass = m_config.AlwaysPass(); + ctx.blacklisted = m_config.Blacklisted(); + ctx.whitelisted = m_config.Whitelisted(); + ctx.passKeywords = m_config.pass_keywords(); + ctx.blacklistKeywords = m_config.blacklist_keywords(); + ctx.whitelistKeywords = m_config.whitelist_keywords(); + ctx.hideTerritory1 = ui->actionHideTerritory1->isChecked(); + ctx.hideTerritory2 = ui->actionHideTerritory2->isChecked(); + ctx.hideTerritory3 = ui->actionHideTerritory3->isChecked(); + ctx.hideTerritory4 = ui->actionHideTerritory4->isChecked(); + ctx.hideB4 = ui->actionHideB4->isChecked(); + ctx.hideEU = ui->actionHideEU->isChecked(); + ctx.hideAS = ui->actionHideAS->isChecked(); + ctx.hideNA = ui->actionHideNA->isChecked(); + ctx.hideSA = ui->actionHideSA->isChecked(); + ctx.hideAF = ui->actionHideAF->isChecked(); + ctx.hideOC = ui->actionHideOC->isChecked(); + ctx.hideAN = ui->actionHideAN->isChecked(); + ctx.territory1 = m_config.Territory1(); + ctx.territory2 = m_config.Territory2(); + ctx.territory3 = m_config.Territory3(); + ctx.territory4 = m_config.Territory4(); + ctx.currentBand = m_currentBand; + ctx.mode = m_mode; + ctx.pounce = pounce; + ctx.respondPolicy = autoRespondPolicy (); + + auto filterResult = MessageFilterLogic::evaluateMSK144(decodedtext, ctx, &m_logBook); + if (filterResult.filtered) filtered = true; + if (filterResult.resetPoints) m_autoRespondScores.reset(); + if (filterResult.shouldReturn) return; // hide or ignore callsigns for MSK144 if (ui->actionHideIgnored->isChecked() or ui->actionHideToday->isChecked() or ui->actionIgnoreIgnored->isChecked() or ui->actionIgnoreToday->isChecked()) { @@ -2990,157 +3014,18 @@ void MainWindow::fastSink(qint64 frames) } } - // Stop Wait & Call timeout when in QSO with this station for MSK144 - if (ui->DX_Call_Button->isChecked() && m_hisCall!="" && text.contains(" " + m_config.my_callsign() + " " + m_hisCall)) { - stopWCTimer.stop(); // stop any Wait & Call timeout - if (ui->DX_Call_Button->isChecked()) ui->DX_Call_Button->click (); // disable Wait & Call - no_wait_and_call = false; // reset Wait & Call - } - - // Wait & Reply for MSK144 - if (text.contains(" " + m_config.my_callsign() + " " + m_hisCall) && m_hisCall!="" && - !text.contains("73 ") && m_mode=="MSK144" && m_config.Wait_features_enabled() - && !ui->autoButton->isChecked() - && (!(ui->actionFull_Duplex_Mode->isChecked() && m_txing))) { - tx_watchdog (false); - m_bDoubleClicked = true; - processMessage(decodedtext); - auto_tx_mode(true); - stopWRTimer.start(int(12000.0*m_TRperiod)); // Wait & Reply Tx max 12*TRperiod - } - - // Wait & Call for MSK144 - if (m_mode=="MSK144" && wait_and_call && m_specOp!=SpecOp::FOX && ui->cbAutoSeq->isChecked() && - m_hisCall!="" && (text.contains("CQ " + m_hisCall) or text.contains("CQ DX " + m_hisCall) or text.contains(m_hisCall + " RR73") - or text.contains(m_hisCall + " RRR") or text.contains(m_hisCall + " 73")) && m_config.Wait_features_enabled() - && (!(ui->actionFull_Duplex_Mode->isChecked() && m_txing))) { - m_bDoubleClicked = true; - processMessage(decodedtext); - auto_tx_mode(true); - no_wait_and_call = true; - stopWCTimer.start(int(6200.0*m_TRperiod)); // Wait & Call Tx max 6*TRperiod - } - - // CQ: First for MSK144 - if(((pounce && text.contains(" CQ ") && m_config.Wait_features_enabled()) - or (m_auto && m_bCallingCQ && text.contains(" " + m_config.my_callsign() + " "))) && !ignored - && !filtered && !selected && ui->respondComboBox->isVisible() && ui->respondComboBox->currentText()=="CQ: First" - && (!(ui->actionFull_Duplex_Mode->isChecked() && m_txing))) { - m_bDoubleClicked=true; - selected = true; - auto_tx_mode(true); - processMessage(decodedtext); - auto now = QDateTime::currentDateTimeUtc(); - m_dateTimeQSOOn = now.addSecs (-(m_ntx - 1) * int(m_TRperiod) - int(fmod(double(now.time().second()),m_TRperiod))); - QTimer::singleShot (6000, [=] {selected = false;}); - if (pounce) stopWCTimer.start(int(6200.0*m_TRperiod)); // Tx max 6*TRperiod - } - - // CQ: Max Dist for MSK144 - if((pounce or m_auto) && ui->respondComboBox->isVisible() && ui->respondComboBox->currentText()=="CQ: Max Dist" - && (!(ui->actionFull_Duplex_Mode->isChecked() && m_txing))) { - QString deCall; - QString deGrid; - decodedtext.deCallAndGrid(/*out*/deCall,deGrid); - if (!filtered && !ignored && (deGrid.contains(grid_regexp) or m_bCallingCQ) && ( - (pounce && text.contains(" CQ ") && !txLog.contains(deCall) && m_config.Wait_features_enabled()) or - (m_bCallingCQ && text.contains(" " + m_config.my_callsign() + " ") && !text.contains("73 ")) - )) { - double utch=0.0; - int nAz,nEl,nDmiles,nDkm,nHotAz,nHotABetter; - azdist_(const_cast <char *> ((m_config.my_grid () + " ").left (6).toLatin1().constData()), - const_cast <char *> ((deGrid + " ").left (6).toLatin1().constData()),&utch, - &nAz,&nEl,&nDmiles,&nDkm,&nHotAz,&nHotABetter,6,6); - Dpoints=nDkm; - if (!deGrid.contains(grid_regexp)) Dpoints=1; - if(Dpoints>maxDPoints) { - maxDPoints=Dpoints; - m_deCall=deCall; - m_bDoubleClicked=true; - if ((pounce && text.contains(" CQ ") && m_config.Wait_features_enabled()) or m_auto) { - auto_tx_mode(true); - processMessage(decodedtext); - if (pounce) stopWCTimer.start(int(6200.0*m_TRperiod)); // Tx max 6*TRperiod - } - ui->dxCallEntry->setText(deCall); - genStdMsgs(QString::number(decodedtext.snr())); - ui->RxFreqSpinBox->setValue(decodedtext.frequencyOffset()); - setTxMsg(m_ntx); - m_currentMessageType=m_ntx; - auto now = QDateTime::currentDateTimeUtc(); - m_dateTimeQSOOn = now.addSecs (-(m_ntx - 1) * int(m_TRperiod) - int(fmod(double(now.time().second()),m_TRperiod))); - } - } - } - - // CQ: Max dB for MSK144 - if((pounce or m_auto) && ui->respondComboBox->isVisible() && ui->respondComboBox->currentText()=="CQ: Max dB" - && (!(ui->actionFull_Duplex_Mode->isChecked() && m_txing))) { - QString deCall; - QString deGrid; - decodedtext.deCallAndGrid(/*out*/deCall,deGrid); - if (!filtered && !ignored && ( - (pounce && text.contains(" CQ ") && !txLog.contains(deCall) && m_config.Wait_features_enabled()) or - (m_bCallingCQ && text.contains(" " + m_config.my_callsign() + " ") && !text.contains("73 ")) - )) { - dBpoints=decodedtext.string().mid(7,3).toInt(); - if(dBpoints>maxdBPoints) { - maxdBPoints=dBpoints; - m_deCall=deCall; - m_bDoubleClicked=true; - if ((pounce && text.contains(" CQ ") && m_config.Wait_features_enabled()) or m_auto) { - auto_tx_mode(true); - processMessage(decodedtext); - if (pounce) stopWCTimer.start(int(6200.0*m_TRperiod)); // Tx max 6*TRperiod - } - ui->dxCallEntry->setText(deCall); - genStdMsgs(QString::number(decodedtext.snr())); - ui->RxFreqSpinBox->setValue(decodedtext.frequencyOffset()); - setTxMsg(m_ntx); - m_currentMessageType=m_ntx; - auto now = QDateTime::currentDateTimeUtc(); - m_dateTimeQSOOn = now.addSecs (-(m_ntx - 1) * int(m_TRperiod) - int(fmod(double(now.time().second()),m_TRperiod))); - } - } - } + if (processWaitReplyCall( + decodedtext, DecodedMessageReaction::WaitDecodeSource::Msk144FastDecoder) + == DecodedMessageReaction::ReactionDisposition::IgnoreDecode) return; - // CQ: Min dB for MSK144 - if((pounce or m_auto) && ui->respondComboBox->isVisible() && ui->respondComboBox->currentText()=="CQ: Min dB" - && (!(ui->actionFull_Duplex_Mode->isChecked() && m_txing))) { - QString deCall; - QString deGrid; - decodedtext.deCallAndGrid(/*out*/deCall,deGrid); - if (!filtered && !ignored && ( - (pounce && text.contains(" CQ ") && !txLog.contains(deCall) && m_config.Wait_features_enabled()) or - (m_bCallingCQ && text.contains(" " + m_config.my_callsign() + " ") && !text.contains("73 ")) - )) { - dBpoints2=decodedtext.string().mid(7,3).toInt(); - if(dBpoints2<mindBPoints) { - mindBPoints=dBpoints2; - m_deCall=deCall; - m_bDoubleClicked=true; - if ((pounce && text.contains(" CQ ") && m_config.Wait_features_enabled()) or m_auto) { - auto_tx_mode(true); - processMessage(decodedtext); - if (pounce) stopWCTimer.start(int(6200.0*m_TRperiod)); // Tx max 6*TRperiod - } - ui->dxCallEntry->setText(deCall); - genStdMsgs(QString::number(decodedtext.snr())); - ui->RxFreqSpinBox->setValue(decodedtext.frequencyOffset()); - setTxMsg(m_ntx); - m_currentMessageType=m_ntx; - auto now = QDateTime::currentDateTimeUtc(); - m_dateTimeQSOOn = now.addSecs (-(m_ntx - 1) * int(m_TRperiod) - int(fmod(double(now.time().second()),m_TRperiod))); - } - } - } + updateRespondTarget(decodedtext, text, pounce, m_dateTimeSeqStart, m_diskData); // show distance and bearing for MSK144 if (!filtered or m_config.filters_for_Wait_and_Pounce_only()) { QString distance; QString deCall; QString deGrid; decodedtext.deCallAndGrid(deCall,deGrid); - if ((m_config.showDistance() || m_config.showAzimuth()) && deGrid.contains(grid_regexp)) { + if ((m_config.showDistance() || m_config.showAzimuth()) && deGrid.contains(MainWindow::grid_regexp)) { double utch=0.0; int nAz,nEl,nDmiles,nDkm,nHotAz,nHotABetter; QString my_Grid = m_config.my_grid(); @@ -3167,12 +3052,12 @@ void MainWindow::fastSink(qint64 frames) // insert blank line for MSK144 int ntime=6; - if ((m_config.insert_blank() or m_config.alert_Enabled()) && !BlankLineInserted && (text.left(ntime) != m_tBlankLine) && text.left(4).contains(QRegularExpression {"\\d\\d\\d\\d"}) && !m_diskData) { + if ((m_config.insert_blank() or m_config.alert_Enabled()) && !BlankLineInserted && (text.left(ntime) != m_tBlankLine) && text.left(4).contains(four_digit_regexp) && !m_diskData) { ui->decodedTextBrowser->new_period (); if (m_config.insert_blank () && (!filtered or m_config.filters_for_Wait_and_Pounce_only())) { QString band; if(((QDateTime::currentMSecsSinceEpoch() / 1000 - m_secBandChanged) > 4*int(m_TRperiod)/4) or m_displayBand) { - band = ' ' + m_config.bands ()->find (m_freqNominal); + band = ' ' + m_config.bands ()->find (m_operatingFrequency.rx ()); } if (m_config.insert_blank ()) { if (ui->actionUse_Dark_Style->isChecked()) { @@ -3218,12 +3103,13 @@ void MainWindow::fastSink(qint64 frames) if (m_mode=="MSK144" && text.mid(22).contains(m_baseCall + " " + m_hisCall + " 73")) { ui->decodedTextBrowser2->displayDecodedText (decodedtext, m_config.my_callsign (), m_mode, m_config.DXCC (), m_logBook, m_currentBand, m_config.ppfx (), false, false, 0.0, false, -99, "", m_muted); + applyHighlighting(decodedtext, ui->decodedTextBrowser2, false, play_Wanted, play_DXcall); } } // Ensure that Tx stops when "73" is received and repeat_Tx is enabled for MSK144 - if (m_config.repeat_Tx() && m_mode=="MSK144" && m_hisCall!="" && text.contains(m_baseCall) && text.contains(m_hisCall + " 73") && m_send_RR73) - QTimer::singleShot (int(750*m_TRperiod), [=] {cease_auto_Tx_after_QSO();}); + if (m_config.repeat_Tx() && m_mode=="MSK144" && m_hisCall!="" && text.contains(m_baseCall) && text.contains(m_hisCall + " 73") && send_rr73_for_tx4 ()) + QTimer::singleShot (int(750*m_TRperiod), this, [=] {cease_auto_Tx_after_QSO();}); // highlight orange and blue callsigns for MSK144 if(m_config.highlight_orange() or (m_config.highlight_blue()) or ui->actionHighlight_Whitelist_entries->isChecked()) { @@ -3232,8 +3118,8 @@ void MainWindow::fastSink(qint64 frames) decodedtext.deCallAndGrid(/*out*/deCall,deGrid); QStringList tw; tw=text.mid(22).split(" ",SkipEmptyParts); - if (m_config.highlight_orange() && deCall.size()>2 && (m_config.highlight_orange_callsigns().contains(deCall + ",") - or m_config.highlight_orange_callsigns().contains(deCall.left(3) + ";") or m_config.highlight_orange_callsigns().contains(deCall.left(2) + ";"))) { + if (m_config.highlight_orange() && deCall.size()>2 + && HighlightingRules::matchesCallsignPrefix(m_config.highlight_orange_callsigns(), deCall)) { ui->decodedTextBrowser->highlight_callsign(deCall, QColor(225,75,0), QColor(255,255,255), true); if (m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted) play_Wanted = true; } @@ -3241,8 +3127,8 @@ void MainWindow::fastSink(qint64 frames) ui->decodedTextBrowser->highlight_callsign(deGrid, QColor(225,75,0), QColor(255,255,255), true); if (m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted) play_Wanted = true; } - if (m_config.highlight_blue() && deCall.size()>2 && (m_config.highlight_blue_callsigns().contains(deCall + ",") - or m_config.highlight_blue_callsigns().contains(deCall.left(3) + ";") or m_config.highlight_blue_callsigns().contains(deCall.left(2) + ";"))) { + if (m_config.highlight_blue() && deCall.size()>2 + && HighlightingRules::matchesCallsignPrefix(m_config.highlight_blue_callsigns(), deCall)) { ui->decodedTextBrowser->highlight_callsign(deCall, QColor(0,100,255), QColor(255,255,255), true); if (m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted) play_Wanted = true; } @@ -3252,29 +3138,20 @@ void MainWindow::fastSink(qint64 frames) } // highlight directional calls if (tw.size () > 2) { - if (m_config.highlight_orange() && tw[0]=="CQ" && m_config.highlight_orange_callsigns().contains("," + tw[1] + ",")) { + if (m_config.highlight_orange() && tw[0]=="CQ" + && HighlightingRules::matchesDirectionalCall(m_config.highlight_orange_callsigns(), tw[1])) { ui->decodedTextBrowser->highlight_callsign(tw[1], QColor(225,75,0), QColor(255,255,255), true); if (m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted && tw[1]!="") play_Wanted = true; } - if (m_config.highlight_blue() && tw[0]=="CQ" && m_config.highlight_blue_callsigns().contains("," + tw[1] + ",")) { + if (m_config.highlight_blue() && tw[0]=="CQ" + && HighlightingRules::matchesDirectionalCall(m_config.highlight_blue_callsigns(), tw[1])) { ui->decodedTextBrowser->highlight_callsign(tw[1], QColor(0,100,255), QColor(255,255,255), true); if (m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted && tw[1]!="") play_Wanted = true; } } // highlight Whitelist entries if (ui->actionHighlight_Whitelist_entries->isChecked() && deCall.size()>2 && - ((deCall.contains(m_config.Whitelist1()) && m_config.Whitelist1() != "") - or (deCall.contains(m_config.Whitelist2()) && m_config.Whitelist2() != "") - or (deCall.contains(m_config.Whitelist3()) && m_config.Whitelist3() != "") - or (deCall.contains(m_config.Whitelist4()) && m_config.Whitelist4() != "") - or (deCall.contains(m_config.Whitelist5()) && m_config.Whitelist5() != "") - or (deCall.contains(m_config.Whitelist6()) && m_config.Whitelist6() != "") - or (deCall.contains(m_config.Whitelist7()) && m_config.Whitelist7() != "") - or (deCall.contains(m_config.Whitelist8()) && m_config.Whitelist8() != "") - or (deCall.contains(m_config.Whitelist9()) && m_config.Whitelist9() != "") - or (deCall.contains(m_config.Whitelist10()) && m_config.Whitelist10() != "") - or (deCall.contains(m_config.Whitelist11()) && m_config.Whitelist11() != "") - or (deCall.contains(m_config.Whitelist12()) && m_config.Whitelist12() != ""))) { + MessageFilter::containsAny(deCall, m_config.whitelist_keywords())) { ui->decodedTextBrowser->highlight_callsign(deCall, QColor(170,0,127), QColor(255,255,255), true); if (m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted) play_Wanted = true; } @@ -3313,27 +3190,7 @@ void MainWindow::fastSink(qint64 frames) if (ui->actionHighlightTerritory1->isChecked() or ui->actionHighlightTerritory2->isChecked() or ui->actionHighlightTerritory3->isChecked() or ui->actionHighlightTerritory4->isChecked()) { auto const& looked_up = m_logBook.countries ()->lookup (deCall); - auto countryName = looked_up.entity_name; - // do some obvious abbreviations - countryName.replace ("Islands", "Is."); - countryName.replace ("Island", "Is."); - countryName.replace ("North ", "N. "); - countryName.replace ("Northern ", "N. "); - countryName.replace ("South ", "S. "); - countryName.replace ("East ", "E. "); - countryName.replace ("Eastern ", "E. "); - countryName.replace ("West ", "W. "); - countryName.replace ("Western ", "W. "); - countryName.replace ("Central ", "C. "); - countryName.replace (" and ", " & "); - countryName.replace ("Republic", "Rep."); - countryName.replace ("United States of America", "U.S.A."); - countryName.replace ("United States", "U.S.A."); - countryName.replace ("Fed. Rep. of ", ""); - countryName.replace ("French ", "Fr."); - countryName.replace ("Asiatic", "AS"); - countryName.replace ("European", "EU"); - countryName.replace ("African", "AF"); + auto countryName =looked_up.abbreviated_entity_name; if (ui->actionHighlightTerritory1->isChecked() && countryName.contains(m_config.Territory1()) && (m_config.Territory1()!="") && !ui->cbBypass->isChecked()) ui->decodedTextBrowser->highlight_callsign(deCall, QColor(115,43,245), QColor(255,255,255), true); if (ui->actionHighlightTerritory2->isChecked() && countryName.contains(m_config.Territory2()) @@ -3352,43 +3209,17 @@ void MainWindow::fastSink(qint64 frames) if (m_config.highlight_DXcall()) { // repeated highlighting to override JTAlert ui->decodedTextBrowser->highlight_callsign(m_hisCall, QColor(255,0,0), QColor(255,255,255), true); - QTimer::singleShot (500, [=] {ui->decodedTextBrowser->highlight_callsign(m_hisCall, QColor(255,0,0), QColor(255,255,255), true);}); - QTimer::singleShot (1000, [=] {ui->decodedTextBrowser->highlight_callsign(m_hisCall, QColor(255,0,0), QColor(255,255,255), true);}); - QTimer::singleShot (2500, [=] {ui->decodedTextBrowser->highlight_callsign(m_hisCall, QColor(255,0,0), QColor(255,255,255), true);}); + QTimer::singleShot (500, this, [=] {ui->decodedTextBrowser->highlight_callsign(m_hisCall, QColor(255,0,0), QColor(255,255,255), true);}); + QTimer::singleShot (1000, this, [=] {ui->decodedTextBrowser->highlight_callsign(m_hisCall, QColor(255,0,0), QColor(255,255,255), true);}); + QTimer::singleShot (2500, this, [=] {ui->decodedTextBrowser->highlight_callsign(m_hisCall, QColor(255,0,0), QColor(255,255,255), true);}); } } if (!pounce && (m_config.highlight_DXgrid () or m_config.alert_Enabled()) && (m_hisGrid!="") && (decodedtext.string().contains(m_hisGrid.left(4)))) { if (m_config.highlight_DXgrid()) ui->decodedTextBrowser->highlight_callsign(m_hisGrid.left(4), QColor(0,0,200), QColor(255,255,255), true); if (m_config.alert_Enabled() && m_config.alert_DXcall() && !m_muted) play_DXcall = true; } - QTimer::singleShot (100, [=] { - if (m_config.alert_Enabled() && ((m_config.alert_DXcall() && play_DXcall && m_hisCall!="") or (m_config.alert_Wanted() && play_Wanted))) { -#ifdef WIN32 - QAudioOutput info(QAudioDeviceInfo::defaultOutputDevice()); - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config.voicesPath() + "/"; - QAudioFormat format; - format.setCodec("audio/pcm"); - format.setSampleRate (48000); - format.setChannelCount (1); - format.setSampleSize (16); - format.setSampleType(QAudioFormat::SignedInt); - QAudioOutput* audio; - audio = new QAudioOutput(format, this); - connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State))); - QFile *effect1 = new QFile(this); - if (m_config.alert_DXcall() && play_DXcall) effect1->setFileName(QString("%1/%2").arg(audioPath, "DXcall.wav")); - else if (m_config.alert_Wanted() && play_Wanted) effect1->setFileName(QString("%1/%2").arg(audioPath, "Wanted.wav")); - effect1->open(QIODevice::ReadOnly); - audio->start(effect1); -#else - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config.voicesPath() + "/"; - if (m_config.alert_DXcall() && play_DXcall) QSound::play(audioPath + "DXcall.wav"); // for Linux and macOS - else if (m_config.alert_DXcall() && play_Wanted) QSound::play(audioPath + "Wanted.wav"); // for Linux and macOS -#endif - play_DXcall = false; - play_Wanted = false; - } - }); + playDecodeAlertSound(play_Wanted, play_DXcall); + play_Wanted = play_DXcall = false; m_bDecoded=true; auto_sequence (decodedtext, ui->sbFtol->value (), std::numeric_limits<unsigned>::max ()); @@ -3409,7 +3240,6 @@ void MainWindow::fastSink(qint64 frames) m_bFastDone=true; } - m_k0=k; if(m_diskData and m_k0 >= dec_data.params.kin - 7 * 512) decodeNow=true; if(!m_diskData and m_tRemaining<0.35 and !m_bFastDecodeCalled) decodeNow=true; if(m_mode=="MSK144") decodeNow=false; @@ -3420,7 +3250,7 @@ void MainWindow::fastSink(qint64 frames) m_t1=k/12000.0; m_kdone=k; dec_data.params.newdat=1; - if(!m_decoderBusy) { + if(!decoderBusy ()) { m_bFastDecodeCalled=true; decode(); } @@ -3435,11 +3265,15 @@ void MainWindow::fastSink(qint64 frames) m_fnameWE = m_config.save_directory ().absoluteFilePath (period_start.toString ("yyMMdd_hhmmss")); if(m_saveAll or m_bAltV or (m_bDecoded and m_saveDecoded) or (m_mode!="MSK144")) { m_bAltV=false; - // the following is potential a threading hazard - not a good - // idea to pass pointer to be processed in another thread - m_saveWAVWatcher.setFuture (QtConcurrent::run (std::bind (&MainWindow::save_wave_file, - this, m_fnameWE, &dec_data.d2[0], int(m_TRperiod*12000.0), m_config.my_callsign(), - m_config.my_grid(), m_mode, m_nSubMode, m_freqNominal, m_hisCall, m_hisGrid))); + double dgrd_value = 0.0; + QString dgrd; + if(m_astroWidget) { + dgrd_value = m_astroWidget->getDgrd(); + dgrd = QString("%1").arg(dgrd_value, 0, 'f', 1); + } else { + dgrd = "NoVal"; + } + save_wave_file (m_fnameWE, int (m_TRperiod * 12000.0), m_operatingFrequency.rx (), dgrd); } if(m_mode!="MSK144") { killFileTimer.start (int(750.0*m_TRperiod)); //Kill 3/4 period from now @@ -3451,62 +3285,32 @@ void MainWindow::fastSink(qint64 frames) m_fCPUmskrtd=0.9*m_fCPUmskrtd + 0.1*tsec; } -void MainWindow::showSoundInError(const QString& errorMsg) -{ - if (m_splash && m_splash->isVisible ()) m_splash->hide (); - MessageBox::critical_message (this, tr ("Error in Sound Input"), errorMsg); -} - -void MainWindow::showSoundOutError(const QString& errorMsg) -{ - if (m_splash && m_splash->isVisible ()) m_splash->hide (); - MessageBox::critical_message (this, tr ("Error in Sound Output"), errorMsg); -} - -void MainWindow::showStatusMessage(const QString& statusMsg) -{ - statusBar()->showMessage(statusMsg, 5000); -} void MainWindow::showQSYMessage(QString message) { QString the_line = message; QString qCall = QString(Radio::base_callsign(m_config.my_callsign ())); QString qDXCall = QString(Radio::base_callsign(ui->dxCallEntry->text())); - if(the_line.mid(22).contains(QString("."))) { + if(QSYMessageParser::mightContainMessage(the_line.mid(22))) { if(!(the_line.contains("OKQSY") || the_line.contains("NOQSY"))) { QStringList bhList = the_line.split(" ",SkipEmptyParts); - QString the_message = ""; - QString the_call = ""; - for (const QString &element : bhList) { - if(element.contains(QString("."))) { - the_message = element.mid(element.indexOf("." ) + 1); - the_call = element.mid(0,element.indexOf("." )); - if(the_message.length() > 0) { - QString finalMatch = ""; - QRegularExpression re1("[A-Z479][V0123456789ABCDEFGHIJKLRW][0-9]{3}"); - QRegularExpressionMatch match = re1.match(the_message); - if(match.hasMatch()) { - finalMatch = match.captured(); - if(the_call == qCall && ui->actionEnable_QSY_Popups->isChecked()) { - if(m_QSYMessageWidget) m_QSYMessageWidget->write_settings(); - m_QSYMessageWidget.reset (new QSYMessage(finalMatch, qCall, m_settings, &m_config)); - - //connect to signal finish - connect (this, &MainWindow::finished, &QSYMessage::close); - - //connect to signal from QSYMessage - connect (m_QSYMessageWidget.data (), &QSYMessage::sendReply, this, &MainWindow::reply_tx5,static_cast<Qt::ConnectionType>(Qt::UniqueConnection)); - m_QSYMessageWidget->setWindowFlags(m_QSYMessageWidget->windowFlags() | Qt::WindowStaysOnTopHint); - m_QSYMessageWidget->show(); - m_QSYMessageWidget->raise(); - m_QSYMessageWidget->activateWindow(); - } - if(m_qsymonitorWidget && finalMatch.mid(0,1) !='Z') m_qsymonitorWidget->getQSYData(QString(bhList[0]) + " " + the_call + " " + finalMatch); - if (m_config.alert_Enabled() && m_config.alert_QSYmessage() && (the_line.contains(qCall) or the_line.contains(qDXCall))) alertQSYmessage(); - } - } + QSYMessageParser::LineResult const qsy = QSYMessageParser::decodeLine (the_line, m_config.region ()); + if (qsy.message) { + QString const the_call = qsy.call; + QString const finalMatch = qsy.payload; + if(the_call == qCall && ui->actionEnable_QSY_Popups->isChecked()) { + if(m_QSYMessageWidget) m_QSYMessageWidget->write_settings(); + m_QSYMessageWidget.reset (new QSYMessage(finalMatch, qCall, m_settings, &m_config)); + + connect (this, &MainWindow::finished, m_QSYMessageWidget.data (), &QSYMessage::close); + connect (m_QSYMessageWidget.data (), &QSYMessage::sendReply, this, &MainWindow::reply_tx5,static_cast<Qt::ConnectionType>(Qt::UniqueConnection)); + m_QSYMessageWidget->setWindowFlags(m_QSYMessageWidget->windowFlags() | Qt::WindowStaysOnTopHint); + m_QSYMessageWidget->show(); + m_QSYMessageWidget->raise(); + m_QSYMessageWidget->activateWindow(); } + if(m_qsymonitorWidget && qsy.message.type == QSYMessageParser::Type::Frequency) m_qsymonitorWidget->getQSYData(QString(bhList[0]) + " " + the_call + " " + finalMatch); + if (m_config.alert_Enabled() && m_config.alert_QSYmessage() && (the_line.contains(qCall) or the_line.contains(qDXCall))) alertQSYmessage(); } } else if (((the_line.mid(22).contains(qDXCall + QString(".") + "OKQSY") || the_line.mid(22).contains(qDXCall +QString(".") + "NOQSY"))) && ui->actionEnable_QSY_Popups->isChecked()) { @@ -3521,8 +3325,7 @@ void MainWindow::showQSYMessage(QString message) if(m_QSYMessageWidget) m_QSYMessageWidget->write_settings(); m_QSYMessageWidget.reset (new QSYMessage(qNewMessage, qDXCall, m_settings, &m_config)); - //connect to signal finish - connect (this, &MainWindow::finished, &QSYMessage::close); + connect (this, &MainWindow::finished, m_QSYMessageWidget.data (), &QSYMessage::close); m_QSYMessageWidget->show(); m_QSYMessageWidget->raise(); m_QSYMessageWidget->activateWindow(); @@ -3542,6 +3345,7 @@ void MainWindow::on_actionSettings_triggered() // Setup Dialog (Settin SpecOp nContest0=m_specOp; auto psk_on = m_config.spot_to_psk_reporter (); if (QDialog::Accepted == m_config.exec ()) { + cancelPendingFt8Decode ("settings changed"); checkMSK144ContestType(); if (m_config.my_callsign () != callsign) { m_baseCall = Radio::base_callsign (m_config.my_callsign ()); @@ -3563,11 +3367,23 @@ void MainWindow::on_actionSettings_triggered() // Setup Dialog (Settin m_psk_Reporter.sendReport (true); } - m_tci_audio = (m_config.tci_audio() && m_config.is_tci()); // update m_tci_audio + bool const next_tci_audio = m_config.tci_audio () && m_config.is_tci (); + bool const receive_source_changed = next_tci_audio != m_tci_audio; bool was_monitoring = m_monitoring; - if (m_monitoring && (m_config.restart_tci () or !m_tci_audio)) on_monitorButton_clicked (false); + if (m_monitoring && (receive_source_changed || m_config.restart_tci () + || !next_tci_audio)) + on_monitorButton_clicked (false); + if (receive_source_changed && !m_tci_audio) Q_EMIT stopAudioInputStream (); + if (receive_source_changed && next_tci_audio) + Q_EMIT m_config.transceiver_audio (false); + m_tci_audio = next_tci_audio; + if (receive_source_changed) + { + m_receiveConsumer.invalidate (); + m_receiveQueue.clear (); + } if (!m_tci_audio) { - if(m_config.restart_audio_input () && !m_config.audio_input_device ().isNull ()) { + if(receive_source_changed || m_config.restart_audio_input ()) { Q_EMIT startAudioInputStream (m_config.audio_input_device () , m_rx_audio_buffer_frames , m_detector, m_downSampleFactor @@ -3580,7 +3396,11 @@ void MainWindow::on_actionSettings_triggered() // Setup Dialog (Settin , m_tx_audio_buffer_frames); } } - if (was_monitoring && (m_config.restart_tci () or !m_tci_audio) && !m_monitoring && !m_transmitting && g_iptt!=1) { + if (!was_monitoring && receive_source_changed && !m_tci_audio) + Q_EMIT suspendAudioInputStream (); + if (was_monitoring && (receive_source_changed || m_config.restart_tci () + || !m_tci_audio) + && !m_monitoring && !m_transmitting && g_iptt!=1) { if(m_mode=="MSK144") { if (m_tci_audio) { if (ui->bandComboBox->currentText()!="OOB") { @@ -3620,10 +3440,10 @@ void MainWindow::on_actionSettings_triggered() // Setup Dialog (Settin } m_config.transceiver_online (); + sync_tci_tx_volume (true); if(!m_bFastMode) setXIT (ui->TxFreqSpinBox->value ()); if ((m_config.single_decode () && !m_mode.startsWith ("FST4")) || m_mode=="JT4") { - ui->lh_decodes_title_label->setText(tr ("Single-Period Decodes")); - ui->rh_decodes_title_label->setText(tr ("Average Decodes")); + setDecodeTitles(tr ("Single-Period Decodes"), tr ("Average Decodes")); } update_watchdog_label (); @@ -3641,6 +3461,8 @@ void MainWindow::on_actionSettings_triggered() // Setup Dialog (Settin } m_specOp=m_config.special_op_id(); if(m_specOp!=nContest0) { + m_q65PileupCopiedLastRxCall.clear(); + m_q65PileupCopiedCallers.clear(); ui->tx1->setEnabled(true); ui->txb1->setEnabled(true); set_mode(m_mode); @@ -3677,32 +3499,6 @@ void MainWindow::on_actionSettings_triggered() // Setup Dialog (Settin } } -void MainWindow::on_monitorButton_clicked (bool checked) -{ - if (!m_transmitting) { - auto prior = m_monitoring; - monitor (checked); - if (checked && !prior) { - if (m_config.monitor_last_used () && m_mode!="Echo") { - // put rig back where it was when last in control - setRig (m_lastMonitoredFrequency); - setXIT (ui->TxFreqSpinBox->value ()); - } - // ensure FreqCal triggers - if(m_mode=="FST4W") { - on_sbFST4W_RxFreq_valueChanged(ui->sbFST4W_RxFreq->value()); - } else { - on_RxFreqSpinBox_valueChanged (ui->RxFreqSpinBox->value ()); - } - } - //Get Configuration in/out of strict split and mode checking - m_config.sync_transceiver (true, checked); - } else { - ui->monitorButton->setChecked (false); // disallow - } - if(m_mode=="Echo") m_echoRunning=false; - check_button_color(); -} void MainWindow::monitor (bool state) { @@ -3710,12 +3506,18 @@ void MainWindow::monitor (bool state) if (state) { m_diskData = false; // no longer reading WAV files if (!m_monitoring) { - float t_rxdelay=0.001*(QDateTime::currentMSecsSinceEpoch() - m_msEchoTxStart); - int ms=int(1000*(m_tEcho-t_rxdelay)); + int ms=0; + if(m_mode=="Echo") { + float t_rxdelay=0.001*(QDateTime::currentMSecsSinceEpoch() - m_msEchoTxStart); + if(t_rxdelay > 2.3 && t_rxdelay < 2.8 && m_tEcho > t_rxdelay) ms=int(1000*(m_tEcho-t_rxdelay)); + } if (m_tci_audio) { if (ui->bandComboBox->currentText()!="OOB") { if(ms>=10) { - QTimer::singleShot (ms, [=] {Q_EMIT m_config.transceiver_audio(true);}); + QTimer::singleShot (ms, this, [this] { + if (m_monitoring && m_tci_audio) + Q_EMIT m_config.transceiver_audio (true); + }); } else { Q_EMIT m_config.transceiver_audio(true); } @@ -3724,7 +3526,9 @@ void MainWindow::monitor (bool state) } } else { if(ms>=10) { - QTimer::singleShot (ms, [=] {resumeAudioInputStream();}); + QTimer::singleShot (ms, this, [this] { + if (m_monitoring && !m_tci_audio) Q_EMIT resumeAudioInputStream (); + }); } else { Q_EMIT resumeAudioInputStream (); } @@ -3742,6 +3546,7 @@ void MainWindow::monitor (bool state) } } m_monitoring = state; + if (!state) cancelPendingFt8Decode ("monitoring stopped"); check_button_color(); } @@ -3750,53 +3555,6 @@ void MainWindow::on_actionAbout_triggered() //Display "About" CAboutDlg {this}.exec (); } -void MainWindow::on_autoButton_clicked (bool checked) -{ - if (ui->DX_Call_Button->isChecked() && m_specOp==SpecOp::HOUND && m_config.superFox() && !m_bDoubleClicked) return; // for Wait & Call - m_config.transceiver_tune (false); // reset rig tuning - if (checked && ui->tuneButton->isChecked() && !(m_mode=="WSPR" || m_mode=="FST4W")) return; // not allowed while tuning - stopWRTimer.stop(); // stop any Wait & Reply timeout - if (!checked && ui->DX_Call_Button->isChecked()) { - stopWCTimer.stop(); // stop any Wait & Call timeout - ui->DX_Call_Button->click (); // disable Wait & Call - no_wait_and_call = false; // reset Wait & Call - } - m_specOp=m_config.special_op_id(); - ui->pbBandHopping->setChecked(false); // disable band hopping when Tx is enabled - if (checked) { - m_auto = checked; - QTimer::singleShot (3000, [=] {pounce = false;}); // ensure to select only CQ messages - } else { - pounce = false; - m_auto = false; - m_bCallingCQ = false; - ui->autoButton->setChecked(false); // ensure autoButton is unchecked - filtered = false; - ignored = false; - m_muted = false; - Dpoints=0; // reset points - maxDPoints=0; // reset points - dBpoints=-28; // reset points - dBpoints2=99; // reset points - maxdBPoints=-28; // reset points - mindBPoints=99; // reset points - } - m_maxPoints=-1; - if (checked && ui->respondComboBox->isVisible() && ui->respondComboBox->currentText() != "CQ: None" - && CALLING == m_QSOProgress) { - m_bAutoReply = false; // ready for next - m_bCallingCQ = true; // allows tail-enders to be picked up - } - statusUpdate (); - m_bEchoTxOK=false; - if(m_mode=="Echo" and m_auto) { - m_nclearave=1; - echocom_.nsum=0; - } - m_tAutoOn=QDateTime::currentMSecsSinceEpoch()/1000; - if(m_mode=="Echo") m_echoRunning=false; - check_button_color(); -} void MainWindow::on_sbTxPercent_valueChanged (int n) { @@ -3814,10 +3572,9 @@ void MainWindow::keyPressEvent (QKeyEvent * e) if(SpecOp::FOX == m_specOp) { switch (e->key()) { case Qt::Key_Return: - doubleClickOnCall2(Qt::KeyboardModifier(Qt::ShiftModifier + Qt::ControlModifier + Qt::AltModifier)); - return; case Qt::Key_Enter: - doubleClickOnCall2(Qt::KeyboardModifier(Qt::ShiftModifier + Qt::ControlModifier + Qt::AltModifier)); + doubleClickOnCall2(ui->decodedTextBrowser->document()->firstBlock().text(), QString {}, + Qt::KeyboardModifier(Qt::ShiftModifier + Qt::ControlModifier + Qt::AltModifier)); return; case Qt::Key_Backspace: qDebug() << "Key Backspace"; @@ -3830,20 +3587,10 @@ void MainWindow::keyPressEvent (QKeyEvent * e) } QMainWindow::keyPressEvent (e); } - - // Why shall RETURN switch Tx on when in Hound mode? Makes little sense and confuses many OMs! -// if(SpecOp::HOUND == m_specOp) { -// switch (e->key()) { -// case Qt::Key_Return: -// auto_tx_mode(true); -// return; -// case Qt::Key_Enter: -// auto_tx_mode(true); -// return; -// } -// QMainWindow::keyPressEvent (e); -// } - + if(m_mode=="JTTY") { + bool handled = jtty_key_struck(e); + if(handled) return; + } int n; bool bAltF1F6=m_config.alternate_bindings(); switch(e->key()) @@ -3862,14 +3609,12 @@ void MainWindow::keyPressEvent (QKeyEvent * e) return; case Qt::Key_C: if(e->modifiers() & Qt::AltModifier) { - int n=ui->respondComboBox->currentIndex()+1; - if(n>2) n=0; - ui->respondComboBox->setCurrentIndex(n); + cycleRespondMode(); } return; case Qt::Key_D: if(m_mode != "WSPR" && e->modifiers() & Qt::ShiftModifier) { - if(!m_decoderBusy) { + if(!decoderBusy ()) { dec_data.params.newdat=0; dec_data.params.nagain=0; decode(); @@ -3925,9 +3670,7 @@ void MainWindow::keyPressEvent (QKeyEvent * e) } case Qt::Key_F6: if(bAltF1F6) { - int n=ui->respondComboBox->currentIndex()+1; - if(n>2) n=0; - ui->respondComboBox->setCurrentIndex(n); + cycleRespondMode(); } else { if(e->modifiers() & Qt::ShiftModifier) { on_actionDecode_remaining_files_in_directory_triggered(); @@ -3938,8 +3681,7 @@ void MainWindow::keyPressEvent (QKeyEvent * e) return; case Qt::Key_F11: if((e->modifiers() & Qt::ControlModifier) and (e->modifiers() & Qt::ShiftModifier)) { - m_bandEdited = true; - band_changed(m_freqNominal-1000); + requestBandChange (m_operatingFrequency.rx () - 1000, FrequencyRequestOrigin::User); } else { n=11; if(e->modifiers() & Qt::ControlModifier) n+=100; @@ -3954,8 +3696,7 @@ void MainWindow::keyPressEvent (QKeyEvent * e) return; case Qt::Key_F12: if((e->modifiers() & Qt::ControlModifier) and (e->modifiers() & Qt::ShiftModifier)) { - m_bandEdited = true; - band_changed(m_freqNominal+1000); + requestBandChange (m_operatingFrequency.rx () + 1000, FrequencyRequestOrigin::User); } else { n=12; if(e->modifiers() & Qt::ControlModifier) n+=100; @@ -3985,7 +3726,7 @@ void MainWindow::keyPressEvent (QKeyEvent * e) break; case Qt::Key_F: if(e->modifiers() & Qt::ControlModifier) { - if(ui->tabWidget->currentIndex()==0) { + if(ui->tabWidget->currentIndex()==standard_messages_tab_index) { ui->tx5->clearEditText(); ui->tx5->setFocus(); } @@ -4044,11 +3785,11 @@ void MainWindow::keyPressEvent (QKeyEvent * e) return; } if(e->modifiers() & Qt::AltModifier) { - if(!m_send_RR73) on_txrb4_doubleClicked(); - return; + set_rr73_tx4 (true); + return; } if(e->modifiers() & Qt::ControlModifier) { - if(m_send_RR73) on_txrb4_doubleClicked(); + set_rr73_tx4 (false); return; } break; @@ -4058,11 +3799,19 @@ void MainWindow::keyPressEvent (QKeyEvent * e) //foxTest(); return; } + break; + case Qt::Key_Z: + if(e->modifiers() & Qt::AltModifier) { + clearHungDecoderStatus("Alt+Z"); + return; + } + break; } QMainWindow::keyPressEvent (e); } + void MainWindow::handleVerifyMsg(int status, QDateTime ts, QString callsign, QString code, unsigned int hz, QString const &response) { (void)status; @@ -4071,9 +3820,9 @@ void MainWindow::handleVerifyMsg(int status, QDateTime ts, QString callsign, QSt QString msg = FoxVerifier::formatDecodeMessage(ts, callsign, hz, response); if (msg.length() > 0) { // Hound label - if ((ui->labDXped->text().contains("Hound") && msg.contains(" verified"))) { - verified = true; - ui->labDXped->setStyleSheet("QLabel {background-color: #00ff00; color: black;}"); + if (isHoundOperation () && msg.contains(" verified")) { + m_houndVerified = true; + updateHoundVerificationStyle (); } ui->decodedTextBrowser->displayDecodedText(DecodedText{msg}, m_config.my_callsign(), m_mode, m_config.DXCC(), m_logBook, m_currentBand, m_config.ppfx(), false, false, 0.0, false, -99, "", true); @@ -4083,16 +3832,6 @@ void MainWindow::handleVerifyMsg(int status, QDateTime ts, QString callsign, QSt LOG_INFO(QString("FoxVerifier response for [%1]: - [%2]").arg(callsign).arg(response).toStdString()); } -QString MainWindow::userAgent() { - // see User-Agent format definition https://www.rfc-editor.org/rfc/rfc9110#name-user-agent - // - QString platform = "(" + QSysInfo::prettyProductName()+"; "+QSysInfo::productType() + " " + QSysInfo::productVersion() + "; " + - QSysInfo::currentCpuArchitecture() + "; " + - QString("rv:%1").arg(QSysInfo::kernelVersion()) + ")"; - QString userAgent = QString{"WSJT-X/" + version() + "_" + m_revision}.simplified() + " " +platform; - return userAgent; - } - void MainWindow::bumpFqso(int n) //bumpFqso() { int i; @@ -4117,12 +3856,14 @@ void MainWindow::bumpFqso(int n) //bumpFqso() void MainWindow::displayDialFrequency () { if (ui->actionUse_Dark_Style->isChecked()) ui->bandComboBox->setStyleSheet("QLineEdit {background-color: #31363b}"); // initialize dark style at startup - Frequency dial_frequency {m_rigState.ptt () && m_rigState.split () ? - m_rigState.tx_frequency () : m_rigState.frequency ()}; + Frequency dial_frequency {m_rigState.ptt () ? + (m_rigState.split () ? m_operatingFrequency.correctedTx (m_astroCorrection.tx) + : m_operatingFrequency.tx ()) : + m_operatingFrequency.correctedRx (m_astroCorrection.rx)}; // lookup band auto const& band_name = m_config.bands ()->find (dial_frequency); - if (m_lastBand != band_name or m_freqNominalPeriod != m_freqNominal) + if (m_lastBand != band_name or m_freqNominalPeriod != m_operatingFrequency.rx ()) { // only change this when necessary as we get called a lot and it // would trash any user input to the band combo box line edit @@ -4130,13 +3871,13 @@ void MainWindow::displayDialFrequency () ui->bandComboBox->setCurrentText (band_name.size () ? band_name : m_config.bands ()->oob ()); m_wideGraph->setRxBand (band_name); m_lastBand = band_name; - band_changed(dial_frequency); + band_changed (dial_frequency); } // prevent wrong frequencies for all.txt, PSK Reporter and highlighting for late decodes after band changes m_displayBand = false; no_decodes_to_UDP = true; // prevent wrong frequencies for devices connected via UDP - QTimer::singleShot ((int(600.0*m_TRperiod)), [=] { - m_freqNominalPeriod = m_freqNominal; + QTimer::singleShot ((int(600.0*m_TRperiod)), this, [=] { + m_freqNominalPeriod = m_operatingFrequency.rx (); m_currentBandPeriod = m_currentBand; m_displayBand = true; no_decodes_to_UDP = false; // prevent wrong frequencies for devices connected via UDP @@ -4188,13 +3929,26 @@ void MainWindow::stopWCTimeout() void MainWindow::statusChanged() { + auto const prior_spec_op = m_specOp; m_specOp=m_config.special_op_id(); // update m_specOp + if (m_specOp != prior_spec_op) { + m_q65PileupCopiedLastRxCall.clear(); + m_q65PileupCopiedCallers.clear(); + } if (m_specOp==SpecOp::Q65_PILEUP && m_mode != "Q65") on_actionQ65_triggered(); - QTimer::singleShot (50, [=] { // only allow Wait & Call where it is appropriate - if((m_mode.startsWith("JT") or m_mode=="WSPR" or m_mode=="Echo" or m_mode=="FST4W" - or (m_specOp!=SpecOp::NONE and m_specOp!=SpecOp::HOUND) - or !ui->cbAutoSeq->isChecked() or m_hisCall=="") && ui->DX_Call_Button->isChecked()) - ui->DX_Call_Button->click (); + QTimer::singleShot (50, this, [=] { + WaitFeatureContext const waitContext { + m_mode, + m_specOp, + m_config.Wait_features_enabled(), + ui->cbAutoSeq->isChecked(), + !m_hisCall.isEmpty(), + m_config.NCCC_Sprint() + }; + if (ui->DX_Call_Button->isChecked() + && !wait_and_call_arming_eligible (waitContext)) { + ui->DX_Call_Button->click (); + } }); statusUpdate (); QFile f {m_config.temp_dir ().absoluteFilePath ("wsjtx_status.txt")}; @@ -4202,7 +3956,7 @@ void MainWindow::statusChanged() QTextStream out(&f); QString tmpGrid = m_hisGrid; if (!tmpGrid.size ()) tmpGrid="n/a"; // Not Available - out << qSetRealNumberPrecision (12) << (m_freqNominal / 1.e6) + out << qSetRealNumberPrecision (12) << (m_operatingFrequency.rx () / 1.e6) << ";" << m_mode << ";" << m_hisCall << ";" << ui->rptSpinBox->value() << ";" << m_mode << ";" << tmpGrid #if QT_VERSION >= QT_VERSION_CHECK (5, 15, 0) @@ -4220,14 +3974,7 @@ void MainWindow::statusChanged() } on_dxGridEntry_textChanged(m_hisGrid); if (m_specOp!=SpecOp::HOUND) { - ui->txb2->setEnabled(true); - ui->txrb2->setEnabled(true); - ui->txb4->setEnabled(true); - ui->txrb4->setEnabled(true); - ui->txb5->setEnabled(true); - ui->txrb5->setEnabled(true); - ui->txb6->setEnabled(true); - ui->txrb6->setEnabled(true); + setTxButtonsEnabled(true); ui->houndButton->setChecked(false); } if (m_specOp==SpecOp::FOX) { @@ -4247,15 +3994,12 @@ void MainWindow::statusChanged() } if (m_mode=="JT4" or m_mode=="Q65" or m_mode=="JT65") { if (ui->actionInclude_averaging->isVisible() && ui->actionInclude_averaging->isChecked()) { - ui->lh_decodes_title_label->setText(tr ("Single-Period Decodes")); - ui->rh_decodes_title_label->setText(tr ("Average Decodes")); + setDecodeTitles(tr ("Single-Period Decodes"), tr ("Average Decodes")); } else { if (m_config.enable_VHF_features()) { - ui->lh_decodes_title_label->setText(tr ("Band Activity")); - ui->rh_decodes_title_label->setText(tr ("Decodes containing My Call")); + setDecodeTitles(tr ("Band Activity"), tr ("Decodes containing My Call")); } else { - ui->lh_decodes_title_label->setText(tr ("Band Activity")); - ui->rh_decodes_title_label->setText(tr ("Rx Frequency")); + setDecodeTitles(tr ("Band Activity"), tr ("Rx Frequency")); } } } @@ -4315,13 +4059,108 @@ void MainWindow::statusChanged() bool MainWindow::eventFilter (QObject * object, QEvent * event) { + if (!m_event_filter_ready) + { + return QObject::eventFilter (object, event); + } + + if ((object == ui->QSO_controls_widget + || (m_modeCheckboxRow && object == m_modeCheckboxRow->parentWidget ())) + && (event->type () == QEvent::Resize || event->type () == QEvent::LayoutRequest)) + QTimer::singleShot (0, this, &MainWindow::updateModeControlsLayout); + switch (event->type()) { + case QEvent::FocusIn: + { + auto const focus_reason = static_cast<QFocusEvent *> (event)->reason (); + if (focus_reason == Qt::MouseFocusReason) + { + m_keyboard_focus_active = false; + } + else if (focus_reason == Qt::TabFocusReason + || focus_reason == Qt::BacktabFocusReason + || focus_reason == Qt::ShortcutFocusReason) + { + m_keyboard_focus_active = true; + } + + auto *widget = qobject_cast<QWidget *> (object); + auto const indicator_widgets = focusIndicatorWidgets (); + auto const is_focus_indicator_target = std::find (indicator_widgets.cbegin (), indicator_widgets.cend (), widget) + != indicator_widgets.cend (); + if (is_focus_indicator_target) + { + if (m_keyboard_focus_active) + { + showMainWindowFocusIndicator (widget); + } + else + { + hideMainWindowFocusIndicators (); + } + } + break; + } + + case QEvent::FocusOut: + if (object == ui->tabWidget->tabBar ()) + { + m_message_selector_focus_frame->hide (); + } + if (m_main_window_focus_frame->widget () == object) + { + m_main_window_focus_frame->hide (); + m_main_window_focus_frame->setWidget (nullptr); + } + break; + case QEvent::KeyPress: - // fall through + { + m_keyboard_focus_active = true; + auto *widget = qobject_cast<QWidget *> (object); + auto const indicator_widgets = focusIndicatorWidgets (); + if (std::find (indicator_widgets.cbegin (), indicator_widgets.cend (), widget) + != indicator_widgets.cend ()) + { + showMainWindowFocusIndicator (widget); + } + + auto const key_event = static_cast<QKeyEvent *> (event); + auto const handled = switchMainWindowTab (key_event) || switchTxNextMessage (key_event); + tx_watchdog (false); + if (handled) return true; + break; + } + + case QEvent::EnabledChange: + { + auto const buttons = txNextButtons (); + if (std::find (buttons.cbegin (), buttons.cend (), qobject_cast<QRadioButton *> (object)) + != buttons.cend ()) + { + QTimer::singleShot (0, this, &MainWindow::updateTxNextFocusPolicies); + } + break; + } + case QEvent::MouseButtonPress: + m_keyboard_focus_active = false; + hideMainWindowFocusIndicators (); // reset the Tx watchdog tx_watchdog (false); + if (object == ui->txFirstCheckBox + && static_cast<QMouseEvent *> (event)->button () == Qt::RightButton) + { + if (m_tx_first_mode_enabled) + { + // Disabling a focused widget advances focus to the next widget. + ui->txFirstCheckBox->clearFocus (); + m_tx_first_user_enabled = !m_tx_first_user_enabled; + updateTxFirstEnabledState (); + } + return true; + } break; case QEvent::ChildAdded: @@ -4346,6 +4185,8 @@ void MainWindow::createStatusBar() //createStatusBar tx_status_label.setStyleSheet ("QLabel{color: #000000; background-color: #00ff00}"); tx_status_label.setFrameStyle (QFrame::Panel | QFrame::Sunken); statusBar()->addWidget (&tx_status_label); + connect (&m_config, &Configuration::tx_inhibit_status_changed, + this, &MainWindow::handleTxInhibitStatus); config_label.setAlignment (Qt::AlignHCenter); config_label.setMinimumSize (QSize {80, 18}); @@ -4378,6 +4219,89 @@ void MainWindow::createStatusBar() //createStatusBar statusBar ()->addPermanentWidget (&watchdog_label); update_watchdog_label (); + + statusBar ()->setAccessibleName (tr ("Application status")); + statusBar ()->setAccessibleDescription (tr ("Current WSJT-X status messages and operating indicators.")); + + tx_status_label.setAccessibleName (tr ("Transmit status")); + config_label.setAccessibleName (tr ("Configuration")); + mode_label.setAccessibleName (tr ("Mode")); + ndecodes_label.setAccessibleName (tr ("Decode count")); + last_tx_label.setAccessibleName (tr ("Last transmitted message")); + band_hopping_label.setAccessibleName (tr ("Power and SWR status")); + progressBar.setAccessibleName (tr ("Decode progress")); + progressBar.setAccessibleDescription (tr ("Progress for the current decode operation.")); + watchdog_label.setAccessibleName (tr ("Transmit watchdog")); +} + +void MainWindow::handleTxInhibitStatus (bool supported, bool inhibited, + QString const& holder, quint32 hold_rx, + quint32 release_rx, quint32 expiries, + quint32 invalid) +{ + m_tx_inhibited = inhibited; + + if (!inhibited) + { + tx_status_label.setToolTip ({}); + tx_status_label.setAccessibleDescription ({}); + } + else + { + auto const description = holder.isEmpty () + ? tr ("TX is inhibited by an external interlock controller.") + : tr ("TX is inhibited by %1.").arg (holder); + tx_status_label.setToolTip (description); + tx_status_label.setAccessibleDescription (description); + } + + if (inhibited) startTxAudioAfterPttDelay (); + if (m_messageClient) + { + m_messageClient->inhibit_status (supported, inhibited, holder, hold_rx, + release_rx, expiries, invalid); + } +} + +void MainWindow::startTxAudioAfterPttDelay () +{ + if (!m_tx_when_ready || !g_iptt) return; + + auto delay_ms = static_cast<int> (1000 * m_config.txDelay ()); + if (m_mode == "FT4") delay_ms = 20; + ptt1Timer.start (delay_ms); + m_tx_when_ready = false; +} + +void MainWindow::show_generated_message_error () +{ + m_generated_message_error = true; + if (!m_tx_watchdog) update_generated_message_error (); +} + +void MainWindow::clear_generated_message_error () +{ + if (!m_generated_message_error) return; + + m_generated_message_error = false; + tx_status_label.setToolTip (QString {}); + tx_status_label.setAccessibleDescription (QString {}); + if (!m_transmitting && !m_tx_watchdog) { + tx_status_label.setStyleSheet (""); + tx_status_label.setText (""); + } +} + +void MainWindow::update_generated_message_error () +{ + auto const details = tr ("The selected transmit message cannot be encoded. " + "Enable Tx has been turned off. Edit the selected " + "message or check station settings before trying again."); + tx_status_label.setStyleSheet ( + "QLabel{color: #000000; background-color: #ffff00}"); + tx_status_label.setText (tr ("Tx message cannot be encoded; Enable Tx is off")); + tx_status_label.setToolTip (details); + tx_status_label.setAccessibleDescription (details); } void MainWindow::setup_status_bar (bool vhf) @@ -4400,6 +4324,8 @@ void MainWindow::setup_status_bar (bool vhf) mode_label.setStyleSheet ("QLabel{color: #000000; background-color: #66ff66}"); } else if ("Q65" == m_mode) { mode_label.setStyleSheet ("QLabel{color: #000000; background-color: #99ff33}"); + } else if ("JTTY" == m_mode) { + mode_label.setStyleSheet ("QLabel{color: #000000; background-color: #9999ff}"); } else if ("MSK144" == m_mode) { mode_label.setStyleSheet ("QLabel{color: #000000; background-color: #ff6666}"); } else if ("FT4" == m_mode) { @@ -4429,53 +4355,42 @@ void MainWindow::setup_status_bar (bool vhf) } } -bool MainWindow::subProcessFailed (QProcess * process, int exit_code, QProcess::ExitStatus status) -{ - if (m_valid && (exit_code || QProcess::NormalExit != status)) - { - QStringList arguments; - for (auto argument: process->arguments ()) - { - if (argument.contains (' ')) argument = '"' + argument + '"'; - arguments << argument; - } - if (m_splash && m_splash->isVisible ()) m_splash->hide (); - MessageBox::critical_message (this, tr ("Subprocess Error") - , tr ("Subprocess failed with exit code %1") - .arg (exit_code) - , tr ("Running: %1\n%2") - .arg (process->program () + ' ' + arguments.join (' ')) - .arg (QString {process->readAllStandardError()})); - return true; - } - return false; -} -void MainWindow::subProcessError (QProcess * process, QProcess::ProcessError) +void MainWindow::paintEvent (QPaintEvent * event) { - if (m_valid) + MultiGeometryWidget::paintEvent (event); + if (!m_startup_paint_reported) { - QStringList arguments; - for (auto argument: process->arguments ()) - { - if (argument.contains (' ')) argument = '"' + argument + '"'; - arguments << argument; - } - if (m_splash && m_splash->isVisible ()) m_splash->hide (); - MessageBox::critical_message (this, tr ("Subprocess error") - , tr ("Running: %1\n%2") - .arg (process->program () + ' ' + arguments.join (' ')) - .arg (process->errorString ())); - m_valid = false; // ensures exit if still constructing - QTimer::singleShot (0, this, SLOT (close ())); + m_startup_paint_reported = true; + PerformanceTrace::finish_run (m_startup_trace_run, "ui.first_paint"); } } void MainWindow::closeEvent(QCloseEvent * e) { + auto const active_run = PerformanceTrace::current_run (); + if (active_run == m_startup_trace_run) + { + auto const shutdown_run = PerformanceTrace::begin_run ("shutdown", "application_exit"); + PerformanceTrace::milestone (shutdown_run, "shutdown.requested"); + } + PerformanceTrace::Phase close {"window.close"}; + cancelPendingFt8Decode ("application closing"); + m_closing = true; + m_jt9ProcessPhase = Jt9ProcessPhase::Closing; + m_decoderShutdownTimer.stop (); + m_decoderTerminateTimer.stop (); + m_decoderKillTimer.stop (); + m_decoderStartTimer.stop (); m_valid = false; // suppresses subprocess errors - m_config.transceiver_offline (); - writeSettings (); + { + PerformanceTrace::Phase rig_shutdown {"rig.shutdown_request"}; + m_config.transceiver_offline (); + } + { + PerformanceTrace::Phase settings_write {"mainwindow.settings_write"}; + writeSettings (); + } if(m_astroWidget) m_astroWidget.reset (); if(m_QSYMessageCreatorWidget) { QCloseEvent closeEvent; @@ -4497,58 +4412,38 @@ void MainWindow::closeEvent(QCloseEvent * e) m_shortcuts.reset (); m_mouseCmnds.reset (); m_colorHighlighting.reset (); - if(m_mode!="MSK144" and m_mode!="FT8") killFile(); + if(m_mode!="MSK144" and m_mode!="FT8") killWaveFile(); float sw=0.0; int nw=400; int nh=100; int irow=-99; plotsave_(&sw,&nw,&nh,&irow); - to_jt9(m_ihsym,999,-1); //Tell jt9 to terminate - if (!proc_jt9.waitForFinished(1000)) proc_jt9.close(); + { + PerformanceTrace::Phase decoder_shutdown {"decoder.shutdown"}; + if (DecoderIpc::hasUsableSize (mem_jt9->size ()) + && mem_jt9->data ()) + { + auto * shared = reinterpret_cast<shared_dec_data_t *> (mem_jt9->data ()); + DecoderIpc::shutdown (*shared); + } + if (proc_jt9.state() != QProcess::NotRunning) { + if (!proc_jt9.waitForFinished(5000)) { + proc_jt9.terminate(); + if (!proc_jt9.waitForFinished(1000)) { + proc_jt9.kill(); + proc_jt9.waitForFinished(1000); + } + } + } + proc_jt9.close(); + } mem_jt9->detach(); Q_EMIT finished (); QMainWindow::closeEvent (e); + close.finish (); } -void MainWindow::on_stopButton_clicked() //stopButton -{ - ui->pbBandHopping->setChecked(false); // disable band hopping - monitor (false); - m_loopall=false; - if(m_bRefSpec) { - MessageBox::information_message (this, tr ("Reference spectrum saved")); - m_bRefSpec=false; - } - if (ui->DX_Call_Button->isChecked()) ui->DX_Call_Button->click (); - stopWRTimer.stop(); // Stop any Wait & Reply timeout - stopWCTimer.stop(); // Stop any Wait & Call timeout - no_wait_and_call = false; - m_specOp=m_config.special_op_id(); - if (ui->respondComboBox->isVisible() and ui->respondComboBox->currentIndex()!=0 and !m_diskData) { - Dpoints=0; // reset points - maxDPoints=0; // reset points - dBpoints=-28; // reset points - dBpoints2=99; // reset points - maxdBPoints=-28; // reset points - mindBPoints=99; // reset points - if (!(m_mode=="Q65" or m_mode=="JT65")) { - clearDX(); // clear dxCallEntry - ui->dxGridEntry->clear (); // clear dxGridEntry - if (!keepTx5) ui->tx5->setCurrentText(""); // clear tx5 - } - } - pounce = false; - ui->autoButton->setChecked(false); // ensure auoButton is unchecked - filtered = false; - ignored = false; - m_muted = false; - check_button_color(); -} -void MainWindow::on_pbBandHopping_clicked() -{ - if (m_auto) ui->pbBandHopping->setChecked(false); // don't allow band hopping when in QSO -} void MainWindow::on_actionRelease_Notes_triggered () { @@ -4585,32 +4480,14 @@ 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"}); } -void MainWindow::on_actionRecommended_Audio_Settings_triggered() -{ - auto const& message = tr("It is very important to avoid audio harmonics and distorted audio signals.\n" - "This is usually achieved by the following step-by-step approach:\n\n" - "1. Select 'Fake it' in the Settings/Radio menu as your 'Split mode'. If your\n" - " rig does not support this, select 'Rig'. But really try to avoid 'None'!\n\n" - "2. Set the transmission power of your transceiver to maximum.\n\n" - "3. Set the Pwr slider to the minimum and click on the 'Tune' button.\n\n" - "4. Observe the actual transmission power of your rig as well as ALC.\n\n" - "5. Carefully increase the Pwr slider until you have reached the\n" - " maximum transmit powe of your transceiver.\n\n" - "6. VERY IMPORTANT: Now reduce the Pwr slider until you reach approx. \n" - " 90% of your max. Tx power. ALC should be close to zero.\n\n" - "7. This is the maximum audio level permitted with your setup.\n" - " Always stay with the Pwr slider below this max. value.\n\n" - "If possible, check your transmission from time to time with a webSDR\n" - "to ensure the signal is clean and not distorted."); - QTimer::singleShot (0, [=] { // don't block guiUpdate - MessageBox::warning_message(this, tr ("<b>Recommended Audio Settings</b>"), message); }); -} - void MainWindow::on_actionOnline_User_Guide_triggered() //Display manual { - QDesktopServices::openUrl (QUrl {"https://wsjt.sourceforge.io/wsjtx-main_en.html"}); + QDesktopServices::openUrl (QUrl {"https://wsjtx.github.io/wsjtx/guide-full.html"}); + } + + //Display local copy of manual void MainWindow::on_actionLocal_User_Guide_triggered() { @@ -4678,19 +4555,12 @@ void MainWindow::on_actionSolve_FreqCal_triggered() void MainWindow::on_actionCopyright_Notice_triggered() { - auto const& message = tr("If you make fair use of any part of WSJT-X under terms of the GNU " - "General Public License, you must display the following copyright " - "notice prominently in your derivative work:\n\n" - "\"The algorithms, source code, look-and-feel of WSJT-X and related " - "programs, and protocol specifications for the modes FSK441, FST4, FT8, " - "JT4, JT6M, JT9, JT65, JTMS, QRA64, Q65, MSK144 are Copyright (C) " - "2001-2026 by one or more of the following authors: Joseph Taylor, " - "K1JT; Bill Somerville, G4WJS; Steven Franke, K9AN; Nico Palermo, " - "IV3NWV; Greg Beam, KI7MT; Michael Black, W9MDB; Edson Pereira, PY2SDR; " - "Philip Karn, KA9Q; Uwe Risse, DG2YCB; Brian Moran, N9ADG; Roger Rehr, " - "W3SZ; John Nelson, G4KLA; Charlie Suckling, DL3WDG; Terrell Deppe, " - "KJ5HST; and other members of the WSJT Development Group.\""); - MessageBox::warning_message(this, message); + MessageBox::warning_message (this, copyright_notice_text ()); +} + +void MainWindow::on_actionTrademark_Policy_triggered() +{ + QDesktopServices::openUrl (QUrl {"https://wsjtx.github.io/wsjtx/trademark.html"}); } // Implement the MultiGeometryWidget::change_layout() operation. @@ -4718,16 +4588,92 @@ void MainWindow::change_layout (std::size_t n) } } +void MainWindow::cycleRespondMode() +{ + ui->respondComboBox->setCurrentIndex ( + next_cyclic_index (ui->respondComboBox->currentIndex (), ui->respondComboBox->count ())); +} + +QString MainWindow::selectedTxMessage() const +{ + switch (m_ntx) { + case 1: return ui->tx1->text(); + case 2: return ui->tx2->text(); + case 3: return ui->tx3->text(); + case 4: return ui->tx4->text(); + case 5: return ui->tx5->currentText(); + case 6: return ui->tx6->text(); + default: return {}; + } +} + +AutoRespondPolicy MainWindow::autoRespondPolicy() const +{ + bool ok; + auto const value = ui->respondComboBox->currentData ().toInt (&ok); + if (!ok) return AutoRespondPolicy::None; + + switch (static_cast<AutoRespondPolicy> (value)) + { + case AutoRespondPolicy::None: + case AutoRespondPolicy::First: + case AutoRespondPolicy::MaxDistance: + case AutoRespondPolicy::MaxSignal: + case AutoRespondPolicy::MinSignal: + return static_cast<AutoRespondPolicy> (value); + } + return AutoRespondPolicy::None; +} + +bool MainWindow::pendingCqAutoRespondIntent() const +{ + return m_auto + && !m_diskData + && !m_tune + && SpecOp::FOX != m_specOp + && SpecOp::HOUND != m_specOp + && CALLING == m_QSOProgress + && ui->cbAutoSeq->isVisible() + && ui->cbAutoSeq->isEnabled() + && ui->cbAutoSeq->isChecked() + && ui->respondComboBox->isVisible() + && AutoRespondPolicy::None != autoRespondPolicy() + && selectedTxMessage().contains(cq_or_qrz_message_regexp); +} + void MainWindow::on_actionSWL_Mode_triggered (bool checked) { select_geometry (checked ? 1 : ui->cbMenus->isChecked () ? 0 : 2); } -// This allows the window to shrink by removing certain things -// and reducing space used by controls void MainWindow::trim_view (bool checked) { - int spacing = checked ? 1 : 6; + auto const spacing = checked ? 1 : 6; + std::array<QLayout *, 19> const compactLayouts {{ + ui->gridLayout_5, + ui->horizontalLayout_2, + ui->horizontalLayout_5, + ui->horizontalLayout_6, + ui->horizontalLayout_7, + ui->horizontalLayout_8, + ui->horizontalLayout_9, + ui->horizontalLayout_10, + ui->horizontalLayout_11, + ui->horizontalLayout_12, + ui->horizontalLayout_13, + ui->horizontalLayout_14, + ui->rh_decodes_widget->layout (), + ui->verticalLayout_2, + ui->verticalLayout_3, + ui->verticalLayout_5, + ui->verticalLayout_7, + ui->verticalLayout_8, + ui->tab->layout () + }}; + for (auto * layout : compactLayouts) layout->setSpacing (spacing); + ui->horizontalLayout_5->setSpacing (qMax (spacing, 4)); + if (!checked) ui->horizontalLayout_2->setSpacing (2); + if (checked) { statusBar ()->removeWidget (&auto_tx_label); } else { @@ -4739,25 +4685,6 @@ void MainWindow::trim_view (bool checked) } ui->lh_decodes_headings_label->setVisible(!checked); ui->rh_decodes_headings_label->setVisible(!checked); - ui->gridLayout_5->layout()->setSpacing(spacing); - ui->horizontalLayout_2->layout()->setSpacing(spacing); - ui->horizontalLayout_5->layout()->setSpacing(spacing); - ui->horizontalLayout_6->layout()->setSpacing(spacing); - ui->horizontalLayout_7->layout()->setSpacing(spacing); - ui->horizontalLayout_8->layout()->setSpacing(spacing); - ui->horizontalLayout_9->layout()->setSpacing(spacing); - ui->horizontalLayout_10->layout()->setSpacing(spacing); - ui->horizontalLayout_11->layout()->setSpacing(spacing); - ui->horizontalLayout_12->layout()->setSpacing(spacing); - ui->horizontalLayout_13->layout()->setSpacing(spacing); - ui->horizontalLayout_14->layout()->setSpacing(spacing); - ui->rh_decodes_widget->layout()->setSpacing(spacing); - ui->verticalLayout_2->layout()->setSpacing(spacing); - ui->verticalLayout_3->layout()->setSpacing(spacing); - ui->verticalLayout_5->layout()->setSpacing(spacing); - ui->verticalLayout_7->layout()->setSpacing(spacing); - ui->verticalLayout_8->layout()->setSpacing(spacing); - ui->tab->layout()->setSpacing(spacing); } void MainWindow::on_actionAstronomical_data_toggled (bool checked) @@ -4770,7 +4697,7 @@ void MainWindow::on_actionAstronomical_data_toggled (bool checked) connect (this, &MainWindow::finished, m_astroWidget.data (), &Astro::close); connect (m_astroWidget.data (), &Astro::tracking_update, [this] { m_astroCorrection = {}; - setRig (); + reapplyCurrentRigFrequencyCorrection (); setXIT (ui->TxFreqSpinBox->value ()); displayDialFrequency (); }); @@ -4779,7 +4706,7 @@ void MainWindow::on_actionAstronomical_data_toggled (bool checked) m_astroWidget->showNormal(); m_astroWidget->raise (); m_astroWidget->activateWindow (); - m_astroWidget->nominal_frequency (m_freqNominal, m_freqTxNominal); + m_astroWidget->nominal_frequency (m_operatingFrequency.rx (), m_operatingFrequency.tx ()); if (!programStart) m_astroWidget->setSkedFreq(m_skedFreq); } else { @@ -4789,10 +4716,15 @@ void MainWindow::on_actionAstronomical_data_toggled (bool checked) void MainWindow::skedFreq(double freqMHz) { - m_skedFreq=freqMHz; - m_bandEdited=true; Frequency f=qRound64(1000000.0*freqMHz); - band_changed(f); + if (requestBandChange (f, FrequencyRequestOrigin::User)) + { + m_skedFreq=freqMHz; + } + else if (m_astroWidget) + { + m_astroWidget->setSkedFreq (m_skedFreq); + } } void MainWindow::on_actionQSYMessage_Creator_triggered() @@ -4800,7 +4732,7 @@ void MainWindow::on_actionQSYMessage_Creator_triggered() if (!m_QSYMessageCreatorWidget) { m_QSYMessageCreatorWidget.reset (new QSYMessageCreator {m_settings, &m_config}); // hook up termination signal - connect (this, &MainWindow::finished, &QSYMessageCreator::close); + connect (this, &MainWindow::finished, m_QSYMessageCreatorWidget.data (), &QSYMessageCreator::close); //connect to signal from QSYMessageCreator connect (m_QSYMessageCreatorWidget.data (), &QSYMessageCreator::sendMessage, this, &MainWindow::update_tx5); connect (m_QSYMessageCreatorWidget.data (), &QSYMessageCreator::sendQSYMessageCreatorStatus, this, &MainWindow::setQSYMessageCreatorStatus); @@ -4819,7 +4751,7 @@ void MainWindow::on_actionQSY_Monitor_triggered() if (!m_qsymonitorWidget) { m_qsymonitorWidget.reset (new QSYMonitor {m_settings, m_config.decoded_text_font (), &m_config}); // hook up termination signal - connect (this, &MainWindow::finished, &QSYMonitor::close); + connect (this, &MainWindow::finished, m_qsymonitorWidget.data (), &QSYMonitor::close); } m_qsymonitorValue = true; m_qsymonitorWidget->showNormal(); @@ -4903,13 +4835,11 @@ void MainWindow::on_actionActiveStations_triggered() connect(m_ActiveStationsWidget.data(), SIGNAL(activeStationsDisplay()),this,SLOT(ARRL_Digi_Display())); m_ActiveStationsWidget->setScore(m_score); if(m_mode=="Q65") m_ActiveStationsWidget->setRate(m_score); - QString as_mode = m_mode; - if(m_mode=="FT8" && SpecOp::FOX==m_specOp) as_mode="Fox Mode"; // TODO - active stations for hound mode? - m_ActiveStationsWidget->setupUi(as_mode); } void MainWindow::on_actionOpen_triggered() //Open File { + if (decoderBusy () || m_wav_load_coordinator.isLoading ()) return; monitor (false); QString fname; @@ -4917,7 +4847,9 @@ void MainWindow::on_actionOpen_triggered() //Open File "WSJT Files (*.wav)"); if(!fname.isEmpty ()) { m_path=fname; - int i1=fname.lastIndexOf("/"); + // Native dialogs on Windows can return backslash-separated paths; + // check both so baseName strips the directory either way. + int i1=qMax(fname.lastIndexOf("/"), fname.lastIndexOf("\\")); QString baseName=fname.mid(i1+1); tx_status_label.setStyleSheet("QLabel{color: #000000; background-color: #99ffff}"); tx_status_label.setText(" " + baseName + " "); @@ -4929,7 +4861,9 @@ void MainWindow::on_actionOpen_triggered() //Open File void MainWindow::read_wav_file (QString const& fname) { - if (m_mode=="FT8" && (m_multithreadFT8 or m_freqNominal>45000000)) { + if (m_wav_load_coordinator.isLoading ()) return; + + if (m_mode=="FT8" && (m_multithreadFT8 or m_operatingFrequency.rx ()>45000000)) { m_nDecodes=0; // reset the decodes counter ndecodes_label.setText(""); earlyDecodes = ""; // reset dupe check @@ -4937,13 +4871,21 @@ void MainWindow::read_wav_file (QString const& fname) // call diskDat() when done int i0=fname.lastIndexOf("_"); int i1=fname.indexOf(".wav"); - int i3=fname.lastIndexOf("/"); + // Native dialogs on Windows can return backslash-separated paths; check + // both so baseName (and so m_UTCdiskDateTime below) is derived from just + // the filename either way. + int i3=qMax(fname.lastIndexOf("/"), fname.lastIndexOf("\\")); QString baseName=fname.mid(i3+1); int i4=baseName.indexOf(".wav"); m_nutc0=m_UTCdisk; if (i1-i3 > 13) { m_UTCdisk=baseName.mid(7, 6).toInt(); - if (i4-i3 > 6) { + // i4 is already an index into baseName (not fname), so compare it + // against a plain threshold rather than subtracting i3 (an fname- + // relative index) from it -- that mismatch made this check fail for + // any file whose directory path was longer than a few characters, + // even though baseName itself was perfectly valid. + if (i4 > 6) { m_UTCdiskDateTime = QDateTime::fromString("20" + baseName.mid(0, 13) + "Z", "yyyyMMdd_hhmmsst").toUTC(); } else { m_UTCdiskDateTime = QDateTime{}; @@ -4967,57 +4909,57 @@ void MainWindow::read_wav_file (QString const& fname) } } - m_wav_future_watcher.setFuture (QtConcurrent::run ([this, fname] { - auto basename = fname.mid (fname.lastIndexOf ('/') + 1); - auto pos = fname.indexOf (".wav", 0, Qt::CaseInsensitive); - int i1=fname.indexOf(".wav"); - int i3=fname.lastIndexOf("/"); - // global variables and threads do not mix well, this needs changing - dec_data.params.nutc = 0; - if (pos > 0) { - if (i1-i3 > 13) { - dec_data.params.nutc = basename.mid(7, 6).toInt(); - m_fileDateTime=basename.mid(0, 13); - } else { - if (pos == fname.indexOf ('_', -11) + 7) { - dec_data.params.nutc = fname.mid (pos - 6, 6).toInt (); - m_fileDateTime=fname.mid(pos-13,13); - } else { - dec_data.params.nutc = 100 * fname.mid (pos - 4, 4).toInt (); - m_fileDateTime=fname.mid(pos-11,11); - } - } - } - BWFFile file {QAudioFormat {}, fname}; - bool ok=file.open (BWFFile::ReadOnly); - if(ok) { - auto bytes_per_frame = file.format ().bytesPerFrame (); - int nsamples=m_TRperiod * RX_SAMPLE_RATE; - qint64 max_bytes = std::min (std::size_t (nsamples), - sizeof (dec_data.d2) / sizeof (dec_data.d2[0]))* bytes_per_frame; - auto n = file.read (reinterpret_cast<char *> (dec_data.d2), - std::min (max_bytes, file.size ())); - int frames_read = n / bytes_per_frame; - // zero unfilled remaining sample space - std::memset(&dec_data.d2[frames_read],0,max_bytes - n); - if (11025 == file.format ().sampleRate ()) { - short sample_size = file.format ().sampleSize (); - wav12_ (dec_data.d2, dec_data.d2, &frames_read, &sample_size); - } - dec_data.params.kin = frames_read; - dec_data.params.newdat = 1; + int const nsamples=m_TRperiod * RX_SAMPLE_RATE; + int const sample_capacity=sizeof (dec_data.d2) / sizeof (dec_data.d2[0]); + int const sample_limit=std::min (nsamples, sample_capacity); + m_wav_load_coordinator.start ([fname, sample_limit] { + return std::make_shared<Radio::WavInputResult> ( + Radio::load_wav_input (fname, sample_limit)); + }); +} + +void MainWindow::wav_file_loaded () +{ + if (!m_valid) return; + + auto const result=m_wav_load_coordinator.result (); + if (!result) return; + m_receiveConsumer.invalidate (); + m_referenceInput.reset (); + + { + QMutexLocker lock {&dec_data_mutex ()}; + dec_data.params.nutc=result->nutc; + dec_data.params.yymmdd=result->yymmdd; + if (result->valid) { + std::copy (result->samples.cbegin (), result->samples.cend (), dec_data.d2); + dec_data.params.kin=result->frames; + dec_data.params.newdat=1; } else { - dec_data.params.kin = 0; - dec_data.params.newdat = 0; + dec_data.params.kin=0; + dec_data.params.newdat=0; } + } + m_fileDateTime=result->fileDateTime; + diskDat (); + if (!m_valid) return; +} - dec_data.params.yymmdd=basename.left(6).toInt(); - })); +void MainWindow::update_wav_file_actions () +{ + auto const backendReady = !usesJt9Process () + || Jt9ProcessPhase::Ready == m_jt9ProcessPhase; + bool const enabled=!decoderBusy () && backendReady + && !m_wav_load_coordinator.isLoading (); + ui->actionOpen->setEnabled(enabled); + ui->actionOpen_next_in_directory->setEnabled(enabled); + ui->actionDecode_remaining_files_in_directory->setEnabled(enabled); + ui->monitorButton->setEnabled(!m_wav_load_coordinator.isLoading ()); } void MainWindow::on_actionOpen_next_in_directory_triggered() //Open Next { - if(m_decoderBusy) return; + if(decoderBusy () || m_wav_load_coordinator.isLoading ()) return; monitor (false); int i,len; QFileInfo fi(m_path); @@ -5029,7 +4971,9 @@ void MainWindow::on_actionOpen_next_in_directory_triggered() //Open Next int n=m_path.length(); QString fname=m_path.replace(n-len,len,list.at(i+1)); m_path=fname; - int i1=fname.lastIndexOf("/"); + // Native dialogs on Windows can return backslash-separated paths; + // check both so baseName strips the directory either way. + int i1=qMax(fname.lastIndexOf("/"), fname.lastIndexOf("\\")); QString baseName=fname.mid(i1+1); tx_status_label.setStyleSheet("QLabel{color: #000000; background-color: #99ffff}"); tx_status_label.setText(" " + baseName + " "); @@ -5046,7 +4990,7 @@ void MainWindow::on_actionOpen_next_in_directory_triggered() //Open Next //Open all remaining files void MainWindow::on_actionDecode_remaining_files_in_directory_triggered() { - if(m_decoderBusy) return; + if(decoderBusy () || m_wav_load_coordinator.isLoading ()) return; m_loopall=true; on_actionOpen_next_in_directory_triggered(); } @@ -5062,12 +5006,12 @@ void MainWindow::diskDat() //diskDat() float bw=m_config.RxBandwidth(); if(db > 0.0) degrade_snr_(dec_data.d2,&dec_data.params.kin,&db,&bw); for(int n=1; n<=m_hsymStop; n++) { // Do the waterfall spectra -// k=(n+1)*kstep; //### Why was this (n+1) ??? ### k=n*kstep; if(k > dec_data.params.kin) break; dec_data.params.npts8=k/8; dataSink(k); qApp->processEvents(); //Update the waterfall + if (!m_valid) return; } } else { MessageBox::information_message(this, tr("No data read from disk. Wrong file format?")); @@ -5128,56 +5072,7 @@ void MainWindow::on_actionKeyboard_shortcuts_triggered() QFont font; font.setPointSize (10); m_shortcuts.reset (new HelpTextWindow {tr ("Keyboard Shortcuts"), - //: Keyboard shortcuts help window contents - tr (R"(<table cellspacing=1> - <tr><td><b>Esc </b></td><td>Stop Tx, abort QSO, clear next-call queue</td></tr> - <tr><td><b>F1 </b></td><td>Online User's Guide (Alt: transmit Tx6)</td></tr> - <tr><td><b>Shift+F1 </b></td><td>Copyright Notice</td></tr> - <tr><td><b>Ctrl+F1 </b></td><td>About WSJT-X</td></tr> - <tr><td><b>F2 </b></td><td>Open settings window (Alt: transmit Tx2)</td></tr> - <tr><td><b>F3 </b></td><td>Display keyboard shortcuts (Alt: transmit Tx3)</td></tr> - <tr><td><b>F4 </b></td><td>Clear DX Call, DX Grid, Tx messages 1-4 (Alt: transmit Tx4)</td></tr> - <tr><td><b>Alt+F4 </b></td><td>Exit program</td></tr> - <tr><td><b>F5 </b></td><td>Display special mouse commands (Alt: transmit Tx5)</td></tr> - <tr><td><b>F6 </b></td><td>Open next file in directory (Alt: toggle "Call 1st")</td></tr> - <tr><td><b>Shift+F6 </b></td><td>Decode all remaining files in directory</td></tr> - <tr><td><b>F7 </b></td><td>Display Message Averaging window</td></tr> - <tr><td><b>F11 </b></td><td>Move Rx frequency down 1 Hz</td></tr> - <tr><td><b>Ctrl+F11 </b></td><td>Move identical Rx and Tx frequencies down 1 Hz</td></tr> - <tr><td><b>Shift+F11 </b></td><td>Move Tx frequency down 60 Hz (FT8) or 90 Hz (FT4)</td></tr> - <tr><td><b>Ctrl+Shift+F11 </b></td><td>Move dial frequency down 1000 Hz</td></tr> - <tr><td><b>F12 </b></td><td>Move Rx frequency up 1 Hz</td></tr> - <tr><td><b>Ctrl+F12 </b></td><td>Move identical Rx and Tx frequencies up 1 Hz</td></tr> - <tr><td><b>Shift+F12 </b></td><td>Move Tx frequency up 60 Hz (FT8) or 90 Hz (FT4)</td></tr> - <tr><td><b>Ctrl+Shift+F12 </b></td><td>Move dial frequency up 1000 Hz</td></tr> - <tr><td><b>Alt+1-6 </b></td><td>Set now transmission to this number on Tab 1</td></tr> - <tr><td><b>Ctl+1-6 </b></td><td>Set next transmission to this number on Tab 1</td></tr> - <tr><td><b>Alt+A </b></td><td>Clear Active Stations for QMAP</td></tr> - <tr><td><b>Alt+B </b></td><td>Toggle "Best S+P" status</td></tr> - <tr><td><b>Alt+C </b></td><td>Toggle "Call 1st" checkbox</td></tr> - <tr><td><b>Alt+D </b></td><td>Decode again at QSO frequency</td></tr> - <tr><td><b>Shift+D </b></td><td>Full decode (both windows)</td></tr> - <tr><td><b>Ctrl+E </b></td><td>Turn on TX even/1st</td></tr> - <tr><td><b>Shift+E </b></td><td>Turn off TX even/1st</td></tr> - <tr><td><b>Alt+E </b></td><td>Erase</td></tr> - <tr><td><b>Ctrl+F </b></td><td>Edit the free text message box</td></tr> - <tr><td><b>Alt+G </b></td><td>Generate standard messages</td></tr> - <tr><td><b>Alt+H </b></td><td>Halt Tx</td></tr> - <tr><td><b>Ctrl+I </b></td><td>Add Dx Call to the Ignore List</td></tr> - <tr><td><b>Ctrl+L </b></td><td>Lookup callsign in database, generate standard messages</td></tr> - <tr><td><b>Alt+M </b></td><td>Monitor</td></tr> - <tr><td><b>Alt+N </b></td><td>Toggle "Enable Tx"</td></tr> - <tr><td><b>Ctrl+O </b></td><td>Open a .wav file</td></tr> - <tr><td><b>Alt+O </b></td><td>Change operator</td></tr> - <tr><td><b>Alt+Q </b></td><td>Open "Log QSO" window</td></tr> - <tr><td><b>Ctrl+R </b></td><td>Set Tx4 message to RRR (not in FT4)</td></tr> - <tr><td><b>Alt+R </b></td><td>Set Tx4 message to RR73</td></tr> - <tr><td><b>Ctrl+Shift+R </b></td><td>Refresh Active Stations window</td></tr> - <tr><td><b>Alt+S </b></td><td>Stop monitoring</td></tr> - <tr><td><b>Alt+T </b></td><td>Toggle Tune status</td></tr> - <tr><td><b>Alt+Z </b></td><td>Clear hung decoder status</td></tr> - -</table>)"), font}); + Radio::HelpText::keyboardShortcuts(), font}); } m_shortcuts->showNormal (); m_shortcuts->raise (); @@ -5190,136 +5085,12 @@ void MainWindow::on_actionSpecial_mouse_commands_triggered() QFont font; font.setPointSize (10); m_mouseCmnds.reset (new HelpTextWindow {tr ("Special Mouse Commands"), - //: Mouse commands help window contents - tr (R"(<table cellpadding=5> - <tr> - <th align="right">Click on</th> - <th align="left">Action</th> - </tr> - <tr> - <td align="right">Waterfall:</td> - <td><b>Click</b> to set Rx frequency.<br/> - <b>Right-click</b> to set Tx frequency.<br/> - <b>Double-right-click</b> to set Rx and Tx frequencies. - </td> - </tr> - <tr> - <td align="right">Decoded text:</td> - <td><b>Double-click</b> to copy second callsign to Dx Call, locator to Dx Grid, change Rx<br/> - and Tx frequency to decoded signal's frequency, and generate standard messages.<br/> - Hold down <b>Alt</b> to prevent Tx from being enabled on <b>double-click</b>.<br/> - If <b>Hold Tx Freq</b> is checked or first callsign in message is your<br/> - own call, Tx frequency is not changed unless <b>Ctrl</b> is held down. - </td> - </tr> - <tr> - <td align="right">Dial Frequency:</td> - <td><b>Turn the mouse wheel</b> to change the kHz values, or:<br/> - <b>Right-click</b> to increase frequency by 1 kHz.<br/> - <b>Left-click</b> to decrease frequency by 1 kHz.<br/> - The mouse pointer must be over the Dial Frequency indicator. - </td> - </tr> - <tr> - <td align="right">H Button:</td> - <td><b>Click</b> to toggle FT8 Hound Mode On/Off.<br/> - <b>Right-click</b> to activate or deactivate SuperFox mode. - </td> - </tr> - <tr> - <td align="right">FT8 Button:</td> - <td><b>Click</b> to switch to FT8 Hound Mode.<br/> - <b>Right-click</b> to toggle last used Special Operating Activity On/Off. - </td> - </tr> - <tr> - <td align="right">Q65 Button:</td> - <td><b>Click</b> to switch to Q65 Mode.<br/> - <b>Right-click</b> to switch to Q65 Pileup Mode. - </td> - </tr> - <tr> - <td align="right">JT65 Button:</td> - <td><b>Click</b> to switch to JT65 Mode.<br/> - <b>Right-click</b> to switch to JT9 Mode. - </td> - </tr> - <tr> - <td align="right">Tx5 Button:</td> - <td><b>Right-click</b> to retain Tx5 free text. - </td> - </tr> - <tr> - <td align="right">Tx Even/1st:</td> - <td><b>Right-click</b> to freeze the state of the checkbox.<br/> - <b>Right-click on the FT8 Button</b> to unfreeze. - </td> - </tr> - <tr> - <td align="right">Enable Tx Button:</td> - <td><b>Click</b> to toggle Auto-Tx mode On/Off.<br/> - <b>Right-click</b> to toggle Wait & Pounce On/Off. - </td> - </tr> - <tr> - <td align="right">Erase button:</td> - <td><b>Click</b> to erase Rx Frequency window.<br/> - <b>Double-click</b> to erase Rx Frequency and Band Activity windows.<br/> - If <b>Alternate Erase button behavior</b> is checked:<br/> - <b>Click</b> to erase Band Activity window.<br/> - <b>Right-click</b> to erase Rx Frequency window.<br/> - <b>Double-click</b> to erase Rx Frequency and Band Activity windows. - </td> - </tr> - <tr> - <td align="right">DX Call Button:</td> - <td><b>Click</b> to toggle Wait & Call On/Off.<br/> - <b>Right-click</b> to clear the Dx Call, Dx Grid and Std Msgs. - </td> - </tr> - <tr> - <td align="right">Lookup Button:</td> - <td><b>Click</b> to search for callsign in database.<br/> - <b>Right-click</b> to search for Dx Call on qrz.com. - </td> - </tr> - <tr> - <td align="right">Add Button:</td> - <td><b>Click</b> to add callsign and locator to database.<br/> - <b>Right-click</b> to search for Dx Call on hamqth.com. - </td> - </tr> - <tr> - <td align="right">Ignore Button:</td> - <td><b>Click</b> to add callsign to the Ignore List.<br/> - <b>Right-click</b> to search for Dx Call on qrzcq.com. - </td> - </tr> - <tr> - <td align="right">Band Buttons:</td> - <td><b>Click</b> to toggle band / mode default frequencies.<br/> - <b>Right-click</b> to toggle FT8 DXpedition frequencies. - </td> - </tr> -</table>)"), font}); + Radio::HelpText::specialMouseCommands(), font}); } m_mouseCmnds->showNormal (); m_mouseCmnds->raise (); } -void MainWindow::on_DecodeButton_clicked (bool /* checked */) //Decode request -{ - if(m_mode=="MSK144") { - ui->DecodeButton->setChecked(false); - } else { - if(m_mode!="WSPR" && !m_decoderBusy) { - m_manualDecode=true; - dec_data.params.newdat=0; - dec_data.params.nagain=1; - decode(); - } - } -} void MainWindow::freezeDecode(int n) //freezeDecode() { @@ -5329,20 +5100,6 @@ void MainWindow::freezeDecode(int n) //freezeDecode() } } -void MainWindow::on_ClrAvgButton_clicked() -{ - m_nclearave=1; - if(m_mode=="Echo") { - echocom_.nsum=0; - m_echoGraph->clearAvg(); - m_wideGraph->restartTotalPower(); - } else { - if(m_msgAvgWidget != NULL) { - if(m_msgAvgWidget->isVisible()) m_msgAvgWidget->displayAvg(""); - } - if(m_mode=="Q65") ndecodes_label.setText("0 0"); - } -} void MainWindow::msgAvgDecode2() { @@ -5351,7 +5108,51 @@ void MainWindow::msgAvgDecode2() void MainWindow::decode() //decode() { - if(m_decoderBusy) return; //Don't start decoder if it's already busy. + decode (Ft8MtdDecodeCoordinator::Stage::None); +} + +void MainWindow::decode (Ft8MtdDecodeCoordinator::Stage ft8Stage, + qint64 ft8Period) +{ + if (ft8Period < 0) ft8Period = currentFt8DecodePeriod (); + auto const scheduledFt8 = Ft8MtdDecodeCoordinator::Stage::None != ft8Stage; + Ft8MtdDecodeCoordinator::Decision ft8Decision; + if (scheduledFt8) + { + ft8Decision = m_ft8MtdDecodeCoordinator.request ( + ft8Stage, ft8Period, configuredFt8MtdEarlyStageCount (), decoderBusy ()); + reportFt8BackpressureDecision (ft8Decision, ft8Period); + if (Ft8MtdDecodeCoordinator::Action::SkipEarly == ft8Decision.action) + { + ui->DecodeButton->setChecked (false); + return; + } + } + + auto const deferFt8Final = scheduledFt8 + && (Ft8MtdDecodeCoordinator::Action::DeferFinal == ft8Decision.action + || Ft8MtdDecodeCoordinator::Action::ReplaceFinal == ft8Decision.action); + if(decoderBusy () && !deferFt8Final) { + recoverDecoderAtBoundary ("decode cycle boundary", false); + if (decoderBusy ()) { + logDecoderBusyRequest("decode request"); + return; //Don't start decoder if it's already busy. + } + } + if (usesJt9Process () + && (Jt9ProcessPhase::Ready != m_jt9ProcessPhase + || QProcess::Running != proc_jt9.state ()) + && Ft8MtdDecodeCoordinator::Stage::Final != ft8Stage) + { + ui->DecodeButton->setChecked (false); + showStatusMessage (tr ("Decoder is starting; decode request skipped.")); + return; + } + if (usesJt9Process () && !dec_data.params.newdat && !m_jt9PayloadValid) + { + dec_data.params.newdat = true; + dec_data.params.nagain = false; + } m_fetched=0; QDateTime now = QDateTime::currentDateTimeUtc (); if( m_dateTimeLastTX.isValid () ) { @@ -5372,6 +5173,9 @@ void MainWindow::decode() //decode() dec_data.params.nutc=dec_data.params.nutc/100; } if(dec_data.params.nagain==0 && dec_data.params.newdat==1 && (!m_diskData)) { + if(m_mode=="Q65" and m_specOp==SpecOp::Q65_PILEUP) { + m_q65PileupCopiedLastRxCall.clear(); // starting a decode pass over fresh audio + } m_dateTimeSeqStart = qt_truncate_date_time_to (QDateTime::currentDateTimeUtc (), m_TRperiod * 1.e3); auto t = m_dateTimeSeqStart.time (); dec_data.params.nutc = t.hour () * 100 + t.minute (); @@ -5390,7 +5194,7 @@ void MainWindow::decode() //decode() dec_data.params.nutc=10000*ihr + 100*imin + isec; } if(m_nPick==2) dec_data.params.nutc=m_nutc0; - dec_data.params.nQSOProgress = m_QSOProgress; + dec_data.params.nQSOProgress = static_cast<int> (m_QSOProgress); dec_data.params.nfqso=m_wideGraph->rxFreq(); dec_data.params.nftx = ui->TxFreqSpinBox->value (); qint32 depth {m_ndepth}; @@ -5470,6 +5274,9 @@ void MainWindow::decode() //decode() if(dec_data.params.nexp_decode==5) dec_data.params.nexp_decode=1; //NA VHF, WW Digi, ARRL Digi contests if(dec_data.params.nexp_decode==8) dec_data.params.nexp_decode=1; //and Q65 Pileup all use 4-character if(dec_data.params.nexp_decode==9) dec_data.params.nexp_decode=1; //grid exchange + if(m_mode=="Q65" && m_specOp==SpecOp::Q65_PILEUP) { + dec_data.params.nexp_decode |= q65PileupDecodeFlag; + } if(m_config.single_decode()) dec_data.params.nexp_decode += 32; if(m_config.enable_VHF_features()) dec_data.params.nexp_decode += 64; if(m_mode.startsWith("FST4")) dec_data.params.nexp_decode += 256*(ui->sbNB->value()+3); @@ -5483,10 +5290,10 @@ void MainWindow::decode() //decode() { //FT8 block of parameters for multithreaded FT8 decoder dec_data.params.nstophint = 0; // stophint should be false to avoid truncating decode process - dec_data.params.nQSOProgress = m_QSOProgress; + dec_data.params.nQSOProgress = static_cast<int> (m_QSOProgress); dec_data.params.nftx = ui->TxFreqSpinBox->value (); - if(m_freqNominal < 30000000) dec_data.params.napwid=5; // FT8AP decoding bandwidth for 'mycall hiscall ???' and RRR,RR73,73 messages - else if(m_freqNominal < 100000000) dec_data.params.napwid=15; + if(m_operatingFrequency.rx () < 30000000) dec_data.params.napwid=5; // FT8AP decoding bandwidth for 'mycall hiscall ???' and RRR,RR73,73 messages + else if(m_operatingFrequency.rx () < 100000000) dec_data.params.napwid=15; else dec_data.params.napwid=50; dec_data.params.nmt=m_ft8threads; dec_data.params.ncandthin=m_ncandthin; @@ -5537,7 +5344,7 @@ void MainWindow::decode() //decode() dec_data.params.lmultift8 = false; // use the standard FT8 decoder for early decoding step if (m_ihsym==m_earlyDecode2) dec_data.params.ndepth=2; } - qDebug() << "dec_data.params.lmultift8 is" << dec_data.params.lmultift8; //ft8md +// qDebug() << "dec_data.params.lmultift8 is" << dec_data.params.lmultift8; //ft8md dec_data.params.ndiskdat=0; if(m_diskData) dec_data.params.ndiskdat=1; dec_data.params.nfa=m_wideGraph->nStartFreq(); @@ -5568,55 +5375,84 @@ void MainWindow::decode() //decode() if(!hisCall.isEmpty() && !m_auto && hisCall != m_lastloggedcall) dec_data.params.lenabledxcsearch=true; //ft8md was && !m_enableTx else dec_data.params.lenabledxcsearch=false; - if (auto * to = reinterpret_cast<char *> (mem_jt9->data())) + if(m_mode=="MSK144" or m_bFast9) { + float t0=m_t0; + float t1=m_t1; + m_fastDecodePending = true; + qApp->processEvents(); //Update the waterfall + if(m_nPick > 0) { + t0=m_t0Pick; + t1=m_t1Pick; + } + narg[0]=dec_data.params.nutc; + if(m_kdone>int(12000.0*m_TRperiod)) { + m_kdone=int(12000.0*m_TRperiod); + } + narg[1]=m_kdone; + narg[2]=m_nSubMode; + narg[3]=dec_data.params.newdat; + narg[4]=dec_data.params.minSync; + narg[5]=m_nPick; + narg[6]=1000.0*t0; + narg[7]=1000.0*t1; + narg[8]=2; //Max decode lines per decode attempt + if(dec_data.params.minSync<0) narg[8]=50; + if(m_mode=="JT9") narg[9]=102; //Fast JT9 + if(m_mode=="MSK144") narg[9]=104; //MSK144 + narg[10]=ui->RxFreqSpinBox->value(); + narg[11]=ui->sbFtol->value (); + narg[12]=0; + narg[13]=-1; + narg[14]=m_config.aggressive(); + watcher3.setFuture (startFastDecode (dec_data.d2, &narg[0], m_TRperiod, + dec_data.params.mycall, dec_data.params.hiscall)); + } else { + decoder_params_t decoderParams; { - char *from = (char*) dec_data.ipc; - int size=sizeof(struct dec_data); - if(dec_data.params.newdat==0) { - int noffset {offsetof (struct dec_data, params.nutc)}; - to += noffset; - from += noffset; - size -= noffset; + QMutexLocker lock {&dec_data_mutex ()}; + decoderParams = dec_data.params; + } + if (deferFt8Final) + { + auto pending = capturePendingFt8MtdDecode (ft8Period); + auto const action = m_ft8MtdDecodeCoordinator.deferFinal (std::move (pending)); + qWarning () << (Ft8MtdDecodeCoordinator::Action::ReplaceFinal == action + ? "Replacing pending FT8 final decode" + : "Deferring FT8 final decode") + << "period:" << ft8Period + << "backoffPeriods:" << m_ft8MtdDecodeCoordinator.skippedPeriods (); + ui->DecodeButton->setChecked (false); + updateDecodeControls (); + return; } - if(m_mode=="MSK144" or m_bFast9) { - float t0=m_t0; - float t1=m_t1; - qApp->processEvents(); //Update the waterfall - if(m_nPick > 0) { - t0=m_t0Pick; - t1=m_t1Pick; - } - static short int d2b[360000]; - narg[0]=dec_data.params.nutc; - if(m_kdone>int(12000.0*m_TRperiod)) { - m_kdone=int(12000.0*m_TRperiod); - } - narg[1]=m_kdone; - narg[2]=m_nSubMode; - narg[3]=dec_data.params.newdat; - narg[4]=dec_data.params.minSync; - narg[5]=m_nPick; - narg[6]=1000.0*t0; - narg[7]=1000.0*t1; - narg[8]=2; //Max decode lines per decode attempt - if(dec_data.params.minSync<0) narg[8]=50; - if(m_mode=="JT9") narg[9]=102; //Fast JT9 - if(m_mode=="MSK144") narg[9]=104; //MSK144 - narg[10]=ui->RxFreqSpinBox->value(); - narg[11]=ui->sbFtol->value (); - narg[12]=0; - narg[13]=-1; - narg[14]=m_config.aggressive(); - memcpy(d2b,dec_data.d2,2*360000); - watcher3.setFuture (QtConcurrent::run (std::bind (fast_decode_, &d2b[0], - &narg[0],&m_TRperiod, &m_msg[0][0], dec_data.params.mycall, - dec_data.params.hiscall, (FCL)8000, (FCL)12, (FCL)12))); - } else { - mem_jt9->lock (); - memcpy(to, from, qMin(mem_jt9->size(), size)); - mem_jt9->unlock (); - to_jt9(m_ihsym,1,-1); //Send m_ihsym to jt9[.exe] and start decoding - decodeBusy(true); + + auto const publishResult = publishDecodeRequest ( + decoderParams.newdat, ft8Stage, ft8Period); + if (DecodePublishResult::Published == publishResult && scheduledFt8) + { + if (m_ft8MtdDecodeCoordinator.published (ft8Stage, ft8Period)) + { + reportFt8BackpressureRecovery (ft8Period); + } + emitFt8DecoderInvocation (decoderParams); + } + if (DecodePublishResult::Published != publishResult) + { + ui->DecodeButton->setChecked (false); + if (DecodePublishResult::Unavailable == publishResult + && Ft8MtdDecodeCoordinator::Stage::Final == ft8Stage) + { + auto pending = capturePendingFt8MtdDecode (ft8Period); + m_ft8MtdDecodeCoordinator.deferFinal (std::move (pending)); + qWarning () << "Deferring FT8 final decode while decoder starts" + << "period:" << ft8Period; + updateDecodeControls (); + } + if (DecodePublishResult::Failed == publishResult) + { + m_ft8MtdDecodeCoordinator.publicationFailed (ft8Stage, ft8Period); + requestDecoderRestart ("decode publication failed"); + } } } if((m_mode=="FT4" or (m_mode=="FT8" and m_ihsym==41) or m_diskData) and @@ -5625,14 +5461,173 @@ void MainWindow::decode() //decode() } } +#if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) +bool MainWindow::configureLiveAudioTestDecodeRange () +{ + // FT8's 1500/2048 Hz bins make 956 pixels at 4 bins/pixel span 200-3000 Hz. + m_wideGraph->setFrequencyScale (liveAudioTestDecodeLowFrequency (), 4, 956); + return m_wideGraph->nStartFreq () == liveAudioTestDecodeLowFrequency () + && m_wideGraph->Fmax () == liveAudioTestDecodeHighFrequency (); +} + +bool MainWindow::prepareLiveAudioTestFt8InputCompletion () +{ + if (!m_automated_test || m_mode != QStringLiteral ("FT8")) return false; + m_liveAudioTestPendingFt8FinalPeriod = -1; + m_liveAudioTestAwaitFt8InputCompletion = true; + m_liveAudioTestFt8InputComplete = false; + return true; +} + +bool MainWindow::configureLiveAudioTestHandoff () +{ + if (!m_automated_test || m_mode != "FT8") return false; + m_multithreadFT8 = true; + m_ft8DecoderStart = 3; + m_delay = 0; + fixStop (); + return m_hsymStop == 49; +} + +QString MainWindow::completeLiveAudioTestFt8Input (qint64 frames) +{ + auto const expectedInputFrames = + static_cast<qint64> (DecoderIpc::Ft8SampleCount) + * static_cast<qint64> (m_downSampleFactor); + if (!m_automated_test || !m_liveAudioTestAwaitFt8InputCompletion + || frames != expectedInputFrames) + { + return tr ("FT8 input completion was rejected: automated=%1 awaiting=%2 frames=%3.") + .arg (m_automated_test) + .arg (m_liveAudioTestAwaitFt8InputCompletion) + .arg (frames); + } + + if (!QMetaObject::invokeMethod ( + m_detector, "flushBufferedFrames", Qt::BlockingQueuedConnection, + Q_ARG (qint64, DecoderIpc::Ft8SampleCount))) + { + return tr ("Unable to flush the final FT8 audio block."); + } + + // The flush transfers its final owned block through the ordinary queued + // handoff. Complete that delivery before this test-only completeness check. + QCoreApplication::sendPostedEvents (this, QEvent::MetaCall); + + { + QMutexLocker lock {&dec_data_mutex ()}; + if (dec_data.params.kin != DecoderIpc::Ft8SampleCount) + { + return tr ("FT8 input completed with %1 of %2 samples in the decode buffer.") + .arg (dec_data.params.kin) + .arg (DecoderIpc::Ft8SampleCount); + } + } + + m_liveAudioTestFt8InputComplete = true; + if (m_liveAudioTestPendingFt8FinalPeriod >= 0) + { + auto const period = m_liveAudioTestPendingFt8FinalPeriod; + m_liveAudioTestPendingFt8FinalPeriod = -1; + m_liveAudioTestAwaitFt8InputCompletion = false; + m_liveAudioTestFt8InputComplete = false; + decode (Ft8MtdDecodeCoordinator::Stage::Final, period); + } + return {}; +} + +MainWindow::LiveAudioTestFt8TransmitRequest +MainWindow::startLiveAudioTestFt8Transmit (qint64 targetPeriodStartMs) +{ + if (!m_automated_test || m_mode != QStringLiteral ("FT8")) + { + std::cerr << "FT8 TX loopback trigger rejected: automated=" + << m_automated_test << " mode=" << m_mode.toStdString () + << std::endl; + return {}; + } + + if (!m_transmitting) + { + g_iptt = 1; + m_iptt0 = 0; + guiUpdate (); + } + if (!m_transmitting) + { + std::cerr << "FT8 TX loopback could not arm transmission: g_iptt=" + << g_iptt << " m_iptt0=" << m_iptt0 + << " message=" << m_currentMessage.toStdString () + << " generated_error=" << m_generated_message_error + << std::endl; + return {}; + } + + // The fixture has no rig backend, so release the generated waveform at the + // same seam normally reached after the rig acknowledges PTT. + m_liveAudioTestFt8StartWindowOpenMs = targetPeriodStartMs; + m_liveAudioTestFt8StartWindowCloseMs = targetPeriodStartMs + 499; + m_liveAudioTestFt8StartSessionId = -1; + m_liveAudioTestFt8StartGeneration = -1; + m_tx_when_ready = false; + ptt1Timer.stop (); + auto const dispatched = startTx2 (); + m_liveAudioTestFt8StartWindowOpenMs = -1; + m_liveAudioTestFt8StartWindowCloseMs = -1; + if (!dispatched) + { + return {}; + } + return {m_liveAudioTestFt8StartSessionId, + m_liveAudioTestFt8StartGeneration}; +} + +QString MainWindow::liveAudioTestFt8BackpressureDiagnostics () const +{ + qint32 ipcState {-1}; + qint32 ipcGeneration {-1}; + qint32 ipcProgress {-1}; + if (DecoderIpc::hasUsableSize (mem_jt9->size ()) && mem_jt9->data ()) + { + auto const * shared = reinterpret_cast<shared_dec_data_t const *> ( + mem_jt9->constData ()); + if (DECODER_IPC_VERSION == DecoderIpc::protocolVersion (*shared)) + { + ipcState = DecoderIpc::state (*shared); + ipcGeneration = DecoderIpc::generation (*shared); + ipcProgress = DecoderIpc::progress (*shared); + } + } + + return QString {"degraded=%1 pending_final=%2 backoff_periods=%3 " + "next_probe_period=%4 owner=%5 process_phase=%6 " + "active_generation=%7 ipc_state=%8 ipc_generation=%9 " + "ipc_progress=%10 decoder_elapsed_ms=%11 " + "decoder_idle_ms=%12"} + .arg (m_ft8MtdDecodeCoordinator.degraded ()) + .arg (m_ft8MtdDecodeCoordinator.hasPending ()) + .arg (m_ft8MtdDecodeCoordinator.skippedPeriods ()) + .arg (m_ft8MtdDecodeCoordinator.nextProbePeriod ()) + .arg (static_cast<int> (m_decodeOwner)) + .arg (static_cast<int> (m_jt9ProcessPhase)) + .arg (m_activeJt9Decode.generation) + .arg (ipcState) + .arg (ipcGeneration) + .arg (ipcProgress) + .arg (decoderDiagnosticElapsedMs ()) + .arg (decoderDiagnosticIdleMs ()); +} +#endif + void::MainWindow::fast_decode_done() { + if (m_fastDecodePending) return; float t,tmax=-99.0; dec_data.params.nagain=false; dec_data.params.ndiskdat=false; -// if(m_msg[0][0]==0) m_bDecoded=false; - for(int i=0; m_msg[i][0] && i<100; i++) { - QString message=QString::fromLatin1(m_msg[i]); + if(m_mode=="JTTY" && m_diskData) flushJttyDecodeLines(); + for(int i=0; i<100 && m_msg[i][0]; i++) { + QString message=QString::fromLatin1(m_msg[i], 80); m_msg[i][0]=0; if(message.length()>80) message=message.left (80); if(narg[13]/8==narg[12]) message=message.trimmed().replace("<...>",m_calls); @@ -5669,19 +5664,671 @@ void::MainWindow::fast_decode_done() m_bFastDone=false; } -void MainWindow::to_jt9(qint32 n, qint32 istart, qint32 idone) +void MainWindow::startDecoderProcess () +{ + auto const replacement = decoderRestartInProgress (); + m_jt9ProcessPhase = replacement ? Jt9ProcessPhase::ReplacementStarting + : Jt9ProcessPhase::InitialStarting; + m_activeJt9Decode = {}; + m_decoderOutputFramer.reset (); + QStringList jt9Args { + "-s", QApplication::applicationName (), // shared memory key, includes rig + "-w", "1", // FFTW planning patience + // The number of threads for FFTW specified here is chosen as + // three because that gives the best throughput of the large + // FFTs used in jt9. The count is the minimum of (the number + // available CPU threads less one) and three. This ensures that + // there is always at least one free CPU thread to run the other + // mode decoder in parallel. + "-m", QString::number (qMin (qMax (QThread::idealThreadCount () - 1, 1), 3)), + "-e", QDir::toNativeSeparators (m_appDir), + "-a", QDir::toNativeSeparators (m_config.writeable_data_dir ().absolutePath ()), + "-t", QDir::toNativeSeparators (m_config.temp_dir ().absolutePath ()), + // -r: read-only shipped-data dir (cty.dat, ALLCALL7.TXT, ...) for the + // Fortran decoder; resolves to Contents/Resources/wsjtx on macOS. + "-r", QDir::toNativeSeparators (m_decoderDataDir.absolutePath ()) + }; + QProcessEnvironment environment {m_env}; + environment.insert ("OMP_STACKSIZE", "10M"); + proc_jt9.setProcessEnvironment (environment); + proc_jt9.start (QDir::toNativeSeparators (QDir {m_appDir}.filePath ("jt9")), + jt9Args, QIODevice::ReadWrite | QIODevice::Unbuffered); + if (replacement) m_decoderStartTimer.start (5000); + updateDecodeControls (); +} + +bool MainWindow::initializeDecoderSharedMemory () +{ + if (!DecoderIpc::hasUsableSize (mem_jt9->size ()) + || !mem_jt9->data ()) + { + return false; + } + auto * shared = reinterpret_cast<shared_dec_data_t *> (mem_jt9->data ()); + DecoderIpc::initialize (*shared); + return true; +} + +DecodeOperatingContext MainWindow::currentDecodeOperatingContext () const { - if (auto * dd = reinterpret_cast<dec_data_t *> (mem_jt9->data())) + auto const periodFrequency = m_freqNominalPeriod ? m_freqNominalPeriod + : m_operatingFrequency.rx (); + auto const periodBand = m_currentBandPeriod.isEmpty () + ? m_config.bands ()->find (periodFrequency) : m_currentBandPeriod; + DecodeOperatingContext context; + context.mode = m_mode; + context.specOp = m_specOp; + context.periodFrequency = periodFrequency; + context.band = periodBand; + context.sequenceStart = m_dateTimeSeqStart; + context.trPeriod = m_TRperiod; + context.submode = m_nSubMode; + context.diskData = m_diskData; + context.multithreadFt8 = m_multithreadFT8; + context.ft8DecoderStart = m_ft8DecoderStart; + context.ft8ThreadCount = m_ft8threads; + context.decodeDepth = m_ndepth; + context.ft8Cycles = m_nFT8Cycles; + context.ft8Sensitivity = m_ft8Sensitivity; + context.ft8RxFrequencySensitivity = m_nFT8RXfSens; + context.decodeLowFrequency = m_wideGraph->nStartFreq (); + context.decodeHighFrequency = m_wideGraph->Fmax (); + context.ft8WideDxCallSearch = m_FT8WideDxCallSearch; + context.hideFt8DuplicateMessages = ui->actionHide_FT8_dupe_messages->isChecked (); + context.ft8ApEnabled = ui->actionEnable_AP_FT8->isChecked (); + context.superFox = m_config.superFox (); + context.myCall = m_config.my_callsign (); + return context; +} + +bool MainWindow::activeDecodeOperatingContextMatchesCurrent () const +{ + return decodeOperatingContextMatchesCurrent (m_activeJt9Decode.context); +} + +bool MainWindow::decodeOperatingContextMatchesCurrent ( + DecodeOperatingContext const& context) const +{ + auto current = currentDecodeOperatingContext (); + current.periodFrequency = m_operatingFrequency.rx (); + current.band = m_config.bands ()->find (m_operatingFrequency.rx ()); + return context.hasSameDecodeIdentity (current); +} + +bool MainWindow::pendingFt8DecodeOperatingContextMatchesCurrent ( + DecodeOperatingContext const& context) const +{ + auto current = currentDecodeOperatingContext (); + current.periodFrequency = m_operatingFrequency.rx (); + current.band = m_config.bands ()->find (m_operatingFrequency.rx ()); + return context.hasSameFt8PendingIdentity (current); +} + +qint64 MainWindow::currentFt8DecodePeriod () const +{ + auto const periodMs = qMax<qint64> (1, qRound64 (m_TRperiod * 1000.0)); + return QDateTime::currentMSecsSinceEpoch () / periodMs; +} + +bool MainWindow::usesFt8MtdFinal () const +{ + auto const standardFinalRequired = + SpecOp::HOUND == m_specOp && m_config.superFox (); + return m_mode == "FT8" + && Ft8MtdDecodeScheduler::supportsBackpressure ( + m_multithreadFT8, standardFinalRequired); +} + +int MainWindow::configuredFt8MtdEarlyStageCount () const +{ + Q_ASSERT (usesFt8MtdFinal ()); + if (0 == m_ft8DecoderStart) return 1; + if (1 == m_ft8DecoderStart) return 2; + return 0; +} + +std::unique_ptr<Ft8MtdDecodeCoordinator::PendingMtdDecode> +MainWindow::capturePendingFt8MtdDecode (qint64 period) const +{ + auto pending = std::make_unique<Ft8MtdDecodeCoordinator::PendingMtdDecode> (); + pending->period = period; + pending->context = currentDecodeOperatingContext (); + { + QMutexLocker payloadLock {&dec_data_mutex ()}; + pending->payload.params = dec_data.params; + Q_ASSERT (8 == pending->payload.params.nmode); + Q_ASSERT (pending->payload.params.lmultift8); + std::copy_n (dec_data.d2, DecoderIpc::Ft8SampleCount, + pending->payload.samples.begin ()); + } + return pending; +} + +void MainWindow::reportFt8BackpressureDecision ( + Ft8MtdDecodeCoordinator::Decision const& decision, qint64 period) +{ + if (decision.enteredDegraded) + { + showStatusMessage (tr ( + "FT8 decoding is running behind; early passes are temporarily reduced.")); + qWarning () << "FT8 decoder entered bounded backpressure" + << "period:" << period + << "backoffPeriods:" << decision.skippedPeriods; + } + else if (Ft8MtdDecodeCoordinator::Action::SkipEarly == decision.action) + { + qInfo () << "Skipping FT8 early decode during backpressure" + << "period:" << period + << "backoffPeriods:" << decision.skippedPeriods + << "nextProbePeriod:" << m_ft8MtdDecodeCoordinator.nextProbePeriod (); + } +} + +void MainWindow::reportFt8BackpressureRecovery (qint64 period) +{ + showStatusMessage (tr ("FT8 decoding caught up; configured early passes restored.")); + qInfo () << "FT8 decoder recovered from bounded backpressure" + << "period:" << period; +} + +void MainWindow::emitFt8DecoderInvocation (decoder_params_t const& params) const +{ +#if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) + if (m_automated_test) + { + Q_EMIT ft8DecoderInvocation ( + params.lmultift8, params.nmt, params.ndepth & 7, + params.nft8cycles, params.lft8subpass, params.ndecoderstart, + params.nzhsym, params.kin, params.nfa, params.nfb); + } +#else + Q_UNUSED (params); +#endif +} + +MainWindow::DecodePublishResult MainWindow::publishDecodeRequest ( + bool copySamples, Ft8MtdDecodeCoordinator::Stage ft8Stage, qint64 ft8Period) +{ + if (Jt9ProcessPhase::Ready != m_jt9ProcessPhase + || QProcess::Running != proc_jt9.state () + || decoderBusy ()) + { + return DecodePublishResult::Unavailable; + } + if ((!copySamples && !m_jt9PayloadValid) + || !DecoderIpc::hasUsableSize (mem_jt9->size ()) + || !mem_jt9->data ()) + { + return DecodePublishResult::Failed; + } + + if (!m_freqNominalPeriod) + { + m_freqNominalPeriod = m_operatingFrequency.rx (); + m_currentBandPeriod = m_config.bands ()->find (m_operatingFrequency.rx ()); + } + + auto const generation = DecoderIpc::nextGeneration (m_nextDecoderGeneration); + if (!beginDecode (DecodeOwner::Jt9)) + { + return DecodePublishResult::Failed; + } + m_activeJt9Decode = {}; + m_activeJt9Decode.generation = generation; + m_activeJt9Decode.context = currentDecodeOperatingContext (); + m_activeJt9Decode.copiedSamples = copySamples; + m_activeJt9Decode.ft8Stage = ft8Stage; + m_activeJt9Decode.ft8Period = ft8Period; + bool published {false}; + { + QMutexLocker payloadLock {&dec_data_mutex ()}; + auto * shared = reinterpret_cast<shared_dec_data_t *> (mem_jt9->data ()); + published = DecoderIpc::publish (*shared, dec_data, copySamples, generation); + } + if (!published) + { + logDecoderAbnormalClear ("decode publication failed"); + m_activeJt9Decode = {}; + endDecode (DecodeOwner::Jt9, DecodeEndState::Aborted); + return DecodePublishResult::Failed; + } + + m_nextDecoderGeneration = generation; + return DecodePublishResult::Published; +} + +MainWindow::DecodePublishResult MainWindow::publishPendingFt8Decode () +{ + using DrainResult = Ft8MtdDecodeCoordinator::DrainResult; + using PendingPublishResult = Ft8MtdDecodeCoordinator::PendingPublishResult; + + auto const outcome = m_ft8MtdDecodeCoordinator.drainPending ( + [this] (Ft8MtdDecodeCoordinator::PendingMtdDecode const& pending) { + return m_monitoring + && pendingFt8DecodeOperatingContextMatchesCurrent (pending.context); + }, + [this] (Ft8MtdDecodeCoordinator::PendingMtdDecode const& pending) { + if (Jt9ProcessPhase::Ready != m_jt9ProcessPhase + || QProcess::Running != proc_jt9.state ()) + { + return PendingPublishResult::Unavailable; + } + if (!DecoderIpc::hasUsableSize (mem_jt9->size ()) || !mem_jt9->data ()) + { + return PendingPublishResult::Failed; + } + + auto const generation = DecoderIpc::nextGeneration ( + m_nextDecoderGeneration); + if (!beginDecode (DecodeOwner::Jt9, &pending.payload.params, + &pending.context)) + { + return PendingPublishResult::Unavailable; + } + m_activeJt9Decode = {}; + m_activeJt9Decode.generation = generation; + m_activeJt9Decode.context = pending.context; + m_activeJt9Decode.copiedSamples = true; + m_activeJt9Decode.ft8Stage = Ft8MtdDecodeCoordinator::Stage::Final; + m_activeJt9Decode.ft8Period = pending.period; + + auto * shared = reinterpret_cast<shared_dec_data_t *> (mem_jt9->data ()); + if (!DecoderIpc::publishFt8Mtd (*shared, pending.payload, generation)) + { + logDecoderAbnormalClear ("pending FT8 decode publication failed"); + m_activeJt9Decode = {}; + endDecode (DecodeOwner::Jt9, DecodeEndState::Aborted); + return PendingPublishResult::Failed; + } + + m_nextDecoderGeneration = generation; + emitFt8DecoderInvocation (pending.payload.params); + qInfo () << "Published pending FT8 final decode" + << "period:" << pending.period + << "generation:" << generation; + return PendingPublishResult::Published; + }); + + if (DrainResult::Obsolete == outcome.result) + { + qInfo () << "Canceling obsolete pending FT8 final decode" + << "period:" << outcome.period; + updateDecodeControls (); + } + if (outcome.recovered) reportFt8BackpressureRecovery (outcome.period); + if (DrainResult::Published == outcome.result) + { + return DecodePublishResult::Published; + } + if (DrainResult::Failed == outcome.result) return DecodePublishResult::Failed; + return DecodePublishResult::Unavailable; +} + +void MainWindow::cancelPendingFt8Decode (QString const& reason) +{ + if (m_ft8MtdDecodeCoordinator.hasPending () || m_ft8MtdDecodeCoordinator.degraded ()) + { + qInfo () << "Resetting FT8 decode backpressure" << "reason:" << reason; + } + m_ft8MtdDecodeCoordinator.cancel (); + updateDecodeControls (); +} + +void MainWindow::requestDecoderRestart (QString const& reason) +{ + if (m_closing || decoderRestartInProgress ()) return; + if (DecodeOwner::Wsprd == m_decodeOwner) return; + + logDecoderAbnormalClear (reason); + m_jt9ProcessPhase = Jt9ProcessPhase::StopRequested; + abortJt9Transaction (); + updateDecodeControls (); + + if (DecoderIpc::hasUsableSize (mem_jt9->size ()) + && mem_jt9->data ()) + { + auto * shared = reinterpret_cast<shared_dec_data_t *> (mem_jt9->data ()); + DecoderIpc::shutdown (*shared); + } + + if (QProcess::NotRunning == proc_jt9.state ()) + { + if (!initializeDecoderSharedMemory ()) + { + m_valid = false; + QTimer::singleShot (0, this, SLOT (close ())); + return; + } + startDecoderProcess (); + return; + } + m_decoderShutdownTimer.start (250); +} + +bool MainWindow::decoderRestartInProgress () const +{ + return Jt9ProcessPhase::StopRequested == m_jt9ProcessPhase + || Jt9ProcessPhase::Terminating == m_jt9ProcessPhase + || Jt9ProcessPhase::Killing == m_jt9ProcessPhase + || Jt9ProcessPhase::ReplacementStarting == m_jt9ProcessPhase; +} + +bool MainWindow::usesJt9Process () const +{ + return "WSPR" != m_mode && "JTTY" != m_mode + && "MSK144" != m_mode && !m_bFast9; +} + +bool MainWindow::beginDecode ( + DecodeOwner owner, decoder_params_t const * diagnosticParams, + DecodeOperatingContext const * diagnosticContext) +{ + if (DecodeOwner::None == owner || DecodeOwner::None != m_decodeOwner) return false; + m_decodeOwner = owner; + Q_EMIT decodeCycleStarted (++m_decodeCycleGeneration); + if (DecodeOwner::Jt9 == owner) + { + beginDecoderDiagnostic (diagnosticParams, diagnosticContext); + } + updateDecodeControls (); + return true; +} + +void MainWindow::endDecode (DecodeOwner owner, DecodeEndState state) +{ + if (owner != m_decodeOwner) + { + qWarning () << "Ignoring decode completion from a non-owning decoder"; + return; + } + if (DecodeOwner::Jt9 == owner) + { + finishDecoderDiagnostic (); + } + m_decodeOwner = DecodeOwner::None; + if (DecodeEndState::Completed == state) + { + Q_EMIT decodeCycleCompleted (m_decodeCycleGeneration); + } + else + { + Q_EMIT decodeCycleAborted (m_decodeCycleGeneration); + } + updateDecodeControls (); +} + +void MainWindow::updateDecodeControls () +{ + auto const backendReady = !usesJt9Process () + || Jt9ProcessPhase::Ready == m_jt9ProcessPhase; + auto const enabled = !decoderBusy () && backendReady + && !m_wav_load_coordinator.isLoading (); + ui->DecodeButton->setEnabled (enabled && "WSPR" != m_mode + && "FST4W" != m_mode && "Echo" != m_mode); + update_wav_file_actions (); + statusUpdate (); +} + +void MainWindow::abortJt9Transaction () +{ + m_decoderOutputFramer.reset (); + m_ft8MtdDecodeCoordinator.publicationFailed ( + m_activeJt9Decode.ft8Stage, m_activeJt9Decode.ft8Period); + m_activeJt9Decode = {}; + m_jt9PayloadValid = false; + dec_data.params.nagain = false; + dec_data.params.ndiskdat = false; + m_nclearave = 0; + m_RxLog = 0; + m_nDecodes = 0; + m_bDecoded = false; + m_manualDecode = false; + m_startAnother = false; + m_loopall = false; + m_bNoMoreFiles = false; + ui->DecodeButton->setChecked (false); + ndecodes_label.setText ("Q65" == m_mode ? "0 0" : "0"); + if (DecodeOwner::Jt9 == m_decodeOwner) { - mem_jt9->lock (); - dd->ipc[0]=n; - if(istart>=0) dd->ipc[1]=istart; - if(idone>=0) dd->ipc[2]=idone; - mem_jt9->unlock (); + endDecode (DecodeOwner::Jt9, DecodeEndState::Aborted); } + else updateDecodeControls (); +} + +qint64 MainWindow::decoderDiagnosticElapsedMs() const +{ + if(!m_decoderDiagActive || !m_decoderDiagElapsedTimer.isValid()) return -1; + return m_decoderDiagElapsedTimer.elapsed(); +} + +qint64 MainWindow::decoderDiagnosticIdleMs() const +{ + if(!m_decoderDiagActive || !m_decoderDiagProgressTimer.isValid()) return -1; + return m_decoderDiagProgressTimer.elapsed(); +} + +qint64 MainWindow::decoderRequestDeadlineMs() const +{ + auto const automaticLiveDecode = m_decoderCompletedSinceStart + && !m_decoderDiagStartNdiskdat + && m_decoderDiagStartNewdat + && !m_decoderDiagStartNagain; + if (automaticLiveDecode && "FT4" == m_decoderDiagStartMode) return 6000; + if (automaticLiveDecode && "FT8" == m_decoderDiagStartMode) return 10000; + + auto const minimum = m_decoderCompletedSinceStart ? 60000 : 300000; + return std::max<qint64> ( + minimum, static_cast<qint64> (4.0 * m_decoderDiagStartTRperiod * 1000.0)); +} + +bool MainWindow::decoderRequestDeadlineExpired() const +{ + auto const idle = decoderDiagnosticIdleMs (); + return idle >= 0 && idle >= decoderRequestDeadlineMs (); +} + +void MainWindow::beginDecoderDiagnostic( + decoder_params_t const * params, DecodeOperatingContext const * context) +{ + auto const& diagnosticParams = params ? *params : dec_data.params; + m_decoderDiagActive=true; + m_decoderDiagActiveSequence=++m_decoderDiagSequence; + m_decoderDiagElapsedTimer.start(); + m_decoderDiagProgressTimer.start(); + m_decoderDiagStartMode=context ? context->mode : m_mode; + m_decoderDiagStartTRperiod=context ? context->trPeriod : m_TRperiod; + m_decoderDiagStartIhsym=params ? diagnosticParams.nzhsym : m_ihsym; + m_decoderDiagStartHsymStop=params ? diagnosticParams.nzhsym : m_hsymStop; + m_decoderDiagStartNzhsym=diagnosticParams.nzhsym; + m_decoderDiagStartNewdat=diagnosticParams.newdat; + m_decoderDiagStartNagain=diagnosticParams.nagain; + m_decoderDiagStartNdiskdat=diagnosticParams.ndiskdat; + m_decoderDiagProgressCount=0; + m_decoderDiagBusyRequestLogged=false; + m_decoderDiagOverrunLogged=false; + m_decoderDiagHardHangLogged=false; + m_decoderDiagAbnormalClear=false; } -void MainWindow::decodeDone () +void MainWindow::markDecoderProgress() +{ + if(m_decoderDiagActive) m_decoderDiagProgressTimer.restart(); +} + +void MainWindow::logDecoderBusyRequest(QString const& reason) +{ + if(!m_decoderDiagActive || m_decoderDiagBusyRequestLogged) return; + + qWarning() << "Decoder busy; decode request skipped" + << "reason:" << reason + << "seq:" << m_decoderDiagActiveSequence + << "mode:" << m_decoderDiagStartMode + << "elapsedMs:" << decoderDiagnosticElapsedMs() + << "currentMode:" << m_mode + << "currentIhsym:" << m_ihsym + << "startIhsym:" << m_decoderDiagStartIhsym + << "hsymStop:" << m_decoderDiagStartHsymStop + << "nzhsym:" << m_decoderDiagStartNzhsym; + m_decoderDiagBusyRequestLogged=true; +} + +void MainWindow::logDecoderProgress() +{ + if(DecodeOwner::Jt9 != m_decodeOwner || !m_decoderDiagActive) return; + + if (DecoderIpc::hasUsableSize (mem_jt9->size ()) && mem_jt9->data ()) + { + auto const * shared = reinterpret_cast<shared_dec_data_t const *> ( + mem_jt9->constData ()); + if (DECODER_IPC_VERSION == DecoderIpc::protocolVersion (*shared) + && m_activeJt9Decode.generation == DecoderIpc::generation (*shared)) + { + auto const progress = DecoderIpc::progress (*shared); + if (progress != m_decoderDiagProgressCount) + { + m_decoderDiagProgressCount = progress; + markDecoderProgress (); + } + } + } + + auto const elapsedMs = decoderDiagnosticElapsedMs(); + if(elapsedMs < 0) return; + + auto const overrunMs = static_cast<qint64>(1.25 * m_decoderDiagStartTRperiod * 1000.0); + if(!m_decoderDiagOverrunLogged && overrunMs > 0 && elapsedMs >= overrunMs) { + qWarning() << "Decoder overrun" + << "seq:" << m_decoderDiagActiveSequence + << "mode:" << m_decoderDiagStartMode + << "elapsedMs:" << elapsedMs + << "thresholdMs:" << overrunMs + << "TRperiod:" << m_decoderDiagStartTRperiod + << "currentIhsym:" << m_ihsym + << "startIhsym:" << m_decoderDiagStartIhsym + << "hsymStop:" << m_decoderDiagStartHsymStop + << "nzhsym:" << m_decoderDiagStartNzhsym; + m_decoderDiagOverrunLogged=true; + } + + auto const hardHangMs = decoderRequestDeadlineMs (); + auto const idleMs = decoderDiagnosticIdleMs (); + if(!m_decoderDiagHardHangLogged && idleMs >= hardHangMs) { + qWarning() << "Decoder hard-hang candidate" + << "seq:" << m_decoderDiagActiveSequence + << "mode:" << m_decoderDiagStartMode + << "elapsedMs:" << elapsedMs + << "idleMs:" << idleMs + << "thresholdMs:" << hardHangMs + << "TRperiod:" << m_decoderDiagStartTRperiod + << "currentMode:" << m_mode + << "currentIhsym:" << m_ihsym + << "startIhsym:" << m_decoderDiagStartIhsym + << "hsymStop:" << m_decoderDiagStartHsymStop + << "nzhsym:" << m_decoderDiagStartNzhsym; + if (proc_jt9.canReadLine ()) + { + readFromStdout (); + if (DecodeOwner::Jt9 != m_decodeOwner || !m_decoderDiagActive) return; + if (!decoderRequestDeadlineExpired ()) return; + } + m_decoderDiagHardHangLogged=true; + requestDecoderRestart ("decoder hard timeout"); + } +} + +void MainWindow::logDecoderAbnormalClear(QString const& reason) +{ + if(!m_decoderDiagActive) return; + + qWarning() << "Clearing decoder busy status" + << "reason:" << reason + << "seq:" << m_decoderDiagActiveSequence + << "mode:" << m_decoderDiagStartMode + << "elapsedMs:" << decoderDiagnosticElapsedMs() + << "overrunLogged:" << m_decoderDiagOverrunLogged + << "hardHangLogged:" << m_decoderDiagHardHangLogged + << "currentMode:" << m_mode + << "currentIhsym:" << m_ihsym + << "startIhsym:" << m_decoderDiagStartIhsym + << "hsymStop:" << m_decoderDiagStartHsymStop + << "nzhsym:" << m_decoderDiagStartNzhsym; + m_decoderDiagAbnormalClear=true; +} + +void MainWindow::finishDecoderDiagnostic() +{ + if(!m_decoderDiagActive) return; + + auto const now = QDateTime::currentDateTimeUtc(); + auto const elapsedMs = decoderDiagnosticElapsedMs(); + auto const lastSample = m_decoderDiagLastSampleUtc.value(m_decoderDiagStartMode); + auto const delayed = m_decoderDiagBusyRequestLogged || m_decoderDiagOverrunLogged || m_decoderDiagHardHangLogged; + if(!m_decoderDiagAbnormalClear && delayed) { + qWarning() << "Delayed decoder completed" + << "seq:" << m_decoderDiagActiveSequence + << "mode:" << m_decoderDiagStartMode + << "elapsedMs:" << elapsedMs + << "decodes:" << m_nDecodes + << "decoded:" << m_bDecoded + << "busyRequestLogged:" << m_decoderDiagBusyRequestLogged + << "overrunLogged:" << m_decoderDiagOverrunLogged + << "hardHangLogged:" << m_decoderDiagHardHangLogged + << "TRperiod:" << m_decoderDiagStartTRperiod + << "currentMode:" << m_mode + << "currentIhsym:" << m_ihsym + << "startIhsym:" << m_decoderDiagStartIhsym + << "hsymStop:" << m_decoderDiagStartHsymStop + << "nzhsym:" << m_decoderDiagStartNzhsym; + } else if(!m_decoderDiagAbnormalClear && + (!lastSample.isValid() || lastSample.msecsTo(now) >= 5 * 60 * 1000)) { + qInfo() << "Decoder completion sample" + << "seq:" << m_decoderDiagActiveSequence + << "mode:" << m_decoderDiagStartMode + << "elapsedMs:" << elapsedMs + << "decodes:" << m_nDecodes + << "decoded:" << m_bDecoded + << "TRperiod:" << m_decoderDiagStartTRperiod + << "currentMode:" << m_mode + << "currentIhsym:" << m_ihsym + << "startIhsym:" << m_decoderDiagStartIhsym + << "hsymStop:" << m_decoderDiagStartHsymStop + << "nzhsym:" << m_decoderDiagStartNzhsym + << "newdat:" << m_decoderDiagStartNewdat + << "nagain:" << m_decoderDiagStartNagain + << "ndiskdat:" << m_decoderDiagStartNdiskdat; + m_decoderDiagLastSampleUtc[m_decoderDiagStartMode]=now; + } + + m_decoderDiagActive=false; + m_decoderDiagBusyRequestLogged=false; + m_decoderDiagOverrunLogged=false; + m_decoderDiagHardHangLogged=false; + m_decoderDiagAbnormalClear=false; +} + +void MainWindow::clearHungDecoderStatus(QString const& reason) +{ + if(DecodeOwner::Jt9 != m_decodeOwner) return; + recoverDecoderAtBoundary (reason, true); +} + +void MainWindow::recoverDecoderAtBoundary (QString const& reason, bool manual) +{ + if (DecodeOwner::Jt9 != m_decodeOwner) return; + if (!manual && !decoderRequestDeadlineExpired ()) + { + logDecoderBusyRequest (reason); + return; + } + if (proc_jt9.canReadLine ()) + { + readFromStdout (); + if (DecodeOwner::Jt9 != m_decodeOwner) return; + } + requestDecoderRestart (reason); +} + +void MainWindow::finishDecodeUi () { if(m_mode=="Q65") m_wideGraph->drawRed(0,0); if ("FST4W" == m_mode) @@ -5714,14 +6361,11 @@ void MainWindow::decodeDone () dec_data.params.ndiskdat=0; m_nclearave=0; ui->DecodeButton->setChecked (false); - decodeBusy(false); m_RxLog=0; if(SpecOp::FOX == m_specOp) { houndCallers(); - if(ui->cbWorkDupes->isChecked()) QTimer::singleShot (5000, [=] {band_activity_cleared();}); + if(ui->cbWorkDupes->isChecked()) QTimer::singleShot (5000, this, [=] {band_activity_cleared();}); } - to_jt9(m_ihsym,-1,1); //Tell jt9 we know it has finished - m_startAnother=m_loopall; if(m_bNoMoreFiles) { MessageBox::information_message(this, tr("No more files to open.")); @@ -5752,27 +6396,35 @@ void MainWindow::refreshPileupList() // Update the ActiveStations display for Q65 pileup situation... int nlist=0; char list[2000]; - char line[36]; + char line[37]; list[0]=0; auto fname {QDir::toNativeSeparators(m_config.writeable_data_dir().absoluteFilePath("tsil.3q"))}; get_q3list_(const_cast<char *> (fname.toLatin1().constData()), &m_diskData, &nlist, &list[0], (FCL)fname.length(), (FCL)2000); QString t=""; QString t0=""; - for(int i=0; i<nlist; i++) { - memcpy(line,&list[36*i],36); - t0=QString::fromLatin1(line)+"\n"; + std::fill(m_callers.begin(), m_callers.end(), QString {}); + for(int i=0; i<qMin(nlist, MaxQ65PileupCallers); i++) { + memcpy(line,&list[37*i],37); + + // Callsign is at offset 11 (6 chars); the final byte is the otherwise-unused terminating char(0), repurposed here for '#'. + QString const call = QString::fromLatin1(line + 11, 6).trimmed (); + if (m_q65PileupCopiedCallers.contains (call)) { + line[36] = '#'; + } + + t0=QString::fromLatin1(line, sizeof line)+"\n"; m_callers[i]=t0; t+=t0; } m_ActiveStationsWidget->setClickOK(false); - m_ActiveStationsWidget->displayRecentStations("Q65-pileup",t); + m_ActiveStationsWidget->displayRecentStations(ActiveStations::DisplayMode::Q65Pileup,t); m_ActiveStationsWidget->setClickOK(true); } void MainWindow::read_log() { - static QFile f {QDir {QStandardPaths::writableLocation (QStandardPaths::DataLocation)}.absoluteFilePath ("wsjtx.log")}; + QFile f {writable_file_path (m_config.writeable_data_dir (), "wsjtx.log")}; f.open(QIODevice::ReadOnly); if(f.isOpen()) { QTextStream in(&f); @@ -5794,161 +6446,6 @@ void MainWindow::read_log() } } -void MainWindow::ARRL_Digi_Update(DecodedText dt) -{ - if(m_mode=="Q65") { - m_fetched=0; - readWidebandDecodes(); - return; - } - - // Extract information relevant for the ARRL Digi contest - QString deCall; - QString deGrid; - dt.deCallAndGrid(/*out*/deCall,deGrid); - ActiveCall ac; - RecentCall rc; - - if(deGrid.contains(grid_regexp)) { - if(!m_activeCall.contains(deCall) or deGrid!=m_activeCall.value(deCall).grid4) { - // Transmitting station's call is not already in QMap "m_activeCall", or grid has changed. - // Insert the call, grid, and associated fixed data into the list. - - double utch=0.0; - int nAz,nEl,nDmiles,nDkm,nHotAz,nHotABetter; - QString my_Grid = m_config.my_grid(); - if (my_Grid.length() < 5) my_Grid = m_config.my_grid().left(4)+"mm"; - QString de_Grid= deGrid.left(4)+"mm"; - azdist_(const_cast <char *> (my_Grid.toLatin1().constData()), - const_cast <char *> (de_Grid.toLatin1().constData()),&utch, - &nAz,&nEl,&nDmiles,&nDkm,&nHotAz,&nHotABetter,(FCL)6,(FCL)6); - int points=nDkm/500; - if(nDkm > 500*points) points += 1; - points += 1; - ac.grid4=deGrid; - ac.bands="......."; - ac.az=nAz; - ac.points=points; - m_activeCall[deCall]=ac; - } - } - - m_points=-1; - if(m_activeCall.contains(deCall)) { - -// Don't display stations we already worked on this band. - QString band=m_config.bands()->find(m_freqNominal); - if(band=="160m" and m_activeCall[deCall].bands.indexOf("a")>=0) {m_recentCall.remove(deCall); return;} - if(band=="80m" and m_activeCall[deCall].bands.indexOf("b")>=0) {m_recentCall.remove(deCall); return;} - if(band=="40m" and m_activeCall[deCall].bands.indexOf("c")>=0) {m_recentCall.remove(deCall); return;} - if(band=="20m" and m_activeCall[deCall].bands.indexOf("d")>=0) {m_recentCall.remove(deCall); return;} - if(band=="15m" and m_activeCall[deCall].bands.indexOf("e")>=0) {m_recentCall.remove(deCall); return;} - if(band=="10m" and m_activeCall[deCall].bands.indexOf("f")>=0) {m_recentCall.remove(deCall); return;} - if(band=="6m" and m_activeCall[deCall].bands.indexOf("g")>=0) {m_recentCall.remove(deCall); return;} - - // Update the variable data for this deCall - rc.dialFreq=m_freqNominal; - rc.audioFreq=dt.frequencyOffset(); - rc.snr=dt.snr(); - m_latestDecodeTime=dt.timeInSeconds(); - rc.txEven = (m_latestDecodeTime % int(2*m_TRperiod)) > 0; - rc.ready2call=false; - bool bCQ=dt.messageWords()[0].left(3)=="CQ "; - if(bCQ or deGrid=="RR73" or deGrid=="73") rc.ready2call=true; - rc.decodeTime=m_latestDecodeTime; - m_recentCall[deCall]=rc; - m_points=m_activeCall.value(deCall).points; - } - updateRate(); -} - -void MainWindow::ARRL_Digi_Display() -{ - if(m_mode=="Q65") { - m_fetched=0; - readWidebandDecodes(); - return; - } - if (m_mode == "Fox Mode") { // ARRL_Digi_Display can be shown for other modes - if (m_ActiveStationsWidget != NULL) { - m_ActiveStationsWidget->setClickOK(true); - } - return; - } - QMutableMapIterator<QString,RecentCall> icall(m_recentCall); - QString deCall,deGrid; - int age=0; - int i=0; - int maxAge=m_ActiveStationsWidget->maxAge(); - int points=0; - int maxPoints=0; - int indx[1000]; - float pts[1000]; - QStringList list; - - while (icall.hasNext()) { - icall.next(); - deCall=icall.key(); - age=int((m_latestDecodeTime - icall.value().decodeTime)/m_TRperiod + 0.5); - if(age<0) age=age + int(86400/m_TRperiod); - int itx=1; - if(icall.value().txEven) itx=0; - int snr=icall.value().snr; - int freq=icall.value().audioFreq; - if(age>maxAge) { - icall.remove(); - } else { - bool bReady=false; - if(age==0 and m_recentCall.value(deCall).ready2call) bReady=true; - - QString bands=m_activeCall[deCall].bands; - bool bWorkedOnBand=false; - if(m_currentBand=="160m" and bands.mid(0,1)!=".") bWorkedOnBand=true; - if(m_currentBand=="80m" and bands.mid(1,1)!=".") bWorkedOnBand=true; - if(m_currentBand=="40m" and bands.mid(2,1)!=".") bWorkedOnBand=true; - if(m_currentBand=="20m" and bands.mid(3,1)!=".") bWorkedOnBand=true; - if(m_currentBand=="15m" and bands.mid(4,1)!=".") bWorkedOnBand=true; - if(m_currentBand=="10m" and bands.mid(5,1)!=".") bWorkedOnBand=true; - if(m_currentBand=="6m" and bands.mid(6,1)!=".") bWorkedOnBand=true; - - if((bReady or !m_ActiveStationsWidget->readyOnly()) and !bWorkedOnBand) { - i++; - int az=m_activeCall[deCall].az; - deGrid=m_activeCall[deCall].grid4; - points=m_activeCall[deCall].points; - if(points>maxPoints) maxPoints=points; - float x=float(age)/(maxAge+1); - if(x>1.0) x=0; - pts[i-1]=points - x; - QString t1; - if(!bReady) t1 = t1.asprintf(" %3d %+2.2d %4d %1d %2d %4d",az,snr,freq,itx,age,points); - if(bReady) t1 = t1.asprintf(" %3d %+2.2d %4d %1d %2d*%4d",az,snr,freq,itx,age,points); -// t1 = (deCall + " ").left(6) + " " + m_activeCall[deCall].grid4 + t1 + " " + bands; - t1 = (deCall + " ").left(6) + " " + m_activeCall[deCall].grid4 + t1; - list.append(t1); - } - } - } - if(i==0) return; - int jz=i; - m_ActiveStationsWidget->setClickOK(false); - int maxRecent=qMin(i,m_ActiveStationsWidget->maxRecent()); - indexx_(pts,&jz,indx); - QString t; - i=0; - for(int j=jz-1; j>=0; j--) { - int k=indx[j]-1; - m_ready2call[i]=list[k]; - i++; - QString t1=QString::number(i) + ". "; - if(i<10) t1=" " + t1; - t += (t1 + list[k] + "\n"); - if(i>=maxRecent) break; - } - bool is_fox_mode = (m_mode=="FT8" && m_specOp == SpecOp::FOX); - if(m_ActiveStationsWidget!=NULL && !is_fox_mode) m_ActiveStationsWidget->displayRecentStations(m_mode,t); - m_ActiveStationsWidget->setClickOK(true); -} void MainWindow::queueActiveWindowHound2(QString line) { // Active Window shows what's going on outside of current F/H display rules (calling below 1000Hz e.g.) @@ -5959,15 +6456,15 @@ void MainWindow::queueActiveWindowHound2(QString line) { // make sure our call is the first in the list, or the station is CQing (not a directed CQ) if ( (w.size() > 7) && (w[5] == m_config.my_callsign() || w[5] == "<"+m_config.my_callsign()+">" || w[5]=="CQ") && - ( w[7].contains(grid_regexp) || w[7].contains(non_r_db_regexp) )){ + ( w[7].contains(MainWindow::grid_regexp) || w[7].contains(MainWindow::non_r_db_regexp) )){ QString caller = w[6]; QString grid = ""; QString db = w[1]; int db_i = w[1].toInt(); db = (db_i >=0 ? "+":"") + QStringLiteral("%1").arg(db_i, (db_i >=0 ? 2:3), 10, QLatin1Char('0')); // +00, -01 etc. // houndcall rpt grid - if (w[7].contains(grid_regexp)) grid = w[7]; - if (w[7].contains(non_r_db_regexp)) { + if (w[7].contains(MainWindow::grid_regexp)) grid = w[7]; + if (w[7].contains(MainWindow::non_r_db_regexp)) { LOG_INFO(QString("ActiveStations Window click: %1 called with signal report %2").arg(caller).arg(w[7])); } if (caller.length() > 2) { @@ -6004,11 +6501,13 @@ void MainWindow::callSandP2(int n) m_specOp=m_config.special_op_id(); bool bCtrl = (n<0); n=qAbs(n)-1; + if(n<0 || n>=int(m_ready2call.size())) return; if(m_mode!="Q65" and m_ready2call[n]=="") return; QStringList w=m_ready2call[n].split(' ', SkipEmptyParts); - if(m_mode=="Q65" and m_specOp==SpecOp::Q65_PILEUP and n < 40) { + if(m_mode=="Q65" and m_specOp==SpecOp::Q65_PILEUP and n < MaxQ65PileupCallers) { // This code is for 6m EME DXpedition operator w=m_callers[n].split(' ', SkipEmptyParts); + if(w.size() < 4) return; m_deCall=w[2]; if(bCtrl) { // Remove this call from q3list. @@ -6017,10 +6516,9 @@ void MainWindow::callSandP2(int n) return; } m_deGrid=w[3]; - m_bDoubleClicked=true; //### needed? + m_bDoubleClicked=true; m_txFirst=true; - ui->dxCallEntry->setText(m_deCall); - ui->dxGridEntry->setText(m_deGrid); + setDXInfo(m_deCall, m_deGrid); ui->txFirstCheckBox->setChecked(m_txFirst); genStdMsgs("-22"); setTxMsg(3); @@ -6029,46 +6527,39 @@ void MainWindow::callSandP2(int n) return; } + bool frequency_changed = false; if(m_mode=="Q65") { - if(!bCtrl) { //Do not reset m_freqNominal if CTRL was down + if(w.size() < 7) return; + if(!bCtrl) { //Do not reset m_operatingFrequency.rx () if CTRL was down double kHz=w[1].toDouble(); - int nMHz=m_freqNominal/1000000; - m_freqNominal=(nMHz*1000 + kHz)* 1000; + int nMHz=m_operatingFrequency.rx ()/1000000; + frequency_changed = requestNominalFrequencyChange ( + (nMHz*1000 + kHz)* 1000, FrequencyRequestOrigin::User); } - m_deCall=w[4]; - m_deGrid=w[5]; - m_txFirst=(w[6]=="0"); -// ui->TxFreqSpinBox->setValue(1500); + applyQ65StationSelection ({w[4], w[5], w[3], w[2], w[6]=="0"}); } else { + if(w.size() < 6) return; m_deCall=w[0]; m_deGrid=w[1]; ui->RxFreqSpinBox->setValue(w[4].toInt()); m_txFirst = (w[5]=="0"); - } - - if(w[3].left(2)=="30") { - ui->sbTR->setValue(30); - } else { - ui->sbTR->setValue(60); - } - if(w[3].right(1)=="A") ui->sbSubmode->setValue(0); - if(w[3].right(1)=="B") ui->sbSubmode->setValue(1); - if(w[3].right(1)=="C") ui->sbSubmode->setValue(2); - if(w[3].right(1)=="D") ui->sbSubmode->setValue(3); - if(w[3].right(1)=="E") ui->sbSubmode->setValue(4); - if(w[3].right(1)=="F") ui->sbSubmode->setValue(5); - - m_bDoubleClicked=true; //### needed? - ui->dxCallEntry->setText(m_deCall); - ui->dxGridEntry->setText(m_deGrid); - if(m_mode=="Q65") { - ui->rptSpinBox->setValue(w[2].toInt()); - genStdMsgs(w[2]); - } else { + if(w[3].left(2)=="30") { + ui->sbTR->setValue(30); + } else { + ui->sbTR->setValue(60); + } + if(w[3].right(1)=="A") ui->sbSubmode->setValue(0); + if(w[3].right(1)=="B") ui->sbSubmode->setValue(1); + if(w[3].right(1)=="C") ui->sbSubmode->setValue(2); + if(w[3].right(1)=="D") ui->sbSubmode->setValue(3); + if(w[3].right(1)=="E") ui->sbSubmode->setValue(4); + if(w[3].right(1)=="F") ui->sbSubmode->setValue(5); + m_bDoubleClicked=true; + setDXInfo(m_deCall, m_deGrid); genStdMsgs(w[3]); + setTxMsg(1); + ui->txFirstCheckBox->setChecked(m_txFirst); } - setTxMsg(1); - ui->txFirstCheckBox->setChecked(m_txFirst); static qint64 ms0=0; qint64 ms=QDateTime::currentMSecsSinceEpoch(); if(SpecOp::NONE==m_specOp) { @@ -6078,8 +6569,10 @@ void MainWindow::callSandP2(int n) ui->autoButton->click(); // Enable Tx again, on double click } if(m_mode=="Q65" && m_ActiveStationsWidget!=NULL) { - setRig (m_freqNominal); - setXIT (ui->TxFreqSpinBox->value ()); + if (frequency_changed || (bCtrl && reapplyCurrentRigFrequencyCorrection ())) + { + setXIT (ui->TxFreqSpinBox->value ()); + } } } else { if(ui->autoButton->isChecked()) { @@ -6092,10 +6585,64 @@ void MainWindow::callSandP2(int n) if(m_transmitting) m_restart=true; } +void MainWindow::applyQ65StationSelection (Q65StationSelection const& selection) +{ + m_deCall=selection.call; + m_deGrid=selection.grid; + m_txFirst=selection.txFirst; + ui->sbTR->setValue (selection.submode.startsWith ("30") ? 30 : 60); + auto const submode = QString {"ABCDEF"}.indexOf (selection.submode.right (1)); + if (submode >= 0) ui->sbSubmode->setValue (submode); + + m_bDoubleClicked=true; + setDXInfo(m_deCall, m_deGrid); + ui->rptSpinBox->setValue(selection.report.toInt()); + genStdMsgs(selection.report); + setTxMsg(1); + ui->txFirstCheckBox->setChecked(m_txFirst); +} + +void MainWindow::qmapCallSandP(QMapDecodeRecord const& record, bool doubleClick) +{ + if (m_mode!="Q65" || SpecOp::NONE!=m_specOp + || !LiveCQ::isValidCallsign (record.callsign)) return; + + auto const clickPolicy = qmapClickPolicy ( + doubleClick, false, ui->autoButton->isChecked (), m_transmitting); + if (clickPolicy.disarmBeforeQsy) { + ui->autoButton->click(); + } + + int nMHz=m_operatingFrequency.rx ()/1000000; + Frequency const frequency = (nMHz*1000 + record.scheduledFrequencyKHz)*1000; + bool const frequency_changed = requestNominalFrequencyChange ( + frequency, FrequencyRequestOrigin::User); + auto const completedClickPolicy = qmapClickPolicy ( + doubleClick, frequency_changed, ui->autoButton->isChecked (), m_transmitting); + QString submode=record.submode; + int odd=0; + if(submode.left(2)=="30" and (record.secondsSinceMidnight%60)==0) odd=1; + if(submode.left(2)=="60" and (record.secondsSinceMidnight%120)==0) odd=1; + auto grid = record.grid; + if(grid.isEmpty ()) grid = m_EMECall.value (record.callsign).grid4; + applyQ65StationSelection ({record.callsign, grid, submode, + QString::number (record.snr), odd==0}); + + if (frequency_changed) setXIT(ui->TxFreqSpinBox->value()); + + if(completedClickPolicy.enableAutoTx) { + if(!ui->autoButton->isChecked()) ui->autoButton->click(); + } else if(completedClickPolicy.disableAutoTx && ui->autoButton->isChecked()) { + // Never carry an active transmission over to a newly selected station. + ui->autoButton->click(); + } + if(completedClickPolicy.restartTransmission) m_restart=true; +} + void MainWindow::activeWorked(QString call, QString band) { - QString bands=m_activeCall[call].bands; - QByteArray ba=bands.toLatin1(); + auto& activeCall = m_activeCall[call]; + QByteArray ba=activeCall.bands.toLatin1().leftJustified(7, '.'); if(band=="160m") ba[0]='a'; if(band=="80m") ba[1]='b'; if(band=="40m") ba[2]='c'; @@ -6103,212 +6650,235 @@ void MainWindow::activeWorked(QString call, QString band) if(band=="15m") ba[4]='e'; if(band=="10m") ba[5]='f'; if(band=="6m") ba[6]='g'; - m_activeCall[call].bands=QString::fromLatin1(ba); + activeCall.bands=QString::fromLatin1(ba); } -void MainWindow::readFromStdout() //readFromStdout +bool MainWindow::handleDecoderOutputEvent (DecoderOutputFramer::Event const& event, + bool& decodeCompleted) { - bool bDisplayPoints = false; - filtered = false; - ignored = false; - m_muted = false; - QString all_decodes; - if(m_ActiveStationsWidget!=NULL) { - bDisplayPoints=(m_mode=="FT4" or m_mode=="FT8") and - (m_specOp==SpecOp::ARRL_DIGI or m_ActiveStationsWidget->isVisible()); - } - while(proc_jt9.canReadLine()) { - auto line_read = proc_jt9.readLine (); - - QString the_line = QString(line_read); - if(ui->actionEnable_QSY_Popups->isChecked() || m_qsymonitorWidget) showQSYMessage(the_line); - - if (m_mode == "FT8" and m_specOp == SpecOp::FOX and m_ActiveStationsWidget != NULL) { // see if we should add this to ActiveStations window - if (!m_ActiveStationsWidget->wantedOnly() || - (the_line.contains(" " + m_config.my_callsign() + " ") || - the_line.contains(" <" + m_config.my_callsign() + "> "))) - all_decodes.append(line_read); - } - if (auto p = std::strpbrk (line_read.constData (), "\n\r")) { - // truncate before line ending chars - line_read = line_read.left (p - line_read.constData ()); - } - if(bDisplayPoints) line_read=line_read.replace("a7"," "); - bool haveFSpread {false}; - bool blockUDP {false}; // allow udp spotting (JTAlert) for all non-filtered messages - bool block_right_display {false}; - float fSpread {0.}; - if (m_mode.startsWith ("FST4")) - { - auto text = line_read.mid (64, 6).trimmed (); - if (text.size ()) - { - fSpread = text.toFloat (&haveFSpread); - line_read = line_read.left (64); - } - auto const& cs = m_config.my_callsign ().toLocal8Bit (); - if ("FST4W" == m_mode && ui->cbNoOwnCall->isChecked () - && (line_read.contains (" " + cs + " ") - || line_read.contains ("<" + cs + ">"))) { - continue; + if (DecoderOutputFramer::EventType::Record == event.type) + { + if (DecodeOwner::Jt9 != m_decodeOwner + || !m_activeJt9Decode.generation + || event.generation != m_activeJt9Decode.generation) + { + return true; } - } + markDecoderProgress (); + if (!m_activeJt9Decode.obsolete + && !activeDecodeOperatingContextMatchesCurrent ()) + { + m_activeJt9Decode.obsolete = true; + qInfo () << "Discarding obsolete decoder output" + << "generation:" << event.generation; + } + return m_activeJt9Decode.obsolete; + } - QString message0 {QString::fromUtf8(line_read.constData())}; - DecodedText decodedtext0 {QString::fromUtf8(line_read.constData())}; - DecodedText decodedtext {QString::fromUtf8(line_read.constData()).remove("TU; ")}; - - // Don't allow a7 decodes during the first period and for non-contest messages when in any contest mode - if ((!((no_a7_decodes && line_read.contains("a7") && !m_diskData) or (line_read.contains("a7") && SpecOp::NONE!=m_specOp - && !m_diskData && !(line_read.contains(" R ") or line_read.contains("RR73") or line_read.contains("CQ "))))) - - // Filtering out some false decodes, and don't write all.txt for such - // FDR step 1 - and (!((SpecOp::NONE==m_specOp or (m_multithreadFT8 && m_ft8DecoderStart<2)) && - ((m_mode=="FT8" && ((m_multithreadFT8 && m_ft8DecoderStart<2) or m_freqNominal>45000000) && earlyDecodes.contains(line_read.mid(23,19))) // MTD or a7/a8 dupes - or ((SpecOp::NONE==m_specOp && decodedtext.snr() < -12) && (message0.contains("> <") // two hashes - || message0.contains(QRegularExpression {"(\\w+)/P (\\w+)/P "}) // two /P calls - || message0.contains(QRegularExpression {"(\\w+)/R (\\w+)/R "}) // two /R calls - || (message0.contains("/R ") && message0.contains("?")) // insecure /R decodes - || (message0.contains(";") && message0.contains(" R "))))))) // invalid combination - // FDR step 2 - and (!(SpecOp::NONE==m_specOp && ui->actionReduce_false_decodes->isChecked() && m_mode=="FT8" && - ((((message0.contains("/P ") && message0.contains(" R ")) // /P and R - || (message0.contains(";") && message0.contains("/R ")) // ; and /R - || (message0.contains(";") && message0.contains("/P ")) // ; and /P - || (message0.contains("<...>") && message0.contains(" R ")) // hash and R - || (message0.contains("<...>") && message0.contains("/P ")) // hash and /P - || (message0.contains("<...>") && message0.contains(";")) // hash and ; - || message0.contains(QRegularExpression {"\\w\\w\\w\\w\\w\\w\\w\\w"}) // likely invalid callsigns - || message0.contains(QRegularExpression {"\\d\\d\\d \\d\\d\\d"}) // contest messages - || message0.contains("3.") || message0.contains("2.")) // -1.9 < dt < 1.9 - && (decodedtext.snr() < -15)) // for such SNRmin = -15 - or ((message0.contains("/R ") or message0.contains(" R ")) && decodedtext.snr() < -18) // for /R or contest calls SNRmin = -18 - or (((message0.contains("<...>") || message0.contains(";") // unresolved hash and F/H messages - || message0.contains("? a") // ap decodes of low confidence - || message0.contains("/R ") || message0.contains(" R ") // rover and contest callsigns - || decodedtext.snr() < -20) // SNR < -20 - && (message0.contains("3.") || message0.contains("2."))))))) // for such -1.9 < dt < 1.9 - ) + if (DecoderOutputFramer::EventType::Malformed == event.type) { - if (m_mode!="FT8" and m_mode!="FT4" and !m_mode.startsWith ("FST4") and m_mode!="Q65") { - //Pad 22-char msg to at least 37 chars - line_read = line_read.left(44) + " " + line_read.mid(44); - } - bool bAvgMsg=false; - int navg=0; - - if(line_read.indexOf("<DecodeFinished>") >= 0) { - m_bDecoded = line_read.mid(20).trimmed().toInt() > 0; - int n=line_read.trimmed().size(); - int n2=line_read.trimmed().mid(n-7).toInt(); - int n0=n2/1000; - int n1=n2%1000; - if(m_mode=="Q65") { - ndecodes_label.setText(QString {"%1 %2"}.arg (n0).arg (n1)); - } else { - if(m_nDecodes==0 && !(m_multithreadFT8 && m_diskData)) ndecodes_label.setText("0"); - } - decodeDone (); - return; - } else { - m_nDecodes+=1; - if(m_mode!="Q65") ndecodes_label.setText(QString::number(m_nDecodes)); - if(m_mode=="JT4" or m_mode=="JT65" or m_mode=="Q65") { - //### Do something about Q65 here ? ### - int nf=line_read.indexOf("f"); - if(nf>0) { - navg=line_read.mid(nf+1,1).toInt(); - if(line_read.indexOf("f*")>0) navg=10; + qWarning () << "Ignoring malformed or unframed decoder output:" + << event.rawLine.trimmed (); + if (event.rawLine.startsWith ("<DecodeStarted>") + || event.rawLine.startsWith ("<DecodeFinished>")) + { + if (Jt9ProcessPhase::Ready == m_jt9ProcessPhase + && DecodeOwner::Jt9 == m_decodeOwner) + { + requestDecoderRestart ("malformed decoder output frame"); + } } - int nd=-1; - if(nf<0) nd=line_read.indexOf("d"); - if(nd>0) { - navg=line_read.mid(nd+2,1).toInt(); - if(line_read.mid(nd+2,1)=="*") navg=10; + else + { + markDecoderProgress (); } - int na=-1; - if(nf<0 and nd<0) na=line_read.indexOf("a"); - if(na>0) { - navg=line_read.mid(na+2,1).toInt(); - if(line_read.mid(na+2,1)=="*") navg=10; + return true; + } + + if (DecoderOutputFramer::EventType::Started == event.type) + { + auto const authoritative = Jt9ProcessPhase::Ready == m_jt9ProcessPhase + && DecodeOwner::Jt9 == m_decodeOwner + && m_activeJt9Decode.generation + && event.generation == m_activeJt9Decode.generation; + if (!authoritative) + { + qWarning () << "Quarantining stale decoder output" + << "generation:" << event.generation + << "activeGeneration:" << m_activeJt9Decode.generation; + if (Jt9ProcessPhase::Ready == m_jt9ProcessPhase + && DecodeOwner::Jt9 == m_decodeOwner) + { + requestDecoderRestart ("decoder output generation mismatch"); + } } - int nq=-1; - if(nf<0 and nd<0 and na<0) nq=line_read.indexOf("q"); - if(nq>0) { - navg=line_read.mid(nq+2,1).toInt(); - if(line_read.mid(nq+2,1)=="*") navg=10; + else + { + markDecoderProgress (); } - if(navg>=2) bAvgMsg=true; - } - write_all("Rx", line_read.trimmed()); - } // Filtering out some false decodes, and don't write all.txt for such + return true; + } + + auto const completion = event.completion; + auto const authoritative = DecodeOwner::Jt9 == m_decodeOwner + && m_activeJt9Decode.generation + && event.generation == m_activeJt9Decode.generation; + if (!authoritative) + { + qWarning () << "Ignoring stale decoder completion" + << "generation:" << completion.generation; + return true; + } + + if (!m_activeJt9Decode.obsolete + && !activeDecodeOperatingContextMatchesCurrent ()) + { + m_activeJt9Decode.obsolete = true; + qInfo () << "Discarding obsolete decoder completion" + << "generation:" << event.generation; + } - if ("FST4W" == m_mode) + bool consumed {false}; + int state {-1}; + if (DecoderIpc::hasUsableSize (mem_jt9->size ()) + && mem_jt9->data ()) + { + auto * shared = reinterpret_cast<shared_dec_data_t *> (mem_jt9->data ()); + if (DECODER_IPC_VERSION == DecoderIpc::protocolVersion (*shared) + && completion.generation == DecoderIpc::generation (*shared)) { - uploadWSPRSpots (true, line_read); + state = DecoderIpc::state (*shared); + consumed = DecoderIpc::consume (*shared, completion.generation); } + } + if (!consumed) + { + qWarning () << "Unable to consume matching decoder completion" + << "generation:" << completion.generation + << "state:" << state; + requestDecoderRestart ("matching decoder completion could not be consumed"); + return true; + } - // Check validity of callsigns if "Reduce false decodes" is checked // EXPERIMENTAL FOR NOW - if (m_mode=="FT8" && !m_multithreadFT8 && ui->actionReduce_false_decodes->isChecked() && decodedtext.snr() < -20) { - bool notInALLCALL7 = false; - QString deCall; - QString deGrid; - decodedtext.deCallAndGrid(/*out*/deCall,deGrid); - QStringList word; - word=decodedtext.string().mid(24).replace("<","").replace(">","").replace("/P","").replace("/R","").replace("/QRP","").replace("/5W","").split(" ",SkipEmptyParts); - - // check file ALLCALL7.TXT - if (deCall!="TNX" && deCall!="73" && deCall!="GL" && deCall!="HNY" && deCall!="TU" && !deCall.left(4).contains("/") - && !decodedtext.string().contains("<...>") && !ALLCALL7.contains(deCall)) { - notInALLCALL7 = true; -// ui->decodedTextBrowser->insertText("deCall not in ALLCALL7.TXT"); - } - if (!ALLCALL7.contains(word[0]) && !(decodedtext.string().contains(" CQ ") or decodedtext.string().contains("TNX") - or decodedtext.string().contains("...") or decodedtext.string().contains("HNY") or decodedtext.string().contains("QSY") - or decodedtext.string().contains("73 ") or decodedtext.string().contains("GL ") or decodedtext.string().contains("PSE") - or decodedtext.string().contains("/") or decodedtext.string().contains("<...>"))) { - notInALLCALL7 = true; -// ui->decodedTextBrowser->insertText("word0 not in ALLCALL7.TXT"); - } + if (!m_activeJt9Decode.obsolete) + { + m_bDecoded = completion.decoded > 0; + auto const& context = m_activeJt9Decode.context; + if(context.mode=="Q65") { + auto const n0 = completion.average / 1000; + auto const n1 = completion.average % 1000; + ndecodes_label.setText(QString {"%1 %2"}.arg (n0).arg (n1)); + } else if(m_nDecodes==0 && !(context.multithreadFt8 && context.diskData)) { + ndecodes_label.setText("0"); + } + } + m_activeJt9Decode.generation = 0; + decodeCompleted = true; + return true; +} - // check syntax of the two callsigns before we hide such messages - if (notInALLCALL7) { - deCall=deCall.replace("<","").replace(">","").replace("/P","").replace("/R","").replace("/QRP","").replace("/5W",""); - if (deCall!="TNX" && deCall!="73" && deCall!="GL" && deCall!="HNY" && - !(deCall.left(3).contains(QRegularExpression {"\\w\\d\\w"}) or - deCall.left(3).contains(QRegularExpression {"\\d\\w\\d"}) or - deCall.left(3).contains(QRegularExpression {"\\w\\w\\d"}) or - deCall.left(4).contains("/") or decodedtext.string().contains("<...>"))) { -// ui->decodedTextBrowser->insertText("deCall has false syntax"); - filtered = true; - } - if (word[0]!="CQ" && word[0]!="TNX" && word[0]!="73 " && word[0]!="HNY" && word[0]!="QSY" && word[0]!="PSE" && - !(word[0].left(3).contains(QRegularExpression {"\\w\\d\\w"}) or - word[0].left(3).contains(QRegularExpression {"\\d\\w\\d"}) or - word[0].left(3).contains(QRegularExpression {"\\w\\w\\d"}) or - decodedtext.string().contains("/")or decodedtext.string().contains("<...>"))) { -// ui->decodedTextBrowser->insertText("word0 has false syntax"); - filtered = true; - } - } - notInALLCALL7 = false; +void MainWindow::readFromStdout() //readFromStdout +{ + bool decodeCompleted {false}; + auto const decodeContext = m_activeJt9Decode.context; + bool bDisplayPoints = false; + QString all_decodes; + if(m_ActiveStationsWidget!=NULL) { + bDisplayPoints=(decodeContext.mode=="FT4" or decodeContext.mode=="FT8") and + (decodeContext.specOp==SpecOp::ARRL_DIGI or m_ActiveStationsWidget->isVisible()); + } + extern bool no_a7_decodes; + extern QString earlyDecodes; + DecodeOutputPlan::PreparationContext preparationContext; + preparationContext.mode = decodeContext.mode; + preparationContext.specOp = decodeContext.specOp; + preparationContext.myCall = decodeContext.myCall; + preparationContext.qsyEnabled = ui->actionEnable_QSY_Popups->isChecked() || m_qsymonitorWidget; + preparationContext.activeStationsAvailable = m_ActiveStationsWidget != nullptr; + preparationContext.activeStationsWantedOnly = m_ActiveStationsWidget && m_ActiveStationsWidget->wantedOnly(); + preparationContext.displayPoints = bDisplayPoints; + preparationContext.noOwnCall = ui->cbNoOwnCall->isChecked (); + preparationContext.diskData = decodeContext.diskData; + preparationContext.noA7Decodes = no_a7_decodes; + preparationContext.multithreadFt8 = decodeContext.multithreadFt8; + preparationContext.ft8DecoderStart = decodeContext.ft8DecoderStart; + preparationContext.nominalFrequency = decodeContext.periodFrequency; + preparationContext.reduceFalseDecodes = ui->actionReduce_false_decodes->isChecked(); + m_decoderOutputFramer.drain ( + proc_jt9, [this, &all_decodes, &preparationContext, &decodeCompleted, + &decodeContext, bDisplayPoints] + (DecoderOutputFramer::Event const& event) { + if (handleDecoderOutputEvent (event, decodeCompleted)) return; + filtered = false; + ignored = false; + m_muted = false; + auto const raw_line = event.rawLine; +#if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) + Q_EMIT decoderOutputLine (raw_line); +#endif + // earlyDecodes grows as lines are displayed within this batch + preparationContext.earlyDecodes = earlyDecodes; + auto const prepared = DecodeOutputPlan::prepareLine (raw_line, preparationContext); + + bool updateArrlActivity = false; + // Apply raw-line actions before terminal dispositions; accepted-line + // persistence actions run only after Ignore and Finish are handled. + for (auto const& action : prepared.actions) { + if (action.kind == DecodeOutputPlan::ActionKind::ShowQsyMessage) { + showQSYMessage (action.text); + } else if (action.kind == DecodeOutputPlan::ActionKind::AccumulateFoxActivity) { + all_decodes.append (action.text); + } else if (action.kind == DecodeOutputPlan::ActionKind::UpdateArrlActivity) { + updateArrlActivity = true; } + } + if (prepared.disposition != DecodeOutputPlan::LineDisposition::Decode) return; - if(m_mode=="FT8" and SpecOp::FOX == m_specOp and - (decodedtext.string().contains("R+") or decodedtext.string().contains("R-"))) { - auto for_us = decodedtext.string().contains(" " + m_config.my_callsign() + " ") or - decodedtext.string().contains(" "+m_baseCall) or - decodedtext.string().contains(m_baseCall+" ") or - decodedtext.string().contains(" <" + m_config.my_callsign() + "> "); - if(decodedtext.string().contains(" DE ")) for_us=true; //Hound with compound callsign - if(for_us) { - QString houndCall,houndGrid; - decodedtext.deCallAndGrid(/*out*/houndCall,houndGrid); - foxRxSequencer(decodedtext.string(),houndCall,houndGrid); + auto line_read = prepared.normalizedLine; + bool haveFSpread = prepared.haveFrequencySpread; + bool block_right_display {false}; + float fSpread = prepared.frequencySpread; + QString const message0 = prepared.decodedOriginal; + DecodedText decodedtext0 {prepared.decodedOriginal}; + DecodedText const& decodedtext {prepared.logicMessage}; + Q_EMIT decodedMessageProcessed (decodedtext.message ().simplified ()); + + if (m_mode=="Q65" && m_specOp==SpecOp::Q65_PILEUP) { + auto const fields = parseDecodedMessage (decodedtext.message ()); + + // Keep the Active Stations '#' indication current: a later decode from the same caller without '#' removes it. + if (!fields.sender.isEmpty ()) { + if (raw_line.trimmed ().endsWith ('#')) { + m_q65PileupCopiedCallers.insert (fields.sender); + } else { + m_q65PileupCopiedCallers.remove (fields.sender); } } + auto const dx_base_call = Radio::base_callsign (ui->dxCallEntry->text ()); + if (!dx_base_call.isEmpty () && fields.sender == dx_base_call) { + m_q65PileupCopiedLastRxCall = dx_base_call; + } + } + + { + bool const bAvgMsg = prepared.averaged; + + for (auto const& action : prepared.actions) { + if (action.kind == DecodeOutputPlan::ActionKind::IncrementDecodeCount) { + m_nDecodes += 1; + if(decodeContext.mode!="Q65") ndecodes_label.setText(QString::number(m_nDecodes)); + } else if (action.kind == DecodeOutputPlan::ActionKind::WriteAll) { + write_all("Rx", action.text, &decodeContext); + } else if (action.kind == DecodeOutputPlan::ActionKind::UploadWsprSpot) { + uploadWSPRSpots (true, action.text); + } + } + + applyExperimentalFT8Filter(decodedtext, filtered); + + processFoxSignals(decodedtext); + //Left (Band activity) window if(!bAvgMsg) { if(m_mode=="FT8" and SpecOp::FOX == m_specOp) { @@ -6331,508 +6901,42 @@ void MainWindow::readFromStdout() //readFromStdout } #endif DecodedText decodedtext1=decodedtext0; - if ((m_mode=="FT4" or m_mode=="FT8") and bDisplayPoints and decodedtext1.isStandardMessage()) { + if (updateArrlActivity) { ARRL_Digi_Update(decodedtext1); } -#ifdef FOX_OTP - if (SpecOp::HOUND == m_specOp) - { - // Payload formats (from column 24 onward): - // Standard: CALL.OTP e.g. "K8R.920749" - // SuperFox: $VERIFY$ CALL OTP e.g. "$VERIFY$ VP2X/K1JT 920749" - // Callsigns may include '/' and decoder output may contain variable spacing. - static const QRegularExpression stdPayloadRe{ - QStringLiteral("^([A-Z0-9]{2,6})\\.([0-9]{6})$")}; - static const QRegularExpression verifyPayloadRe{ - QStringLiteral("^\\$VERIFY\\$\\s+([A-Z0-9/]{2,13})\\s+([0-9]{6})$")}; + processSFoxVerification(decodedtext0, filtered); - QString const payload = decodedtext0.mid(24, -1).trimmed(); - QString callsign, otp; - unsigned int hz = 0; + QString text = decodedtext.string().replace("<", "").replace(">", ""); - QRegularExpressionMatch payloadMatch = stdPayloadRe.match(payload); - if (payloadMatch.hasMatch()) { - callsign = payloadMatch.captured(1); - otp = payloadMatch.captured(2); - hz = static_cast<unsigned int>(decodedtext0.frequencyOffset()); - } else if (m_config.superFox() && - (payloadMatch = verifyPayloadRe.match(payload)).hasMatch()) { - callsign = payloadMatch.captured(1); - otp = payloadMatch.captured(2); - hz = 750; - } + if (processWaitReplyCall(decodedtext0, DecodedMessageReaction::WaitDecodeSource::SlowDecoder, + &block_right_display) + == DecodedMessageReaction::ReactionDisposition::IgnoreDecode) return; - if (!callsign.isEmpty()) { - if (!m_config.ShowOTP() || otp == QLatin1String("000000")) - filtered = true; + if (!applyFiltering(decodedtext, filtered)) return; - QDateTime verifyDateTime; - if (m_diskData) { - verifyDateTime = m_UTCdiskDateTime; - } else { - verifyDateTime = QDateTime(QDateTime::currentDateTimeUtc().date(), - QTime::fromString(decodedtext0.left(6), "hhmmss")); - } - if (otp != QLatin1String("000000")) { - FoxVerifier *fv = new FoxVerifier(MainWindow::userAgent(), - &m_network_manager, - m_config.OTPUrl(), - callsign, - verifyDateTime, - otp, - hz); - connect(fv, &FoxVerifier::verifyComplete, this, &MainWindow::handleVerifyMsg); - m_verifications << fv; - } - } - } -#endif - - QString text = decodedtext.string().replace("<","").replace(">",""); // for Wait & Reply/Call and filtering - - // FT4 NS (NCCC Sprints): Log QSO after receiving "mycall hiscall R hisgrid" - if (m_mode=="FT4" && SpecOp::NA_VHF==m_specOp && m_config.NCCC_Sprint() && m_hisCall!="" && m_hisGrid!="" && - text.contains(" " + m_config.my_callsign() + " " + m_hisCall + " R " + m_hisGrid.left(4))) { - if (m_config.prompt_to_log() || m_config.autoLog()) logQSOTimer.start(0); - QTimer::singleShot (500, [=] { - on_stopTxButton_clicked(); - }); - } - - // Stop Wait & Call timeout when in QSO with this station - if (ui->DX_Call_Button->isChecked() && m_hisCall!="" && text.contains(" " + m_config.my_callsign() + " " + m_hisCall)) { - stopWCTimer.stop(); // stop any Wait & Call timeout - if (ui->DX_Call_Button->isChecked()) ui->DX_Call_Button->click (); // disable Wait & Call - no_wait_and_call = false; // reset Wait & Call - } - - // Wait & Reply + FT4 NS (NCCC Sprints) reply to incoming RR73 messages - if ((m_mode=="FT8" or m_mode=="FT4" or m_mode=="Q65" or m_mode=="FST4" or m_mode=="JT65" or m_mode=="JT9" or m_mode=="JT4") && m_hisCall!="" - && text.contains(" " + m_config.my_callsign() + " " + m_hisCall) && ((!text.contains("73 ") - && m_config.Wait_features_enabled() && !ui->autoButton->isChecked()) - or (m_mode=="FT4" && SpecOp::NA_VHF==m_specOp && m_config.NCCC_Sprint()))) { - if (SpecOp::HOUND==m_specOp && (text.mid(4,2).contains("15") or text.mid(4,2).contains("45"))) return; // ignore stations calling in the wrong time slot - tx_watchdog (false); - m_bDoubleClicked = true; - processMessage(decodedtext0); - auto_tx_mode(true); - if (m_mode=="FT4" && SpecOp::NA_VHF==m_specOp && m_config.NCCC_Sprint()) { - if (!no_logging) logQSOTimer.start(0); // logging of stations not in contest mode - } else { - if (m_config.Wait_features_enabled()) stopWRTimer.start(int(8000.0*m_TRperiod)); // Wait & Reply Tx max 8*TRperiod - } - } - - // Wait & Call - if (wait_and_call && (m_mode=="FT8" or m_mode=="FT4" or m_mode=="Q65" or m_mode=="FST4" or m_mode=="JT65" or m_mode=="JT9" or m_mode=="JT4") && - m_specOp!=SpecOp::FOX && ui->cbAutoSeq->isChecked() && m_hisCall!="" && !no_wait_and_call && - (text.contains("CQ " + m_hisCall) or text.contains("CQ DX " + m_hisCall) or text.contains(m_hisCall + " RR73") - or text.contains(m_hisCall + " RRR") or text.contains(m_hisCall + " 73")) - && m_config.Wait_features_enabled()) { - if (!text.contains(" " + m_config.my_callsign() + " " + m_hisCall)) - block_right_display = true; // prevent display of first message twice - m_bDoubleClicked = true; - processMessage(decodedtext0); - auto_tx_mode(true); - no_wait_and_call = true; - stopWCTimer.start(int(6200.0*m_TRperiod)); // Wait & Call Tx max 8*TRperiod - } - - // Filtering - QString text2 = ""; - QStringList tw; - if (m_mode == "FT8" or m_mode == "FT4" or m_mode == "Q65" or m_mode == "FST4") { - tw=text.mid(24).split(" ",SkipEmptyParts); - } else { - tw=text.mid(22).split(" ",SkipEmptyParts); - } - if (m_config.filters_for_word2()) { - if (tw.size () < 2) { - text2 = "___"; // prevent segfault errors with free text messages - } else if (tw[1].length() == 2 && tw[1].contains(QRegularExpression{"\\w\\w"})) { // directional calls - if (tw.size () > 2) { - text2 = tw[2]; // for directional calls analyze word 3 for filtering - } else { - text2 = "___"; // prevent segfault errors with free text messages - } - } else { - if (text.contains(";")) { - text2 = tw[3]; // analyze word 4 for filtering of combined messages - } else { - text2 = tw[1]; // otherwise analyze word 2 for filtering - } - } - if (!(SpecOp::NONE==m_specOp && m_config.AlwaysPass () // Always pass messages with keywords from Always Pass list - && ( - (text2.startsWith(m_config.Pass1()) && (m_config.Pass1()!="")) - || (text2.startsWith(m_config.Pass2()) && (m_config.Pass2()!="")) - || (text2.startsWith(m_config.Pass3()) && (m_config.Pass3()!="")) - || (text2.startsWith(m_config.Pass4()) && (m_config.Pass4()!="")) - || (text2.startsWith(m_config.Pass5()) && (m_config.Pass5()!="")) - || (text2.startsWith(m_config.Pass6()) && (m_config.Pass6()!="")) - || (text2.startsWith(m_config.Pass7()) && (m_config.Pass7()!="")) - || (text2.startsWith(m_config.Pass8()) && (m_config.Pass8()!="")) - || (text2.startsWith(m_config.Pass9()) && (m_config.Pass9()!="")) - || (text2.startsWith(m_config.Pass10()) && (m_config.Pass10()!="")) - || (text2.startsWith(m_config.Pass11()) && (m_config.Pass11()!="")) - || (text2.startsWith(m_config.Pass12()) && (m_config.Pass12()!="")) - ))) { - - // Filtering out messages with keywords from Blacklist - if ((SpecOp::NONE==m_specOp or SpecOp::HOUND==m_specOp) && m_config.Blacklisted () - && ( - (text2.startsWith(m_config.Blacklist1()) && (m_config.Blacklist1()!="")) - || (text2.startsWith(m_config.Blacklist2()) && (m_config.Blacklist2()!="")) - || (text2.startsWith(m_config.Blacklist3()) && (m_config.Blacklist3()!="")) - || (text2.startsWith(m_config.Blacklist4()) && (m_config.Blacklist4()!="")) - || (text2.startsWith(m_config.Blacklist5()) && (m_config.Blacklist5()!="")) - || (text2.startsWith(m_config.Blacklist6()) && (m_config.Blacklist6()!="")) - || (text2.startsWith(m_config.Blacklist7()) && (m_config.Blacklist7()!="")) - || (text2.startsWith(m_config.Blacklist8()) && (m_config.Blacklist8()!="")) - || (text2.startsWith(m_config.Blacklist9()) && (m_config.Blacklist9()!="")) - || (text2.startsWith(m_config.Blacklist10()) && (m_config.Blacklist10()!="")) - || (text2.startsWith(m_config.Blacklist11()) && (m_config.Blacklist11()!="")) - || (text2.startsWith(m_config.Blacklist12()) && (m_config.Blacklist12()!="")) - )) { - if (!ui->cbBypass->isChecked()) filtered = true; - if (!(m_config.filters_for_Wait_and_Pounce_only() or ui->cbBypass->isChecked())) return; - // reset dB score when filtered - if (pounce && (ui->respondComboBox->currentText()=="CQ: Max Dist" - or ui->respondComboBox->currentText()=="CQ: Max dB" - or ui->respondComboBox->currentText()=="CQ: Min dB")) { - Dpoints=0; - maxDPoints=0; - dBpoints=-28; - dBpoints2=99; - maxdBPoints=-28; - mindBPoints=99; - } - - // Filtering out everything but messages with keywords from Whitelist - } else if ((SpecOp::NONE==m_specOp or SpecOp::HOUND==m_specOp) && m_config.Whitelisted () - && !(text2.startsWith(m_config.Whitelist1()) && (m_config.Whitelist1()!="")) - && !(text2.startsWith(m_config.Whitelist2()) && (m_config.Whitelist2()!="")) - && !(text2.startsWith(m_config.Whitelist3()) && (m_config.Whitelist3()!="")) - && !(text2.startsWith(m_config.Whitelist4()) && (m_config.Whitelist4()!="")) - && !(text2.startsWith(m_config.Whitelist5()) && (m_config.Whitelist5()!="")) - && !(text2.startsWith(m_config.Whitelist6()) && (m_config.Whitelist6()!="")) - && !(text2.startsWith(m_config.Whitelist7()) && (m_config.Whitelist7()!="")) - && !(text2.startsWith(m_config.Whitelist8()) && (m_config.Whitelist8()!="")) - && !(text2.startsWith(m_config.Whitelist9()) && (m_config.Whitelist9()!="")) - && !(text2.startsWith(m_config.Whitelist10()) && (m_config.Whitelist10()!="")) - && !(text2.startsWith(m_config.Whitelist11()) && (m_config.Whitelist11()!="")) - && !(text2.startsWith(m_config.Whitelist12()) && (m_config.Whitelist12()!="")) - ) { - if (!ui->cbBypass->isChecked()) filtered = true; - if (!(m_config.filters_for_Wait_and_Pounce_only() or ui->cbBypass->isChecked())) return; - // reset dB score when filtered - if (pounce && (ui->respondComboBox->currentText()=="CQ: Max Dist" - or ui->respondComboBox->currentText()=="CQ: Max dB" - or ui->respondComboBox->currentText()=="CQ: Min dB")) { - Dpoints=0; - maxDPoints=0; - dBpoints=-28; - dBpoints2=99; - maxdBPoints=-28; - mindBPoints=99; - } - } - - // search logbook for filtering - if (ui->actionHideTerritory1->isChecked() or ui->actionHideTerritory2->isChecked() or - ui->actionHideTerritory3->isChecked() or ui->actionHideTerritory4->isChecked() or - ui->actionHideB4->isChecked() or ui->actionHideEU->isChecked() or ui->actionHideAS->isChecked() or - ui->actionHideNA->isChecked() or ui->actionHideSA->isChecked() or ui->actionHideAF->isChecked() or - ui->actionHideOC->isChecked() or ui->actionHideAN->isChecked()) { - QString deCall; - QString deGrid; - decodedtext.deCallAndGrid(/*out*/deCall,deGrid); - // search for country names - if (ui->actionHideTerritory1->isChecked() or ui->actionHideTerritory2->isChecked() or - ui->actionHideTerritory3->isChecked() or ui->actionHideTerritory4->isChecked()) { - auto const& looked_up = m_logBook.countries ()->lookup (deCall); - auto countryName = looked_up.entity_name; - // do some obvious abbreviations - countryName.replace ("Islands", "Is."); - countryName.replace ("Island", "Is."); - countryName.replace ("North ", "N. "); - countryName.replace ("Northern ", "N. "); - countryName.replace ("South ", "S. "); - countryName.replace ("East ", "E. "); - countryName.replace ("Eastern ", "E. "); - countryName.replace ("West ", "W. "); - countryName.replace ("Western ", "W. "); - countryName.replace ("Central ", "C. "); - countryName.replace (" and ", " & "); - countryName.replace ("Republic", "Rep."); - countryName.replace ("United States of America", "U.S.A."); - countryName.replace ("United States", "U.S.A."); - countryName.replace ("Fed. Rep. of ", ""); - countryName.replace ("French ", "Fr."); - countryName.replace ("Asiatic", "AS"); - countryName.replace ("European", "EU"); - countryName.replace ("African", "AF"); - if (ui->actionHideTerritory1->isChecked() && countryName.contains(m_config.Territory1()) - && (m_config.Territory1()!="") && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideTerritory2->isChecked() && countryName.contains(m_config.Territory2()) - && (m_config.Territory2()!="") && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideTerritory3->isChecked() && countryName.contains(m_config.Territory3()) - && (m_config.Territory3()!="") && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideTerritory4->isChecked() && countryName.contains(m_config.Territory4()) - && (m_config.Territory4()!="") && !ui->cbBypass->isChecked()) filtered = true; - } - // search for callsigns worked B4 on band - if (ui->actionHideB4->isChecked()) { - bool callB4onBand; - bool countryB4onBand; - bool gridB4onBand; - bool continentB4onBand; - bool CQZoneB4onBand; - bool ITUZoneB4onBand; - auto const& looked_up = m_logBook.countries ()->lookup (deCall); - m_logBook.match (deCall, m_mode, deGrid, looked_up, callB4onBand, countryB4onBand, gridB4onBand, - continentB4onBand, CQZoneB4onBand, ITUZoneB4onBand, m_currentBand); - if (callB4onBand && ui->actionHideB4->isChecked() && !ui->cbBypass->isChecked()) filtered = true; - } - // search for continents - if (ui->actionHideEU->isChecked() or ui->actionHideAS->isChecked() or ui->actionHideNA->isChecked() - or ui->actionHideSA->isChecked() or ui->actionHideAF->isChecked() or ui->actionHideOC->isChecked() - or ui->actionHideAN->isChecked()) { - auto const& looked_up = m_logBook.countries ()->lookup (deCall); - QString continent = AD1CCty::continent (looked_up.continent); - if (ui->actionHideEU->isChecked() && continent == "EU" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideAS->isChecked() && continent == "AS" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideNA->isChecked() && continent == "NA" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideSA->isChecked() && continent == "SA" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideAF->isChecked() && continent == "AF" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideOC->isChecked() && continent == "OC" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideAN->isChecked() && continent == "AN" && !ui->cbBypass->isChecked()) filtered = true; - } - } - } - } else { - if (!(SpecOp::NONE==m_specOp && m_config.AlwaysPass () // Always pass messages with keywords from Always Pass list - && ( - (text.contains(m_config.Pass1()) && (m_config.Pass1()!="")) - || (text.contains(m_config.Pass2()) && (m_config.Pass2()!="")) - || (text.contains(m_config.Pass3()) && (m_config.Pass3()!="")) - || (text.contains(m_config.Pass4()) && (m_config.Pass4()!="")) - || (text.contains(m_config.Pass5()) && (m_config.Pass5()!="")) - || (text.contains(m_config.Pass6()) && (m_config.Pass6()!="")) - || (text.contains(m_config.Pass7()) && (m_config.Pass7()!="")) - || (text.contains(m_config.Pass8()) && (m_config.Pass8()!="")) - || (text.contains(m_config.Pass9()) && (m_config.Pass9()!="")) - || (text.contains(m_config.Pass10()) && (m_config.Pass10()!="")) - || (text.contains(m_config.Pass11()) && (m_config.Pass11()!="")) - || (text.contains(m_config.Pass12()) && (m_config.Pass12()!="")) - ))) { - - // Filtering out messages with keywords from Blacklist - if ((SpecOp::NONE==m_specOp or SpecOp::HOUND==m_specOp) && m_config.Blacklisted () - && ( - (text.contains(m_config.Blacklist1()) && (m_config.Blacklist1()!="")) - || (text.contains(m_config.Blacklist2()) && (m_config.Blacklist2()!="")) - || (text.contains(m_config.Blacklist3()) && (m_config.Blacklist3()!="")) - || (text.contains(m_config.Blacklist4()) && (m_config.Blacklist4()!="")) - || (text.contains(m_config.Blacklist5()) && (m_config.Blacklist5()!="")) - || (text.contains(m_config.Blacklist6()) && (m_config.Blacklist6()!="")) - || (text.contains(m_config.Blacklist7()) && (m_config.Blacklist7()!="")) - || (text.contains(m_config.Blacklist8()) && (m_config.Blacklist8()!="")) - || (text.contains(m_config.Blacklist9()) && (m_config.Blacklist9()!="")) - || (text.contains(m_config.Blacklist10()) && (m_config.Blacklist10()!="")) - || (text.contains(m_config.Blacklist11()) && (m_config.Blacklist11()!="")) - || (text.contains(m_config.Blacklist12()) && (m_config.Blacklist12()!="")) - )) { - if (!ui->cbBypass->isChecked()) filtered = true; - if (!(m_config.filters_for_Wait_and_Pounce_only() or ui->cbBypass->isChecked())) return; - // reset dB score when filtered - if (pounce && (ui->respondComboBox->currentText()=="CQ: Max Dist" - or ui->respondComboBox->currentText()=="CQ: Max dB" - or ui->respondComboBox->currentText()=="CQ: Min dB")) { - Dpoints=0; - maxDPoints=0; - dBpoints=-28; - dBpoints2=99; - maxdBPoints=-28; - mindBPoints=99; - } - - // Filtering out everything but messages with keywords from Whitelist - } else if ((SpecOp::NONE==m_specOp or SpecOp::HOUND==m_specOp) && m_config.Whitelisted () - && !(text.contains(m_config.Whitelist1()) && (m_config.Whitelist1()!="")) - && !(text.contains(m_config.Whitelist2()) && (m_config.Whitelist2()!="")) - && !(text.contains(m_config.Whitelist3()) && (m_config.Whitelist3()!="")) - && !(text.contains(m_config.Whitelist4()) && (m_config.Whitelist4()!="")) - && !(text.contains(m_config.Whitelist5()) && (m_config.Whitelist5()!="")) - && !(text.contains(m_config.Whitelist6()) && (m_config.Whitelist6()!="")) - && !(text.contains(m_config.Whitelist7()) && (m_config.Whitelist7()!="")) - && !(text.contains(m_config.Whitelist8()) && (m_config.Whitelist8()!="")) - && !(text.contains(m_config.Whitelist9()) && (m_config.Whitelist9()!="")) - && !(text.contains(m_config.Whitelist10()) && (m_config.Whitelist10()!="")) - && !(text.contains(m_config.Whitelist11()) && (m_config.Whitelist11()!="")) - && !(text.contains(m_config.Whitelist12()) && (m_config.Whitelist12()!="")) - ) { - if (!ui->cbBypass->isChecked()) filtered = true; - if (!(m_config.filters_for_Wait_and_Pounce_only() or ui->cbBypass->isChecked())) return; - // reset dB score when filtered - if (pounce && (ui->respondComboBox->currentText()=="CQ: Max Dist" - or ui->respondComboBox->currentText()=="CQ: Max dB" - or ui->respondComboBox->currentText()=="CQ: Min dB")) { - Dpoints=0; - maxDPoints=0; - dBpoints=-28; - dBpoints2=99; - maxdBPoints=-28; - mindBPoints=99; - } - } - - // search logbook for filtering - if (ui->actionHideTerritory1->isChecked() or ui->actionHideTerritory2->isChecked() or - ui->actionHideTerritory3->isChecked() or ui->actionHideTerritory4->isChecked() or - ui->actionHideB4->isChecked() or ui->actionHideEU->isChecked() or ui->actionHideAS->isChecked() or - ui->actionHideNA->isChecked() or ui->actionHideSA->isChecked() or ui->actionHideAF->isChecked() or - ui->actionHideOC->isChecked() or ui->actionHideAN->isChecked()) { - QString deCall; - QString deGrid; - decodedtext.deCallAndGrid(/*out*/deCall,deGrid); - // search for country names - if (ui->actionHideTerritory1->isChecked() or ui->actionHideTerritory2->isChecked() or - ui->actionHideTerritory3->isChecked() or ui->actionHideTerritory4->isChecked()) { - auto const& looked_up = m_logBook.countries ()->lookup (deCall); - auto countryName = looked_up.entity_name; - // do some obvious abbreviations - countryName.replace ("Islands", "Is."); - countryName.replace ("Island", "Is."); - countryName.replace ("North ", "N. "); - countryName.replace ("Northern ", "N. "); - countryName.replace ("South ", "S. "); - countryName.replace ("East ", "E. "); - countryName.replace ("Eastern ", "E. "); - countryName.replace ("West ", "W. "); - countryName.replace ("Western ", "W. "); - countryName.replace ("Central ", "C. "); - countryName.replace (" and ", " & "); - countryName.replace ("Republic", "Rep."); - countryName.replace ("United States of America", "U.S.A."); - countryName.replace ("United States", "U.S.A."); - countryName.replace ("Fed. Rep. of ", ""); - countryName.replace ("French ", "Fr."); - countryName.replace ("Asiatic", "AS"); - countryName.replace ("European", "EU"); - countryName.replace ("African", "AF"); - if (ui->actionHideTerritory1->isChecked() && countryName.contains(m_config.Territory1()) - && (m_config.Territory1()!="") && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideTerritory2->isChecked() && countryName.contains(m_config.Territory2()) - && (m_config.Territory2()!="") && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideTerritory3->isChecked() && countryName.contains(m_config.Territory3()) - && (m_config.Territory3()!="") && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideTerritory4->isChecked() && countryName.contains(m_config.Territory4()) - && (m_config.Territory4()!="") && !ui->cbBypass->isChecked()) filtered = true; - } - // search for callsigns worked B4 on band - if (ui->actionHideB4->isChecked()) { - bool callB4onBand; - bool countryB4onBand; - bool gridB4onBand; - bool continentB4onBand; - bool CQZoneB4onBand; - bool ITUZoneB4onBand; - auto const& looked_up = m_logBook.countries ()->lookup (deCall); - m_logBook.match (deCall, m_mode, deGrid, looked_up, callB4onBand, countryB4onBand, gridB4onBand, - continentB4onBand, CQZoneB4onBand, ITUZoneB4onBand, m_currentBand); - if (callB4onBand && ui->actionHideB4->isChecked() && !ui->cbBypass->isChecked()) filtered = true; - } - // search for continents - if (ui->actionHideEU->isChecked() or ui->actionHideAS->isChecked() or ui->actionHideNA->isChecked() - or ui->actionHideSA->isChecked() or ui->actionHideAF->isChecked() or ui->actionHideOC->isChecked() - or ui->actionHideAN->isChecked()) { - auto const& looked_up = m_logBook.countries ()->lookup (deCall); - QString continent = AD1CCty::continent (looked_up.continent); - if (ui->actionHideEU->isChecked() && continent == "EU" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideAS->isChecked() && continent == "AS" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideNA->isChecked() && continent == "NA" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideSA->isChecked() && continent == "SA" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideAF->isChecked() && continent == "AF" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideOC->isChecked() && continent == "OC" && !ui->cbBypass->isChecked()) filtered = true; - if (ui->actionHideAN->isChecked() && continent == "AN" && !ui->cbBypass->isChecked()) filtered = true; - } - } - } - } - - // mute audible alerts when callsign is on the Ignored List - if (m_config.alert_Enabled() && !ui->cbBypass->isChecked()) { - QString deCall; - QString deGrid; - decodedtext.deCallAndGrid(deCall,deGrid); - if (deCall!="" && ignoreList.contains(deCall + ",")) m_muted = true; - } - - // hide or ignore callsigns - if (ui->actionHideIgnored->isChecked() or ui->actionHideToday->isChecked() or ui->actionIgnoreIgnored->isChecked() or ui->actionIgnoreToday->isChecked()) { - QString today = QDateTime::currentDateTimeUtc().toString ("yyyy-MM-dd"); - QString yesterday = QDateTime::currentDateTimeUtc().addDays(-1).toString ("yyyy-MM-dd"); - QString deCall; - QString deGrid; - decodedtext.deCallAndGrid(/*out*/deCall,deGrid); - if (ui->actionHideIgnored->isChecked() && !ui->cbBypass->isChecked() && ignoreList.contains(deCall + ",")) filtered = true; - if (ui->actionHideToday->isChecked() && !ui->cbBypass->isChecked() && ( - txLog.contains(QRegularExpression{today + ",[0-9][0-9]:[0-9][0-9]:[0-9][0-9]," + (deCall + ",")}) - or (m_config.twoDays() && txLog.contains(QRegularExpression{yesterday + ",[0-9][0-9]:[0-9][0-9]:[0-9][0-9]," + (deCall + ",")})))) { - filtered = true; - } - if (ui->actionIgnoreIgnored->isChecked() && ignoreList.contains(deCall + ",")) { - ignored = true; - m_muted = true; - } - if (ui->actionIgnoreToday->isChecked() && (txLog.contains(QRegularExpression{today + ",[0-9][0-9]:[0-9][0-9]:[0-9][0-9]," + (deCall + ",")}) - or (m_config.twoDays() && txLog.contains(QRegularExpression{yesterday + ",[0-9][0-9]:[0-9][0-9]:[0-9][0-9]," + (deCall + ",")})))) { - ignored = true; - m_muted = true; - } - } - if (ui->actionIgnoreB4->isChecked() && (pounce or m_auto)) { - QString deCall; - QString deGrid; - decodedtext.deCallAndGrid(/*out*/deCall,deGrid); - bool callB4onBand; - bool countryB4onBand; - bool gridB4onBand; - bool continentB4onBand; - bool CQZoneB4onBand; - bool ITUZoneB4onBand; - auto const& looked_up = m_logBook.countries ()->lookup (deCall); - m_logBook.match (deCall, m_mode, deGrid, looked_up, callB4onBand, countryB4onBand, gridB4onBand, - continentB4onBand, CQZoneB4onBand, ITUZoneB4onBand, m_currentBand); - if (callB4onBand && ui->actionIgnoreB4->isChecked() && !ui->cbBypass->isChecked()) { - ignored = true; - m_muted = true; - } - } // insert blank line, but only if not filtered and no decodes int ntime=6; - if (m_TRperiod>=60) ntime=4; - if ((m_config.insert_blank () or m_config.alert_Enabled()) && (line_read.left(ntime) != m_tBlankLine) && message0.left(4).contains(QRegularExpression {"\\d\\d\\d\\d"}) && !m_diskData) { + if (decodeContext.trPeriod>=60) ntime=4; + if ((m_config.insert_blank () or m_config.alert_Enabled()) && (line_read.left(ntime) != m_tBlankLine) && message0.left(4).contains(four_digit_regexp) && !decodeContext.diskData) { ui->decodedTextBrowser->new_period (); if (m_specOp == SpecOp::FOX and m_ActiveStationsWidget != NULL && m_config.insert_blank ()) { // clear the ActiveStations window m_ActiveStationsWidget->clearStations(); - m_ActiveStationsWidget->displayRecentStations("Fox Mode", ""); + m_ActiveStationsWidget->displayRecentStations(ActiveStations::DisplayMode::Fox, ""); } if (SpecOp::FOX != m_specOp && (!filtered or m_config.filters_for_Wait_and_Pounce_only()) && m_config.insert_blank ()) { QString band; if(((QDateTime::currentMSecsSinceEpoch() / 1000 - m_secBandChanged) > 4*int(m_TRperiod)/4) or m_displayBand) { - band = ' ' + m_config.bands ()->find (m_freqNominal); + band = ' ' + decodeContext.band; } if (m_config.insert_blank ()) { if (ui->actionUse_Dark_Style->isChecked()) { if (m_config.detailed_blank()) { if (m_config.DXCC()) { - ui->decodedTextBrowser->insertText(("------ " + m_dateTimeSeqStart.toString("yyyy-MM-dd - hh:mm:ss' UTC - '") + m_currentBandPeriod + " - " + m_mode + " ------"), "#a2a2a2", "#000000"); + ui->decodedTextBrowser->insertText(("------ " + decodeContext.sequenceStart.toString("yyyy-MM-dd - hh:mm:ss' UTC - '") + decodeContext.band + " - " + decodeContext.mode + " ------"), "#a2a2a2", "#000000"); } else { - ui->decodedTextBrowser->insertText(("------ " + m_dateTimeSeqStart.toString("yyyy-MM-dd - hh:mm:ss' UTC - '") + m_currentBandPeriod + " - " + m_mode), "#a2a2a2", "#000000"); + ui->decodedTextBrowser->insertText(("------ " + decodeContext.sequenceStart.toString("yyyy-MM-dd - hh:mm:ss' UTC - '") + decodeContext.band + " - " + decodeContext.mode), "#a2a2a2", "#000000"); } } else { ui->decodedTextBrowser->insertText(band.rightJustified(40, '-'), "#a2a2a2", "#000000"); @@ -6840,9 +6944,9 @@ void MainWindow::readFromStdout() //readFromStdout } else { if (m_config.detailed_blank()) { if (m_config.DXCC()) { - ui->decodedTextBrowser->insertLineSpacer ("------ " + m_dateTimeSeqStart.toString("yyyy-MM-dd - hh:mm:ss' UTC - '") + m_currentBandPeriod + " - " + m_mode + " ------"); + ui->decodedTextBrowser->insertLineSpacer ("------ " + decodeContext.sequenceStart.toString("yyyy-MM-dd - hh:mm:ss' UTC - '") + decodeContext.band + " - " + decodeContext.mode + " ------"); } else { - ui->decodedTextBrowser->insertLineSpacer ("------ " + m_dateTimeSeqStart.toString("yyyy-MM-dd - hh:mm:ss' UTC - '") + m_currentBandPeriod + " - " + m_mode); + ui->decodedTextBrowser->insertLineSpacer ("------ " + decodeContext.sequenceStart.toString("yyyy-MM-dd - hh:mm:ss' UTC - '") + decodeContext.band + " - " + decodeContext.mode); } } else { ui->decodedTextBrowser->insertLineSpacer (band.rightJustified (40, '-')); @@ -6854,137 +6958,19 @@ void MainWindow::readFromStdout() //readFromStdout } // SuperHound label - if (ui->labDXped->text().contains("Hound") && decodedtext0.mid(3,18).contains(" verified")) { - verified = true; - write_all("Vf",decodedtext0.string()); - ui->labDXped->setStyleSheet("QLabel {background-color: #00ff00; color: black;}"); - } else { -#ifndef FOX_OTP - if (m_specOp==SpecOp::HOUND && m_config.superFox() && (decodedtext0.mid(4,2).contains("00") or decodedtext0.mid(4,2).contains("30"))) verified = false; -#endif - } - if ((!verified && ui->labDXped->isVisible()) or !ui->labDXped->text().contains("Hound")) - ui->labDXped->setStyleSheet("QLabel {background-color: red; color: white;}"); + processSuperHoundVerification(decodedtext0); // show distance and bearing - if (!filtered or m_config.filters_for_Wait_and_Pounce_only()) { // show decodes if not filtered - QString distance; - QString deCall; - QString deGrid; - decodedtext.deCallAndGrid(deCall,deGrid); - if ((m_config.showDistance() || m_config.showAzimuth()) && deGrid.contains(grid_regexp)) { - double utch=0.0; - int nAz,nEl,nDmiles,nDkm,nHotAz,nHotABetter; - QString my_Grid = m_config.my_grid(); - if (my_Grid.length() < 5) my_Grid = m_config.my_grid().left(4)+"mm"; - QString de_Grid= deGrid.left(4)+"mm"; - azdist_(const_cast <char *> (my_Grid.toLatin1().constData()), - const_cast <char *> (de_Grid.toLatin1().constData()),&utch, - &nAz,&nEl,&nDmiles,&nDkm,&nHotAz,&nHotABetter,(FCL)6,(FCL)6); - if (m_config.showDistance()) { - int nd=nDkm; - if(m_config.miles()) nd=nDmiles; - distance = QString::number(nd); - if(m_config.miles()) distance += " mi"; - if(!m_config.miles()) distance += " km"; - } - if (m_config.showAzimuth()) { - if (distance.length()) distance += " / "; - distance += QString::number(nAz) + "°"; - } - } - - // display country names for JT65 and JT9 like for FT8 - if ((m_mode == "JT65" or m_mode == "JT9" or m_mode == "JT4") && m_config.DXCC()) { - DecodedText decodedtextJT {((QString::fromUtf8(line_read.left(44).constData())) + (QString::fromUtf8(line_read.mid(62, 2).constData())))}; - ui->decodedTextBrowser->displayDecodedText (decodedtextJT, m_config.my_callsign (), m_mode, m_config.DXCC (), - m_logBook, m_currentBandPeriod, m_config.ppfx (), - ui->cbCQonly->isVisible() && ui->cbCQonly->isChecked(), - haveFSpread, fSpread, bDisplayPoints, m_points, distance, m_muted); - } else { - if (ui->actionHide_AP_info->isVisible() && ui->actionHide_AP_info->isChecked()) { - // Hide FT8 AP information - DecodedText decodedtext2 {(QString::fromUtf8(line_read.replace("a1","").replace("a2","").replace("a3","").replace("a4","") - .replace("a5","").replace("a6","").replace("a7","").replace("a8","").replace("a9","").replace("?","")))}; - ui->decodedTextBrowser->displayDecodedText (decodedtext2, m_config.my_callsign (), m_mode, m_config.DXCC (), - m_logBook, m_currentBandPeriod, m_config.ppfx (), - ui->cbCQonly->isVisible() && ui->cbCQonly->isChecked(), - haveFSpread, fSpread, bDisplayPoints, m_points, distance, m_muted); - } else { - ui->decodedTextBrowser->displayDecodedText (decodedtext1, m_config.my_callsign (), m_mode, m_config.DXCC (), - m_logBook, m_currentBandPeriod, m_config.ppfx (), - ui->cbCQonly->isVisible() && ui->cbCQonly->isChecked(), - haveFSpread, fSpread, bDisplayPoints, m_points, distance, m_muted); - } - } + if (DecodeOutputPlan::shouldDisplayLeft(bAvgMsg, decodeContext.mode, + decodeContext.specOp, filtered, + m_config.filters_for_Wait_and_Pounce_only())) { + QString distance = calculateDistanceAndBearing(decodedtext); + displayDecodedTextLine(decodedtext1, line_read, distance, haveFSpread, fSpread, bDisplayPoints); if(m_position != 0) ui->decodedTextBrowser->horizontalScrollBar()->setValue(m_position); } - if (m_mode=="FT8" && ((m_multithreadFT8 && m_ft8DecoderStart<2) or m_freqNominal>45000000)) earlyDecodes.append(line_read); //ft8md - - // highlight callsigns worked B4 on band or worked today - if(ui->actionHighlightB4->isChecked() or ui->actionHighlightToday->isChecked() or ui->actionHighlightIgnored->isChecked() - or ui->actionHighlightTerritory1->isChecked() or ui->actionHighlightTerritory2->isChecked() - or ui->actionHighlightTerritory3->isChecked() or ui->actionHighlightTerritory4->isChecked()) { - QString today = QDateTime::currentDateTimeUtc().toString ("yyyy-MM-dd"); - QString yesterday = QDateTime::currentDateTimeUtc().addDays(-1).toString ("yyyy-MM-dd"); - QString deCall; - QString deGrid; - decodedtext.deCallAndGrid(/*out*/deCall,deGrid); - bool callB4onBand; - bool countryB4onBand; - bool gridB4onBand; - bool continentB4onBand; - bool CQZoneB4onBand; - bool ITUZoneB4onBand; - if (ui->actionHighlightB4->isChecked()) { - auto const& looked_up = m_logBook.countries ()->lookup (deCall); - m_logBook.match (deCall, m_mode, deGrid, looked_up, callB4onBand, countryB4onBand, gridB4onBand, - continentB4onBand, CQZoneB4onBand, ITUZoneB4onBand, m_currentBand); - if (callB4onBand) ui->decodedTextBrowser->highlight_callsign(deCall, QColor(195,195,195), QColor(0,0,0), true); - } - if (ui->actionHighlightToday->isChecked() && ( - txLog.contains(QRegularExpression{today + ",[0-9][0-9]:[0-9][0-9]:[0-9][0-9]," + (deCall + ",")}) - or (m_config.twoDays() && txLog.contains(QRegularExpression{yesterday + ",[0-9][0-9]:[0-9][0-9]:[0-9][0-9]," + (deCall + ",")})))) { - ui->decodedTextBrowser->highlight_callsign(deCall, QColor(100,100,100), QColor(255,255,0), true); - } - if (ui->actionHighlightIgnored->isChecked() && ignoreList.contains(deCall + ",")) { - ui->decodedTextBrowser->highlight_callsign(deCall, QColor(85,0,0), QColor(255,255,0), true); - } - // search for country names - if (ui->actionHighlightTerritory1->isChecked() or ui->actionHighlightTerritory2->isChecked() or - ui->actionHighlightTerritory3->isChecked() or ui->actionHighlightTerritory4->isChecked()) { - auto const& looked_up = m_logBook.countries ()->lookup (deCall); - auto countryName = looked_up.entity_name; - // do some obvious abbreviations - countryName.replace ("Islands", "Is."); - countryName.replace ("Island", "Is."); - countryName.replace ("North ", "N. "); - countryName.replace ("Northern ", "N. "); - countryName.replace ("South ", "S. "); - countryName.replace ("East ", "E. "); - countryName.replace ("Eastern ", "E. "); - countryName.replace ("West ", "W. "); - countryName.replace ("Western ", "W. "); - countryName.replace ("Central ", "C. "); - countryName.replace (" and ", " & "); - countryName.replace ("Republic", "Rep."); - countryName.replace ("United States of America", "U.S.A."); - countryName.replace ("United States", "U.S.A."); - countryName.replace ("Fed. Rep. of ", ""); - countryName.replace ("French ", "Fr."); - countryName.replace ("Asiatic", "AS"); - countryName.replace ("European", "EU"); - countryName.replace ("African", "AF"); - if (ui->actionHighlightTerritory1->isChecked() && countryName.contains(m_config.Territory1()) - && (m_config.Territory1()!="") && !ui->cbBypass->isChecked()) ui->decodedTextBrowser->highlight_callsign(deCall, QColor(115,43,245), QColor(255,255,255), true); - if (ui->actionHighlightTerritory2->isChecked() && countryName.contains(m_config.Territory2()) - && (m_config.Territory2()!="") && !ui->cbBypass->isChecked()) ui->decodedTextBrowser->highlight_callsign(deCall, QColor(115,43,245), QColor(255,255,255), true); - if (ui->actionHighlightTerritory3->isChecked() && countryName.contains(m_config.Territory3()) - && (m_config.Territory3()!="") && !ui->cbBypass->isChecked()) ui->decodedTextBrowser->highlight_callsign(deCall, QColor(115,43,245), QColor(255,255,255), true); - if (ui->actionHighlightTerritory4->isChecked() && countryName.contains(m_config.Territory4()) - && (m_config.Territory4()!="") && !ui->cbBypass->isChecked()) ui->decodedTextBrowser->highlight_callsign(deCall, QColor(115,43,245), QColor(255,255,255), true); - } - } + if (m_mode=="FT8" && ((m_multithreadFT8 && m_ft8DecoderStart<2) or m_operatingFrequency.rx ()>45000000)) earlyDecodes.append(line_read); //ft8md + + applyHighlighting(decodedtext, ui->decodedTextBrowser, true, play_Wanted, play_DXcall); if((m_mode=="FT4" or m_mode=="FT8") and bDisplayPoints and decodedtext1.isStandardMessage()) { QString deCall,deGrid; @@ -6993,121 +6979,8 @@ void MainWindow::readFromStdout() //readFromStdout if(bWorkedOnBand) activeWorked(deCall,m_currentBand); } - // CQ: First - if(((pounce && text.contains(" CQ ") && m_config.Wait_features_enabled()) - or (m_auto && m_bCallingCQ && text.contains(" " + m_config.my_callsign() + " "))) && !ignored - && !filtered && !selected && ui->respondComboBox->isVisible() && ui->respondComboBox->currentText()=="CQ: First" - && (!(ui->actionFull_Duplex_Mode->isChecked() && m_txing))) { - m_bDoubleClicked=true; - selected = true; - auto_tx_mode(true); - processMessage(decodedtext0); - auto now = QDateTime::currentDateTimeUtc(); - m_dateTimeQSOOn = now.addSecs (-(m_ntx - 1) * int(m_TRperiod) - int(fmod(double(now.time().second()),m_TRperiod))); - QTimer::singleShot (6000, [=] {selected = false;}); - if (pounce) stopWCTimer.start(int(6200.0*m_TRperiod)); // Tx max 6*TRperiod - } - - // CQ: Max Dist - if((pounce or m_auto) && ui->respondComboBox->isVisible() && ui->respondComboBox->currentText()=="CQ: Max Dist" - && (!(ui->actionFull_Duplex_Mode->isChecked() && m_txing))) { - QString deCall; - QString deGrid; - decodedtext.deCallAndGrid(/*out*/deCall,deGrid); - if (!filtered && !ignored && (deGrid.contains(grid_regexp) or m_bCallingCQ) && ( - (pounce && text.contains(" CQ ") && !txLog.contains(deCall) && m_config.Wait_features_enabled()) or - (m_bCallingCQ && text.contains(" " + m_config.my_callsign() + " ") && !text.contains("73 ")) - )) { - double utch=0.0; - int nAz,nEl,nDmiles,nDkm,nHotAz,nHotABetter; - azdist_(const_cast <char *> ((m_config.my_grid () + " ").left (6).toLatin1().constData()), - const_cast <char *> ((deGrid + " ").left (6).toLatin1().constData()),&utch, - &nAz,&nEl,&nDmiles,&nDkm,&nHotAz,&nHotABetter,6,6); - Dpoints=nDkm; - if (!deGrid.contains(grid_regexp)) Dpoints=1; - if(Dpoints>maxDPoints) { - maxDPoints=Dpoints; - m_deCall=deCall; - m_bDoubleClicked=true; - if ((pounce && text.contains(" CQ ") && m_config.Wait_features_enabled()) or m_auto) { - auto_tx_mode(true); - processMessage(decodedtext0); - if (pounce) stopWCTimer.start(int(6200.0*m_TRperiod)); // Tx max 6*TRperiod - } - ui->dxCallEntry->setText(deCall); - genStdMsgs(QString::number(decodedtext.snr())); - ui->RxFreqSpinBox->setValue(decodedtext.frequencyOffset()); - setTxMsg(m_ntx); - m_currentMessageType=m_ntx; - auto now = QDateTime::currentDateTimeUtc(); - m_dateTimeQSOOn = now.addSecs (-(m_ntx - 1) * int(m_TRperiod) - int(fmod(double(now.time().second()),m_TRperiod))); - } - } - } - - // CQ: Max dB - if((pounce or m_auto) && ui->respondComboBox->isVisible() && ui->respondComboBox->currentText()=="CQ: Max dB" - && (!(ui->actionFull_Duplex_Mode->isChecked() && m_txing))) { - QString deCall; - QString deGrid; - decodedtext.deCallAndGrid(/*out*/deCall,deGrid); - if (!filtered && !ignored && ( - (pounce && text.contains(" CQ ") && !txLog.contains(deCall) && m_config.Wait_features_enabled()) or - (m_bCallingCQ && text.contains(" " + m_config.my_callsign() + " ") && !text.contains("73 ")) - )) { - dBpoints=decodedtext.string().mid(7,3).toInt(); - if(dBpoints>maxdBPoints) { - maxdBPoints=dBpoints; - m_deCall=deCall; - m_bDoubleClicked=true; - if ((pounce && text.contains(" CQ ") && m_config.Wait_features_enabled()) or m_auto) { - auto_tx_mode(true); - processMessage(decodedtext0); - if (pounce) stopWCTimer.start(int(6200.0*m_TRperiod)); // Tx max 6*TRperiod - } - ui->dxCallEntry->setText(deCall); - genStdMsgs(QString::number(decodedtext.snr())); - ui->RxFreqSpinBox->setValue(decodedtext.frequencyOffset()); - setTxMsg(m_ntx); - m_currentMessageType=m_ntx; - auto now = QDateTime::currentDateTimeUtc(); - m_dateTimeQSOOn = now.addSecs (-(m_ntx - 1) * int(m_TRperiod) - int(fmod(double(now.time().second()),m_TRperiod))); - QTimer::singleShot (6000, [=] {selected = false;}); - } - } - } - - // CQ: Min dB - if((pounce or m_auto) && ui->respondComboBox->isVisible() && ui->respondComboBox->currentText()=="CQ: Min dB" - && (!(ui->actionFull_Duplex_Mode->isChecked() && m_txing))) { - QString deCall; - QString deGrid; - decodedtext.deCallAndGrid(/*out*/deCall,deGrid); - if (!filtered && !ignored && ( - (pounce && text.contains(" CQ ") && !txLog.contains(deCall) && m_config.Wait_features_enabled()) or - (m_bCallingCQ && text.contains(" " + m_config.my_callsign() + " ") && !text.contains("73 ")) - )) { - dBpoints2=decodedtext.string().mid(7,3).toInt(); - if(dBpoints2<mindBPoints) { - mindBPoints=dBpoints2; - m_deCall=deCall; - m_bDoubleClicked=true; - if ((pounce && text.contains(" CQ ") && m_config.Wait_features_enabled()) or m_auto) { - auto_tx_mode(true); - processMessage(decodedtext0); - if (pounce) stopWCTimer.start(int(6200.0*m_TRperiod)); // Tx max 6*TRperiod - } - ui->dxCallEntry->setText(deCall); - genStdMsgs(QString::number(decodedtext.snr())); - ui->RxFreqSpinBox->setValue(decodedtext.frequencyOffset()); - setTxMsg(m_ntx); - m_currentMessageType=m_ntx; - auto now = QDateTime::currentDateTimeUtc(); - m_dateTimeQSOOn = now.addSecs (-(m_ntx - 1) * int(m_TRperiod) - int(fmod(double(now.time().second()),m_TRperiod))); - QTimer::singleShot (6000, [=] {selected = false;}); - } - } - } + updateRespondTarget(decodedtext0, text, pounce, decodeContext.sequenceStart, + decodeContext.diskData); // Ensure that Tx stops and QSO is logged when repeat_Tx is enabled and "73" is received if(m_config.repeat_Tx() && m_mode=="Q65" && m_hisCall!="" && text.contains(m_baseCall) && text.contains(m_hisCall + " 73 ")) { @@ -7115,107 +6988,8 @@ void MainWindow::readFromStdout() //readFromStdout cease_auto_Tx_after_QSO(); } - // highlight orange and blue callsigns - if (m_config.highlight_orange() or (m_config.highlight_blue()) or ui->actionHighlight_Whitelist_entries->isChecked()) { - QString deCall; - QString deGrid; - decodedtext.deCallAndGrid(/*out*/deCall,deGrid); - if (m_config.highlight_orange() && deCall.size()>2 && (m_config.highlight_orange_callsigns().contains(deCall + ",") - or m_config.highlight_orange_callsigns().contains(deCall.left(3) + ";") or m_config.highlight_orange_callsigns().contains(deCall.left(2) + ";"))) { - ui->decodedTextBrowser->highlight_callsign(deCall, QColor(225,75,0), QColor(255,255,255), true); - if (m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted) play_Wanted = true; - } - if (m_config.highlight_orange() && deGrid.size()>3 && m_config.highlight_orange_callsigns().contains(deGrid)) { - ui->decodedTextBrowser->highlight_callsign(deGrid, QColor(225,75,0), QColor(255,255,255), true); - if (m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted) play_Wanted = true; - } - if (m_config.highlight_blue() && deCall.size()>2 && (m_config.highlight_blue_callsigns().contains(deCall + ",") - or m_config.highlight_blue_callsigns().contains(deCall.left(3) + ";") or m_config.highlight_blue_callsigns().contains(deCall.left(2) + ";"))) { - ui->decodedTextBrowser->highlight_callsign(deCall, QColor(0,100,255), QColor(255,255,255), true); - if (m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted) play_Wanted = true; - } - if (m_config.highlight_blue() && deGrid.size()>3 && m_config.highlight_blue_callsigns().contains(deGrid)) { - ui->decodedTextBrowser->highlight_callsign(deGrid, QColor(0,100,255), QColor(255,255,255), true); - if (m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted) play_Wanted = true; - } - // highlight directional calls - if (tw.size () > 2) { - if (m_config.highlight_orange() && tw[0]=="CQ" && m_config.highlight_orange_callsigns().contains("," + tw[1] + ",")) { - ui->decodedTextBrowser->highlight_callsign(tw[1], QColor(225,75,0), QColor(255,255,255), true); - if (m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted && tw[1]!="") play_Wanted = true; - } - if (m_config.highlight_blue() && tw[0]=="CQ" && m_config.highlight_blue_callsigns().contains("," + tw[1] + ",")) { - ui->decodedTextBrowser->highlight_callsign(tw[1], QColor(0,100,255), QColor(255,255,255), true); - if (m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted && tw[1]!="") play_Wanted = true; - } - } - // highlight Whitelist entries - if (ui->actionHighlight_Whitelist_entries->isChecked() && deCall.size()>2 && - ((deCall.contains(m_config.Whitelist1()) && m_config.Whitelist1() != "") - or (deCall.contains(m_config.Whitelist2()) && m_config.Whitelist2() != "") - or (deCall.contains(m_config.Whitelist3()) && m_config.Whitelist3() != "") - or (deCall.contains(m_config.Whitelist4()) && m_config.Whitelist4() != "") - or (deCall.contains(m_config.Whitelist5()) && m_config.Whitelist5() != "") - or (deCall.contains(m_config.Whitelist6()) && m_config.Whitelist6() != "") - or (deCall.contains(m_config.Whitelist7()) && m_config.Whitelist7() != "") - or (deCall.contains(m_config.Whitelist8()) && m_config.Whitelist8() != "") - or (deCall.contains(m_config.Whitelist9()) && m_config.Whitelist9() != "") - or (deCall.contains(m_config.Whitelist10()) && m_config.Whitelist10() != "") - or (deCall.contains(m_config.Whitelist11()) && m_config.Whitelist11() != "") - or (deCall.contains(m_config.Whitelist12()) && m_config.Whitelist12() != ""))) { - ui->decodedTextBrowser->highlight_callsign(deCall, QColor(170,0,127), QColor(255,255,255), true); - if (m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted) play_Wanted = true; - } - } - - // Highlight DX Call/Grid - if (!pounce && (m_config.highlight_DXcall() or m_config.alert_Enabled()) && (m_hisCall != "") && - ((decodedtext.string().contains(QRegularExpression{"(\\w+) " + m_hisCall})) - || (decodedtext.string().contains(QRegularExpression{"(\\w+) <" + m_hisCall + ">"})) - || (decodedtext.string().contains(QRegularExpression{"<(\\w+)> " + m_hisCall})) - || (decodedtext.string().contains(QRegularExpression{"<...> " + m_hisCall})))) { - if (m_config.alert_Enabled() && m_config.alert_DXcall() && !m_muted) play_DXcall = true; - if (m_config.highlight_DXcall()) { - // repeated highlighting to override JTAlert - ui->decodedTextBrowser->highlight_callsign(m_hisCall, QColor(255,0,0), QColor(255,255,255), true); - QTimer::singleShot (500, [=] {ui->decodedTextBrowser->highlight_callsign(m_hisCall, QColor(255,0,0), QColor(255,255,255), true);}); - QTimer::singleShot (1000, [=] {ui->decodedTextBrowser->highlight_callsign(m_hisCall, QColor(255,0,0), QColor(255,255,255), true);}); - QTimer::singleShot (2500, [=] {ui->decodedTextBrowser->highlight_callsign(m_hisCall, QColor(255,0,0), QColor(255,255,255), true);}); - } - } - if (!pounce && (m_config.highlight_DXgrid () or m_config.alert_Enabled()) && (m_hisGrid!="") && - (decodedtext.string().contains(m_hisGrid.left(4)))) { - if (m_config.highlight_DXgrid()) ui->decodedTextBrowser->highlight_callsign(m_hisGrid.left(4), QColor(0,0,200), QColor(255,255,255), true); - if (m_config.alert_Enabled() && m_config.alert_DXcall() && !m_muted) play_DXcall = true; - } - QTimer::singleShot (100, [=] { - if (m_config.alert_Enabled() && ((m_config.alert_DXcall() && play_DXcall && m_hisCall!="") or (m_config.alert_Wanted() && play_Wanted))) { -#ifdef WIN32 - QAudioOutput info(QAudioDeviceInfo::defaultOutputDevice()); - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config.voicesPath() + "/"; - QAudioFormat format; - format.setCodec("audio/pcm"); - format.setSampleRate (48000); - format.setChannelCount (1); - format.setSampleSize (16); - format.setSampleType(QAudioFormat::SignedInt); - QAudioOutput* audio; - audio = new QAudioOutput(format, this); - connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State))); - QFile *effect1 = new QFile(this); - if (m_config.alert_DXcall() && play_DXcall) effect1->setFileName(QString("%1/%2").arg(audioPath, "DXcall.wav")); - else if (m_config.alert_Wanted() && play_Wanted) effect1->setFileName(QString("%1/%2").arg(audioPath, "Wanted.wav")); - effect1->open(QIODevice::ReadOnly); - audio->start(effect1); -#else - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config.voicesPath() + "/"; - if (m_config.alert_DXcall() && play_DXcall) QSound::play(audioPath + "DXcall.wav"); // for Linux and macOS - else if (m_config.alert_DXcall() && play_Wanted) QSound::play(audioPath + "Wanted.wav"); // for Linux and macOS -#endif - play_DXcall = false; - play_Wanted = false; - } - }); + playDecodeAlertSound(play_Wanted, play_DXcall); + play_Wanted = play_DXcall = false; if (m_bBestSPArmed && m_mode=="FT4" && CALLING == m_QSOProgress && !ignored && !filtered) { QString messagePriority=ui->decodedTextBrowser->CQPriority(); @@ -7226,7 +7000,7 @@ void MainWindow::readFromStdout() //readFromStdout and (!(ui->actionFull_Duplex_Mode->isChecked() && m_txing))) { m_BestCQpriority="New Call on Band"; m_bDoubleClicked = true; - processMessage(decodedtext0); + processSyntheticMessage(decodedtext0); } if (messagePriority=="New DXCC" and m_BestCQpriority!="New DXCC" @@ -7234,7 +7008,7 @@ void MainWindow::readFromStdout() //readFromStdout and (!(ui->actionFull_Duplex_Mode->isChecked() && m_txing))) { m_BestCQpriority="New DXCC"; m_bDoubleClicked = true; - processMessage(decodedtext0); + processSyntheticMessage(decodedtext0); } } } @@ -7242,101 +7016,76 @@ void MainWindow::readFromStdout() //readFromStdout } //Right (Rx Frequency) window - bool bDisplayRight=bAvgMsg; - int audioFreq=decodedtext.frequencyOffset(); - if(m_mode=="FT8" or m_mode=="FT4" or m_mode=="FST4" or m_mode=="Q65") { - int ftol=10; - if(m_mode=="Q65") ftol=ui->sbFtol->value(); - auto const& parts = decodedtext.string().remove("<").remove(">") - .split (' ', SkipEmptyParts); - if (parts.size() > 6) { - auto for_us = parts[5].contains (m_baseCall) - || ("DE" == parts[5] && qAbs (ui->RxFreqSpinBox->value () - audioFreq) <= ftol); - if(m_baseCall == m_config.my_callsign()) { - if (m_baseCall != parts[5]) for_us=false; - } else { - if (m_config.my_callsign () != parts[5]) { -// Same base call as ours but different prefix or suffix. Rare but can happen with -// multi-station special events. - for_us = false; - } - } - - // Reply also to averaged messages that are only displayed in the right window - if(m_bCallingCQ && !m_bAutoReply && for_us && m_specOp!=SpecOp::FOX && m_specOp!=SpecOp::HOUND - && ui->actionInclude_averaging->isVisible() && ui->actionInclude_averaging->isChecked()) { - bool bProcessMsgNormally=ui->respondComboBox->currentText()!="CQ: None" or - (m_ActiveStationsWidget!=NULL and !m_ActiveStationsWidget->isVisible()); - if (decodedtext.messageWords().length() >= 3) { - QString t=decodedtext.messageWords()[2]; - if(t.contains("R+") or t.contains("R-") or t=="R" or t=="RRR" or t=="RR73") bProcessMsgNormally=true; - } else { - bProcessMsgNormally=true; - } - if(bProcessMsgNormally) { - m_bDoubleClicked=true; - m_bAutoReply = true; - processMessage (decodedtext); - } - } - - if(SpecOp::FOX==m_specOp and decodedtext.string().contains(" DE ")) for_us=true; //Hound with compound callsign - if(SpecOp::FOX==m_specOp and for_us and decodedtext.string().contains(QRegularExpression{" R\\W\\d"})) bDisplayRight=true; - if(SpecOp::FOX!=m_specOp and (for_us or (abs(audioFreq - m_wideGraph->rxFreq()) <= 10))) bDisplayRight=true; - if(SpecOp::HOUND==m_specOp and !for_us) bDisplayRight=false; - - // Give the Fox a warning when there is probably another Fox on the frequency - if(SpecOp::FOX==m_specOp and audioFreq<1000 and !for_us and decodedtext.string().contains(QRegularExpression{" R\\W\\d"})) { - if (first_Fox_alert) { - first_Fox_alert = false; - QTimer::singleShot (120000, [=] {first_Fox_alert = true;}); // Reset after 2 minutes - } else { - if (second_Fox_alert) { - second_Fox_alert = false; - QTimer::singleShot (300000, [=] {second_Fox_alert = true;}); // Reset after 5 minutes - } else { - if (!no_Fox_alert) { - MessageBox::warning_message (this, - "Looks like another fox is working on this frequency.\n\n" - "Stop transmitting, exit Fox mode for a few minutes,\n" - "and check the incoming FT8 messages."); - no_Fox_alert = true; - QTimer::singleShot (3600000, [=] { // No further Fox warnings for 60 minutes - no_Fox_alert = false; - first_Fox_alert = true; - second_Fox_alert = true; - }); - } - } - } - } - - } - } else { - if((abs(audioFreq - m_wideGraph->rxFreq()) <= 10) and - !m_config.enable_VHF_features()) bDisplayRight=true; - } - if(m_mode=="Q65" and !bAvgMsg and !decodedtext.string().contains(m_baseCall)) bDisplayRight=false; - if((m_mode=="JT4" or m_mode=="Q65" or m_mode=="JT65") and decodedtext.string().contains(m_baseCall) && ui->actionInclude_averaging->isVisible() && !ui->actionInclude_averaging->isChecked()) bDisplayRight=true; - if((m_mode=="FT8" or m_mode=="FT4") and SpecOp::FOX!=m_specOp && decodedtext0.string().replace("<","").replace(">","").contains(m_baseCall + " " + m_hisCall)) bDisplayRight=true; // really all messages for us - - // AutoSeq for JT65/JT4 short messages - if ((m_mode=="JT65" or m_mode=="JT4") && m_auto && m_config.enable_VHF_features() && ui->cbShMsgs->isChecked() && ui->cbAutoSeq->isChecked () && (abs(audioFreq - m_wideGraph->rxFreq()) <= 15)) { - if (decodedtext.string().contains(" " + m_config.my_callsign() + " ") && decodedtext.string().contains(" OOO")) { - setTxMsg(3); - } - if (decodedtext.string().contains(" RO")) { - setTxMsg(4); + DecodeOutputPlan::RoutingContext routingContext; + routingContext.mode = decodeContext.mode; + routingContext.specOp = decodeContext.specOp; + routingContext.myCall = decodeContext.myCall; + routingContext.baseCall = Radio::base_callsign (decodeContext.myCall); + routingContext.hisCall = m_hisCall; + routingContext.rxFrequency = ui->RxFreqSpinBox->value(); + routingContext.wideGraphRxFrequency = m_wideGraph->rxFreq(); + routingContext.q65Tolerance = ui->sbFtol->value(); + routingContext.enableVhfFeatures = m_config.enable_VHF_features(); + routingContext.includeAveragingVisible = ui->actionInclude_averaging->isVisible(); + routingContext.includeAveraging = ui->actionInclude_averaging->isChecked(); + routingContext.blockRightDisplay = block_right_display; + auto const routingDecision = + DecodeOutputPlan::decideRouting(decodedtext0, decodedtext, bAvgMsg, routingContext); + bool const bDisplayRight = routingDecision.displayRight; + bool const for_us = routingDecision.forUs; + + // Reply also to averaged messages that are only displayed in the right window + if(m_bCallingCQ && !m_bAutoReply && for_us && m_specOp!=SpecOp::FOX && m_specOp!=SpecOp::HOUND + && ui->actionInclude_averaging->isVisible() && ui->actionInclude_averaging->isChecked()) { + bool bProcessMsgNormally=autoRespondPolicy () != AutoRespondPolicy::None or + (m_ActiveStationsWidget!=NULL and !m_ActiveStationsWidget->isVisible()); + if (decodedtext.messageWords().length() >= 3) { + QString t=decodedtext.messageWords()[2]; + if(t.contains("R+") or t.contains("R-") or t=="R" or t=="RRR" or t=="RR73") bProcessMsgNormally=true; + } else { + bProcessMsgNormally=true; } - if (decodedtext.string().contains(" RRR")) { - setTxMsg(5); + if(bProcessMsgNormally) { + m_bDoubleClicked=true; + m_bAutoReply = true; + processSyntheticMessage(decodedtext); } - if (decodedtext.string().contains(" 73")) { - setTxMsg(5); + } + + // Give the Fox a warning when there is probably another Fox on the frequency + if (routingDecision.competingFoxReport) { + if (first_Fox_alert) { + first_Fox_alert = false; + QTimer::singleShot (120000, this, [=] {first_Fox_alert = true;}); + } else if (second_Fox_alert) { + second_Fox_alert = false; + QTimer::singleShot (300000, this, [=] {second_Fox_alert = true;}); + } else if (!no_Fox_alert) { + MessageBox::warning_message (this, + "Looks like another fox is working on this frequency.\n\n" + "Stop transmitting, exit Fox mode for a few minutes,\n" + "and check the incoming FT8 messages."); + no_Fox_alert = true; + QTimer::singleShot (3600000, this, [=] { + no_Fox_alert = false; + first_Fox_alert = true; + second_Fox_alert = true; + }); } } + if ((m_mode == "JT65" || m_mode == "JT4") && m_auto + && m_config.enable_VHF_features() && ui->cbShMsgs->isChecked() + && ui->cbAutoSeq->isChecked()) { + auto shortMessageSnapshot = qsoReactionSnapshot(); + shortMessageSnapshot.rxFrequency = m_wideGraph->rxFreq(); + applyQsoReactionPlan( + DecodedMessageReaction::planAutoSequence( + decodedtext, shortMessageSnapshot, + DecodedMessageReaction::AutoSequencePhase::LegacyShortMessage, 15, 15), + decodedtext); + } - if (bDisplayRight && !block_right_display) { + if (bDisplayRight) { // This msg is within 10 hertz of our tuned frequency, or a JT4 or JT65 avg, or contains MyCall if(!pounce && (!m_bBestSPArmed or m_mode!="FT4")) { @@ -7352,29 +7101,28 @@ void MainWindow::readFromStdout() //readFromStdout if (m_config.alert_Enabled() && ui->actionInclude_averaging->isVisible() && ui->actionInclude_averaging->isChecked()) ui->decodedTextBrowser->new_period (); // ensure alerts are played ui->decodedTextBrowser2->displayDecodedText (decodedtext0, m_config.my_callsign (), m_mode, m_config.DXCC (), m_logBook, m_currentBand, m_config.ppfx (), false, false, 0.0, bDisplayPoints, m_points, "", m_muted); + applyHighlighting(decodedtext, ui->decodedTextBrowser2, false, play_Wanted, play_DXcall); } m_QSOText = decodedtext.string ().trimmed (); } - if (!blockUDP) // block udp spotting for false decodes (JTAlert) postDecode (true, decodedtext.string ()); if(m_mode=="FT8" and SpecOp::HOUND==m_specOp) { if(decodedtext.string().contains(";")) { QString text = decodedtext.string().remove("<").remove(">"); // needed for MSHV multistream messages QStringList w=text.mid(24).split(" ",SkipEmptyParts); - QString foxCall=w.at(3); - if(w.at(0)==m_config.my_callsign() or w.at(0)==Radio::base_callsign(m_config.my_callsign())) { - //### Check for ui->dxCallEntry->text()==foxCall before logging! ### - ui->stopTxButton->click (); - logQSOTimer.start(0); - } - if((w.at(2)==m_config.my_callsign() or w.at(2)==Radio::base_callsign(m_config.my_callsign())) - and ui->tx3->text().length()>0) { - m_rptRcvd=w.at(4); - m_rptSent=decodedtext.string().mid(7,3); - m_nFoxFreq=decodedtext.string().mid(16,4).toInt(); - hound_reply (); + if(w.size() >= 5) { + if(w.at(0)==m_config.my_callsign() or w.at(0)==Radio::base_callsign(m_config.my_callsign())) { + ui->stopTxButton->click (); + logQSOTimer.start(0); + } + if((w.at(2)==m_config.my_callsign() or w.at(2)==Radio::base_callsign(m_config.my_callsign())) + and ui->tx3->text().length()>0) { + m_rptRcvd=w.at(4); + m_rptSent=decodedtext.string().mid(7,3); + hound_reply (decodedtext.string().mid(16,4).toInt()); + } } } else { QString text = decodedtext.string().remove("<").remove(">"); // needed for MSHV multistream messages @@ -7392,11 +7140,10 @@ void MainWindow::readFromStdout() //readFromStdout (w.at(2).mid(0,1)=="+" or w.at(2).mid(0,1)=="-")) { m_rptRcvd=w.at(2); m_rptSent=decodedtext.string().mid(7,3); - m_nFoxFreq=decodedtext.string().mid(16,4).toInt(); - hound_reply (); + hound_reply (decodedtext.string().mid(16,4).toInt()); } else { - if (SpecOp::HOUND==m_specOp && (text.mid(4,2).contains("15") or text.mid(4,2).contains("45"))) return; // ignore stations calling in the wrong time slot - if (text.contains(" " + m_config.my_callsign() + " " + m_hisCall) && !text.contains("73 ")) processMessage(decodedtext0); // needed for MSHV multistream messages + if (SpecOp::HOUND==m_specOp && (text.mid(4,2).contains("15") or text.mid(4,2).contains("45"))) return; + if (text.contains(" " + m_config.my_callsign() + " " + m_hisCall) && !text.contains("73 ")) processSyntheticMessage(decodedtext0); // needed for MSHV multistream messages } } } @@ -7432,34 +7179,63 @@ void MainWindow::readFromStdout() //readFromStdout } } // extract details and send to PSKreporter - int nsec=QDateTime::currentMSecsSinceEpoch()/1000-m_secBandChanged; - bool okToPost=(nsec > int(4*m_TRperiod)/5); - if(m_mode=="FST4W" and okToPost) { - line_read=line_read.left(22) + " CQ " + line_read.trimmed().mid(22); - auto p = line_read.lastIndexOf (' '); - DecodedText FST4W_post {QString::fromUtf8 (line_read.left (p).constData ())}; - pskPost(FST4W_post); - } else { - if (stdMsg && okToPost) pskPost(decodedtext); + bool const okToPost = + QDateTime::currentMSecsSinceEpoch()/1000-m_secBandChanged > int(4*m_TRperiod)/5; + if (DecodeOutputPlan::shouldPostPsk(decodeContext.mode, decodeContext.specOp, + decodeContext.superFox, + stdMsg, okToPost)) { + if(m_mode=="FST4W") { + line_read=line_read.left(22) + " CQ " + line_read.trimmed().mid(22); + auto p = line_read.lastIndexOf (' '); + DecodedText FST4W_post {QString::fromUtf8 (line_read.left (p).constData ())}; + pskPost(FST4W_post, decodeContext); + } else { + pskPost(decodedtext, decodeContext); + } } - if((m_mode=="JT4" or m_mode=="JT65" or m_mode=="Q65") and - m_msgAvgWidget!=NULL) { - if(m_msgAvgWidget->isVisible()) { - QFile f(m_config.temp_dir ().absoluteFilePath ("avemsg.txt")); - if(f.open(QIODevice::ReadOnly | QIODevice::Text)) { - QTextStream s(&f); - QString t=s.readAll(); - if (t != NULL) m_msgAvgWidget->displayAvg(t); - else qDebug() << "tmp==NULL at s.readAll"; - } + if((m_mode=="JT4" or m_mode=="JT65" or m_mode=="Q65") + and m_msgAvgWidget and m_msgAvgWidget->isVisible()) { + QFile f(m_config.temp_dir ().absoluteFilePath ("avemsg.txt")); + if(f.open(QIODevice::ReadOnly | QIODevice::Text)) { + QTextStream s(&f); + QString t=s.readAll(); + if (t != NULL) m_msgAvgWidget->displayAvg(t); + else qDebug() << "tmp==NULL at s.readAll"; } } } } + }); + auto const batchActions = DecodeOutputPlan::finishBatchActions( + decodeContext.mode, decodeContext.specOp, + m_ActiveStationsWidget != nullptr, all_decodes); + for (auto const& action : batchActions) { + if (action.kind == DecodeOutputPlan::ActionKind::FlushFoxActivity) { + m_ActiveStationsWidget->addLine(action.text); + } } - if (m_mode == "FT8" and m_specOp == SpecOp::FOX and m_ActiveStationsWidget != NULL) { - m_ActiveStationsWidget->addLine(all_decodes); - } + if (decodeCompleted && DecodeOwner::Jt9 == m_decodeOwner) + { + if (m_activeJt9Decode.obsolete) + { + abortJt9Transaction (); + } + else + { + m_ft8MtdDecodeCoordinator.completed ( + m_activeJt9Decode.ft8Stage, m_activeJt9Decode.ft8Period); + m_decoderCompletedSinceStart = true; + m_jt9PayloadValid = m_jt9PayloadValid || m_activeJt9Decode.copiedSamples; + m_activeJt9Decode = {}; + finishDecodeUi (); + endDecode (DecodeOwner::Jt9); + } + auto const pendingResult = publishPendingFt8Decode (); + if (DecodePublishResult::Failed == pendingResult) + { + requestDecoderRestart ("pending FT8 decode publication failed"); + } + } } // @@ -7470,142 +7246,55 @@ void MainWindow::readFromStdout() //readFromStdout // another caller and we are going to transmit within // +/- this value of the reply to another caller // -void MainWindow::auto_sequence (DecodedText const& message, unsigned start_tolerance, unsigned stop_tolerance) -{ - auto const& message_words = message.messageWords (); - auto is_73 = message_words.filter (QRegularExpression {"^(73|RR73)$"}).size(); - auto msg_no_hash = message.clean_string(); - msg_no_hash = msg_no_hash.mid(22).remove("<").remove(">"); - bool is_OK=false; - if(m_mode=="MSK144" && msg_no_hash.indexOf(ui->dxCallEntry->text()+" R ")>0) is_OK=true; - if (message_words.size () > 3 && (message.isStandardMessage() || (is_73 or is_OK))) { - auto df = message.frequencyOffset (); - auto within_tolerance = (qAbs (ui->RxFreqSpinBox->value () - df) <= int (start_tolerance) - || qAbs (ui->TxFreqSpinBox->value () - df) <= int (start_tolerance)); - bool acceptable_73 = is_73 - && m_QSOProgress >= ROGER_REPORT - && ((message.isStandardMessage () - && (message_words.contains (m_baseCall) - || message_words.contains (m_config.my_callsign ()) - || message_words.contains (ui->dxCallEntry->text ()) - || message_words.contains (Radio::base_callsign (ui->dxCallEntry->text ())) - || message_words.contains ("DE"))) - || (!message.isStandardMessage () && m_mode != "MSK144")); // free text 73/RR73 except for MSK - - auto const& w = msg_no_hash.split(" ",SkipEmptyParts); - QString w2; - int nrpt=0; - if (w.size () > 2) - { - w2=w.at(2); - if(w.size()>3) { - nrpt=w2.toInt(); - if(w2=="R") nrpt=w.at(3).toInt(); - } - } - bool bEU_VHF=(nrpt>=520001 and nrpt<=594000); - if(bEU_VHF and message.clean_string ().contains("<"+m_config.my_callsign() + "> ")) { - m_xRcvd=message.clean_string ().trimmed().right(13); - } - if (m_auto - && (m_QSOProgress==REPLYING or (!ui->tx1->isEnabled () and m_QSOProgress==REPORT)) - && SpecOp::HOUND != m_specOp && qAbs (ui->TxFreqSpinBox->value () - df) <= int (stop_tolerance) // - && message_words.at (2) != "DE" - && !message_words.at (2).contains (QRegularExpression {"(^(CQ|QRZ))|" + m_baseCall}) - && message_words.at (3).contains (Radio::base_callsign (ui->dxCallEntry->text ()))) { - // auto stop to avoid accidental QRM - ui->stopTxButton->click (); // halt any transmission - LOG_INFO("STOPPED!"); - } else if (m_auto // transmit allowed - && ui->cbAutoSeq->isVisible () && ui->cbAutoSeq->isEnabled () && ui->cbAutoSeq->isChecked () // auto-sequencing allowed - && ((!m_bCallingCQ // not calling CQ/QRZ - && !m_sentFirst73 // not finished QSO - && ((message_words.at (2).contains (m_baseCall) - // being called and not already in a QSO - && (message_words.at(3).contains(Radio::base_callsign(ui->dxCallEntry->text())) - or bEU_VHF)) - || message_words.at(1) == m_baseCall // <de-call> RR73; ... - // type 2 compound replies - || (within_tolerance && - (acceptable_73 || - ("DE" == message_words.at (2) && - w2.contains(Radio::base_callsign (m_hisCall))))))) - || (m_bCallingCQ && m_bAutoReply - // look for type 2 compound call replies on our Tx and Rx offsets - && ((within_tolerance && "DE" == message_words.at (2)) - || message_words.at (2).contains (m_baseCall))))) { - if(SpecOp::FOX != m_specOp) processMessage (message); - } - } +void MainWindow::auto_sequence(DecodedText const& message, unsigned start_tolerance, + unsigned stop_tolerance) +{ + auto const snapshot = qsoReactionSnapshot(); + applyQsoReactionPlan( + DecodedMessageReaction::planAutoSequence( + message, snapshot, DecodedMessageReaction::AutoSequencePhase::StandardDecode, + start_tolerance, stop_tolerance), + message); } - void MainWindow::pskPost (DecodedText const& decodedtext) { - if (m_diskData || !m_config.spot_to_psk_reporter() || decodedtext.isLowConfidence () - || (decodedtext.string().contains(m_baseCall) && decodedtext.string().contains(m_config.my_grid().left(4)))) return; // prevent self-spotting when running multiple instances - int h=decodedtext.string().mid(0,2).toInt(); - int m=decodedtext.string().mid(2,2).toInt(); - int s=decodedtext.string().mid(4,2).toInt(); - int sTimeString = decodedtext.string().mid(0,6).toInt(); - QTime time2(h, m, s); - QDateTime qSpotTime; - if (sTimeString + m_TRperiod < 236000) { - qSpotTime = QDateTime(QDateTime::currentDateTimeUtc().date(), time2, Qt::UTC); - } - else { - qSpotTime = QDateTime((QDateTime::currentDateTimeUtc().addDays(-1)).date(), time2, Qt::UTC); - } - QString msgmode=m_mode; + pskPost (decodedtext, currentDecodeOperatingContext ()); +} + +void MainWindow::pskPost (DecodedText const& decodedtext, + DecodeOperatingContext const& context) +{ + auto const baseCall = Radio::base_callsign (context.myCall); + if (context.diskData || !m_config.spot_to_psk_reporter() || decodedtext.isLowConfidence () + || (decodedtext.string().contains(baseCall) && decodedtext.string().contains(m_config.my_grid().left(4)))) return; // prevent self-spotting when running multiple instances + auto const qSpotTime = DecodedTime::spotTime( + decodedtext.string().section(' ', 0, 0), + QDateTime::currentDateTimeUtc(), context.trPeriod); + if (!qSpotTime.isValid()) return; + QString msgmode=context.mode; QString deCall; QString grid; decodedtext.deCallAndGrid(/*out*/deCall,grid); int audioFrequency = decodedtext.frequencyOffset(); - if(m_mode=="FT8" or m_mode=="MSK144" or m_mode=="FT4") { + if(context.mode=="FT8" or context.mode=="MSK144" or context.mode=="FT4") { audioFrequency=decodedtext.string().mid(16,4).toInt(); } int snr = decodedtext.snr(); - Frequency frequency = m_freqNominalPeriod + audioFrequency; // prevent spotting wrong band - if(grid.contains (grid_regexp) || decodedtext.string().contains(" CQ ")) { + Frequency frequency = context.periodFrequency + audioFrequency; + if(grid.contains (MainWindow::grid_regexp) || decodedtext.string().contains(" CQ ")) { // qDebug() << "To PSKreporter:" << deCall << grid << frequency << msgmode << snr; if (!m_psk_Reporter.addRemoteStation (deCall, grid, frequency, msgmode, snr, qSpotTime)) { - showStatusMessage (tr ("Spotting to PSK Reporter unavailable")); + showStatusMessage (tr ("PSK Reporter spot queue full; oldest spot dropped")); } } } -void MainWindow::killFile () +void MainWindow::killWaveFile () { - if (m_fnameWE.size () && !(m_saveAll || (m_saveDecoded && m_bDecoded))) { - QFile f1 {m_fnameWE + ".wav"}; - if(f1.exists()) f1.remove(); - if(m_mode=="WSPR" or m_mode=="FST4W") { - QFile f2 {m_fnameWE + ".c2"}; - if(f2.exists()) f2.remove(); - } - } + Radio::WavFile::killWaveFile (m_fnameWE, m_saveAll, m_saveDecoded, m_bDecoded, m_mode); } -void MainWindow::on_EraseButton_clicked () -{ - qint64 ms=QDateTime::currentMSecsSinceEpoch(); - if (m_config.alternate_erase_button()) { - ui->decodedTextBrowser->erase (); - if((ms-m_msErase)<500) { - ui->decodedTextBrowser2->erase (); - } - } else { - ui->decodedTextBrowser2->erase (); - if(m_mode=="WSPR" or m_mode=="Echo" or m_mode=="FST4W") { - ui->decodedTextBrowser->erase (); - } else { - if((ms-m_msErase)<500) { - ui->decodedTextBrowser->erase (); - } - } - } - m_msErase=ms; -} void MainWindow::band_activity_cleared () { @@ -7618,20 +7307,10 @@ void MainWindow::rx_frequency_activity_cleared () { m_QSOText.clear(); set_dateTimeQSO(-1); // G4WJS: why do we do this? -} - -void MainWindow::decodeBusy(bool b) //decodeBusy() -{ - if (!b) { - m_optimizingProgress.reset (); - } - m_decoderBusy=b; - ui->DecodeButton->setEnabled(!b); - ui->actionOpen->setEnabled(!b); - ui->actionOpen_next_in_directory->setEnabled(!b); - ui->actionDecode_remaining_files_in_directory->setEnabled(!b); - - statusUpdate (); + // decodedTextBrowser2's document just lost every block; drop our cached + // JTTY per-transmission QTextBlock handles along with it. + m_jttyQsoLines.clear(); + m_jttyQsoGroupEndPosition = -1; } //------------------------------------------------------------- //guiUpdate() @@ -7655,7 +7334,8 @@ void MainWindow::guiUpdate() tx2 += m_TRperiod; } - qint64 ms = QDateTime::currentMSecsSinceEpoch() % 86400000; + auto const nowUtc = QDateTime::currentDateTimeUtc(); + qint64 ms = nowUtc.toMSecsSinceEpoch() % 86400000; int nsec=ms/1000; double tsec=0.001*ms; double t2p=fmod(tsec,2*m_TRperiod); @@ -7671,21 +7351,7 @@ void MainWindow::guiUpdate() } if(m_mode=="WSPR" or m_mode=="FST4W") { - if(nseq==0 and m_ntr==0) { //Decide whether to Tx or Rx - m_tuneup=false; //This is not an ATU tuneup - bool btx = m_auto && m_WSPR_tx_next; // To Tx, we need m_auto and - // scheduled transmit - m_WSPR_tx_next = false; - if(btx) { - m_ntr=-1; //This says we will have transmitted - ui->pbTxNext->setChecked (false); - m_bTxTime=true; //Start a WSPR or FST4W Tx sequence - } else { - // This will be a WSPR or FST4W Rx sequence. - m_ntr=1; //This says we will have received - m_bTxTime=false; //Start a WSPR or FST4W Rx sequence - } - } + processBeaconActions (m_beaconTxController.observeUtc (nowUtc.toMSecsSinceEpoch ())); } else { // For all modes other than WSPR and FST4W @@ -7701,6 +7367,13 @@ void MainWindow::guiUpdate() } if(m_tune) m_bTxTime=true; //"Tune" takes precedence + bool const nominalTransmitPeriod = m_txFirst ? t2p < m_TRperiod : t2p >= m_TRperiod; + auto const periodStart = qt_truncate_date_time_to(nowUtc, qRound(m_TRperiod * 1000.0)); + if (m_autoRespondPeriodState.observePeriod(periodStart, !nominalTransmitPeriod, + pendingCqAutoRespondIntent(), autoRespondPolicy())) { + m_autoRespondScores.reset(); + } + if(m_transmitting or m_auto or m_tune) { m_dateTimeLastTX = QDateTime::currentDateTimeUtc (); @@ -7709,7 +7382,7 @@ void MainWindow::guiUpdate() if(f.exists() and fmod(tsec,m_TRperiod) < (0.5 + 105.0*576.0/12000.0)) m_bTxTime=true; // Don't transmit another mode in the 30 m WSPR sub-band - Frequency onAirFreq = m_freqNominal + ui->TxFreqSpinBox->value(); + Frequency onAirFreq = m_operatingFrequency.rx () + ui->TxFreqSpinBox->value(); if ((onAirFreq > 10139900 and onAirFreq < 10140320) and m_mode!="WSPR" and m_mode!="FST4W") { m_bTxTime=false; if (m_auto) auto_tx_mode (false); @@ -7718,47 +7391,34 @@ void MainWindow::guiUpdate() auto const& message = tr ("Please choose another Tx frequency." " WSJT-X will not knowingly transmit another" " mode in the WSPR sub-band on 30m."); - QTimer::singleShot (0, [=] { // don't block guiUpdate + QTimer::singleShot (0, this, [=] { // don't block guiUpdate MessageBox::warning_message (this, tr ("WSPR Guard Band"), message); }); } } if(m_mode=="FT8" and SpecOp::FOX==m_specOp) { -// Don't allow Fox mode in any of the default FT8 sub-bands. - QVector<qint32> ft8Freq = {1840000,3573000,7074000,10136000,14074000,18100000,21074000,24915000,28074000,50313000,70154000}; - for(int i=0; i<ft8Freq.length()-1; i++) { - int kHzdiff=m_freqNominal - ft8Freq[i]; - if(qAbs(kHzdiff) < 3000 ) { - m_bTxTime=false; - if (m_auto) auto_tx_mode (false); - if (m_tune) stop_tuning(); - auto const& message = tr ("Please choose another dial frequency.\n" - "Must be 3Khz away from %1.\n" - "WSJT-X will not operate in Fox mode\n" - "overlapping the standard FT8 sub-bands.").arg(ft8Freq[i]); - QTimer::singleShot (0, [=] { // don't block guiUpdate - MessageBox::warning_message (this, tr ("Fox Mode warning"), message); - }); - break; - } - } -// Don't allow Fox mode on WSPR frequencies. - QVector<qint32> wsprFreq = {1836600,5364700,3568600,7038600,10138700,14095600,18104600,21094600,24924600,28124600}; - for(int i=0; i<wsprFreq.length()-1; i++) { - int kHzdiff=m_freqNominal - wsprFreq[i]; - if(kHzdiff > -3500 && kHzdiff < 300) { - m_bTxTime=false; - if (m_auto) auto_tx_mode (false); - if (m_tune) stop_tuning(); - auto const& message = tr ("Please choose another dial frequency.\n" - "WSJT-X will not operate in Fox mode\n" - "overlapping the WSPR sub-bands.").arg(ft8Freq[i]); - QTimer::singleShot (0, [=] { // don't block guiUpdate - MessageBox::warning_message (this, tr ("Fox Mode warning"), message); - }); - break; + auto const guard = FoxGuardBands::check (m_operatingFrequency.rx ()); + if (guard.blocked) { + m_bTxTime=false; + if (m_auto) auto_tx_mode (false); + if (m_tune) stop_tuning(); + + QString message; + if (guard.kind == FoxGuardBands::GuardKind::StandardFT8) { + message = tr ("Please choose another dial frequency.\n" + "Must be 3Khz away from %1.\n" + "WSJT-X will not operate in Fox mode\n" + "overlapping the standard FT8 sub-bands.").arg (guard.guard_frequency); + } else { + message = tr ("Please choose another dial frequency.\n" + "WSJT-X will not operate in Fox mode\n" + "overlapping the WSPR sub-bands."); } + + QTimer::singleShot (0, this, [=] { // don't block guiUpdate + MessageBox::warning_message (this, tr ("Fox Mode warning"), message); + }); } } @@ -7777,13 +7437,18 @@ void MainWindow::guiUpdate() if(m_ntx == 5) txMsg=ui->tx5->currentText(); if(m_ntx == 6) txMsg=ui->tx6->text(); int msgLength=txMsg.trimmed().length(); - if(msgLength==0 and !m_tune) on_stopTxButton_clicked(); + if(should_stop_for_missing_tx_payload (m_mode, msgLength, m_tune)) on_stopTxButton_clicked(); - if(g_iptt==0 and ((m_bTxTime and (fTR < 0.75) and (msgLength>0)) or m_tune)) { + if(g_iptt==0 and can_start_transmit (m_mode, m_bTxTime, fTR, msgLength, m_tune)) { //### Allow late starts + m_autoRespondPeriodState.close(); icw[0]=m_ncw; g_iptt = 1; - setRig (); + if (m_beaconTxController.txLifecycle () == BeaconTx::TxLifecycle::Decided) + { + processBeaconActions (m_beaconTxController.txStartRequested ()); + } + reapplyCurrentRigFrequencyCorrection (); if(m_mode=="FT8") { if (SpecOp::FOX == m_specOp) { if(m_config.superFox()) { @@ -7795,25 +7460,26 @@ void MainWindow::guiUpdate() } } else if (SpecOp::HOUND == m_specOp && !m_config.superFox()) { - if(m_auto && !m_tune) { - if (ui->TxFreqSpinBox->value() < 999 && m_ntx != 3) { + HoundTransmissionPolicy::ClassicTxStartInput input; + input.autoEnabled = m_auto; + input.tune = m_tune; + input.selectedTxMessage = m_ntx; + input.currentTxFrequency = ui->TxFreqSpinBox->value(); + auto const plan = HoundTransmissionPolicy::planClassicTxStart ( + m_houndTransmissionState, input); + if (HoundTransmissionPolicy::FrequencyAction::RandomizeCalling + == plan.frequencyDecision.action) { // Hound randomized range: 1000-3000 Hz #if QT_VERSION >= QT_VERSION_CHECK (5, 15, 0) ui->TxFreqSpinBox->setValue (QRandomGenerator::global ()->bounded (1000, 2999)); #else ui->TxFreqSpinBox->setValue ((qrand () % 2000) + 1000); #endif - } - } - if (m_nSentFoxRrpt==2 and m_ntx==3) { - // move off the original Fox frequency on subsequent tries of Tx3 - int nfreq=m_nFoxFreq + 300; - if(m_nFoxFreq>600) nfreq=m_nFoxFreq - 300; //keep nfreq below 900 Hz - ui->TxFreqSpinBox->setValue(nfreq); - } - if (m_nSentFoxRrpt == 1) { - ++m_nSentFoxRrpt; + } else if (HoundTransmissionPolicy::FrequencyAction::Set + == plan.frequencyDecision.action) { + ui->TxFreqSpinBox->setValue (plan.frequencyDecision.frequency); } + m_houndTransmissionState = plan.nextState; } } @@ -7829,28 +7495,16 @@ void MainWindow::guiUpdate() } setXIT (ui->TxFreqSpinBox->value ()); - m_config.transceiver_ptt (true); //Assert the PTT - m_tx_when_ready = true; } -// if(!m_bTxTime and !m_tune and m_mode!="FT4") m_btxok=false; //Time to stop transmitting - if(!m_bTxTime and !m_tune) m_btxok=false; //Time to stop transmitting + if(!m_bTxTime and !m_tune and (m_mode != "JTTY")) m_btxok=false; //Time to stop transmitting } - if((m_mode=="WSPR" or m_mode=="FST4W") and - ((m_ntr==1 and m_rxDone) or (m_ntr==-1 and nseq>tx2))) { - if(m_monitoring) { - m_rxDone=false; - } - if(m_transmitting) { - WSPR_history(m_freqNominal,-1); - m_bTxTime=false; //Time to stop a WSPR or FST4W transmission + if ((m_mode=="WSPR" or m_mode=="FST4W") + && m_beaconTxController.transmitWindow () && nseq > tx2) + { + processBeaconActions (m_beaconTxController.transmitWindowEnded ()); m_btxok=false; } - else if (m_ntr != -1) { - WSPR_scheduling (); - m_ntr=0; //This WSPR or FST4W Rx sequence is complete - } - } // Calculate Tx tones when needed @@ -7867,38 +7521,33 @@ void MainWindow::guiUpdate() ui->txrb1->setChecked(true); } - if(m_mode=="FT4" and m_bBestSPArmed) { - m_BestCQpriority=""; - m_bBestSPArmed=false; - ui->pbBestSP->setStyleSheet (""); - } - - if(m_ntx == 1) ba=ui->tx1->text().toLocal8Bit(); - if(m_ntx == 2) ba=ui->tx2->text().toLocal8Bit(); - if(m_ntx == 3) ba=ui->tx3->text().toLocal8Bit(); - if(m_ntx == 4) ba=ui->tx4->text().toLocal8Bit(); - if(m_ntx == 5) ba=ui->tx5->currentText().toLocal8Bit(); - if(m_ntx == 6) ba=ui->tx6->text().toLocal8Bit(); + QString txText; + if(m_ntx == 1) txText=ui->tx1->text(); + if(m_ntx == 2) txText=ui->tx2->text(); + if(m_ntx == 3) txText=ui->tx3->text(); + if(m_ntx == 4) txText=ui->tx4->text(); + if(m_ntx == 5) txText=ui->tx5->currentText(); + if(m_ntx == 6) txText=ui->tx6->text(); + ba=expandTxMacros(txText).toLocal8Bit(); } ba2msg(ba,message); int ichk=0; - if (m_lastMessageSent != m_currentMessage - || m_lastMessageType != m_currentMessageType) - { - m_lastMessageSent = m_currentMessage; - m_lastMessageType = m_currentMessageType; - } + int msgsent_length=37; + std::fill_n(msgsent, sizeof msgsent, ' '); + msgsent[37]=0; + auto const previous_message = m_currentMessage; + auto const previous_message_type = m_currentMessageType; m_currentMessageType = 0; if(m_tune or m_mode=="Echo") { itone[0]=0; + auto const generated_label = m_tune ? QByteArrayLiteral("TUNE") : QByteArrayLiteral("ECHO"); + std::copy(generated_label.cbegin(), generated_label.cend(), msgsent); if(ui->rbEchoMessage->isChecked() or ui->rbEchoCW->isChecked()) { QString echoMsg=(ui->leEchoMessage->text()+" ").left(6); gen_echocall_(const_cast <char *> (echoMsg.toLatin1().constData()),const_cast<int *>(itone),(FCL)6); } } else { - if(m_QSOProgress==REPORT || m_QSOProgress==ROGER_REPORT) m_bSentReport=true; - if(m_bSentReport and (m_QSOProgress<REPORT or m_QSOProgress>ROGER_REPORT)) m_bSentReport=false; if(m_mode=="JT4") gen4_(message, &ichk , msgsent, const_cast<int *> (itone), &m_currentMessageType, (FCL)22, (FCL)22); if(m_mode=="JT9") gen9_(message, &ichk, msgsent, const_cast<int *> (itone), @@ -7907,12 +7556,14 @@ void MainWindow::guiUpdate() &m_currentMessageType); if(m_mode=="WSPR") genwspr_(message, msgsent, const_cast<int *> (itone), (FCL)22, (FCL)22); + if(m_mode=="JT4" or m_mode=="JT9" or m_mode=="JT65" or m_mode=="WSPR") msgsent_length=22; if(m_mode=="MSK144" or m_mode=="FT8" or m_mode=="FT4" or m_mode=="FST4" or m_mode=="FST4W" || "Q65" == m_mode) { if(m_mode=="MSK144") { genmsk_128_90_(message, &ichk, msgsent, const_cast<int *> (itone), &m_currentMessageType, (FCL)37, (FCL)37); - if(m_restart) { + if(m_restart && !should_block_generated_transmit ( + QString::fromLatin1 (msgsent), m_tune)) { int nsym=144; if(itone[40]==-40) nsym=40; m_modulator->set_nsym(nsym); @@ -7920,41 +7571,46 @@ void MainWindow::guiUpdate() } if(m_mode=="FT8") { - if(SpecOp::FOX==m_specOp and ui->tabWidget->currentIndex()==1) { - foxTxSequencer(); + if(SpecOp::FOX==m_specOp and ui->tabWidget->currentIndex()==fox_queue_tab_index) { + if (!foxTxSequencer()) return; } else { int i3=0; int n3=0; char ft8msgbits[77]; genft8_(message, &i3, &n3, msgsent, const_cast<char *> (ft8msgbits), const_cast<int *> (itone), (FCL)37, (FCL)37); - int nsym=79; - int nsps=4*1920; - float fsample=48000.0; - float bt=2.0; - float f0=ui->TxFreqSpinBox->value() - m_XIT; - int icmplx=0; - int nwave=nsym*nsps; - gen_ft8wave_(const_cast<int *>(itone),&nsym,&nsps,&bt,&fsample,&f0,foxcom_.wave, - foxcom_.wave,&icmplx,&nwave); - if(SpecOp::FOX == m_specOp) { - //Fox must generate the full Tx waveform, not just an itone[] array. - QString fm = QString::fromStdString(message).trimmed(); - foxGenWaveform(0,fm); - foxcom_.nslots=1; - foxcom_.nfreq=ui->TxFreqSpinBox->value(); - if(m_config.split_mode()) foxcom_.nfreq = foxcom_.nfreq - m_XIT; //Fox Tx freq - QString foxCall=m_config.my_callsign() + " "; - ::memcpy(foxcom_.mycall, foxCall.toLatin1(), sizeof foxcom_.mycall); //Copy Fox callsign into foxcom_ - bool bSuperFox=m_config.superFox(); - auto fname {QDir::toNativeSeparators(m_config.writeable_data_dir().absoluteFilePath("sfox_1.dat")).toLocal8Bit()}; - foxcom_.bMoreCQs=ui->cbMoreCQs->isChecked(); - foxcom_.bSendMsg=ui->cbSendMsg->isChecked(); - memcpy(foxcom_.textMsg, m_freeTextMsg.leftJustified(26,' ').toLatin1(),26); - foxgen_(&bSuperFox, fname.constData(), (FCL)fname.size()); - if(bSuperFox) { - writeFoxTxMsgs(); - sfox_tx(); + if (!should_block_generated_transmit (QString::fromLatin1 (msgsent), m_tune)) { + int nsym=79; + int nsps=4*1920; + float fsample=48000.0; + float bt=2.0; + float f0=ui->TxFreqSpinBox->value() - m_XIT; + int icmplx=0; + int nwave=nsym*nsps; + gen_ft8wave_(const_cast<int *>(itone),&nsym,&nsps,&bt,&fsample,&f0,foxcom_.wave, + foxcom_.wave,&icmplx,&nwave); + if(SpecOp::FOX == m_specOp) { + //Fox must generate the full Tx waveform, not just an itone[] array. + QString fm = QString::fromStdString(message).trimmed(); + clearFoxTxMessages(); + foxGenWaveform(0,fm); + foxcom_.nslots=1; + foxcom_.nfreq=ui->TxFreqSpinBox->value(); + if(m_config.split_mode()) foxcom_.nfreq = foxcom_.nfreq - m_XIT; //Fox Tx freq + QString foxCall=m_config.my_callsign() + " "; + ::memcpy(foxcom_.mycall, foxCall.toLatin1(), sizeof foxcom_.mycall); //Copy Fox callsign into foxcom_ + bool bSuperFox=m_config.superFox(); + auto fname {QDir::toNativeSeparators(m_config.writeable_data_dir().absoluteFilePath("sfox_1.dat")).toLocal8Bit()}; + foxcom_.bMoreCQs=ui->cbMoreCQs->isChecked(); + foxcom_.bSendMsg=ui->cbSendMsg->isChecked(); + memcpy(foxcom_.textMsg, m_freeTextMsg.leftJustified(26,' ').toLatin1(),26); + foxgen_(&bSuperFox, fname.constData(), (FCL)fname.size()); + if(bSuperFox) { + if(sfox_tx()) { + displayFoxTxMsgs(); + writeFoxTxMsgs(); + } + } } } } @@ -7964,14 +7620,16 @@ void MainWindow::guiUpdate() char ft4msgbits[77]; genft4_(message, &ichk, msgsent, const_cast<char *> (ft4msgbits), const_cast<int *>(itone), (FCL)37, (FCL)37); - int nsym=103; - int nsps=4*576; - float fsample=48000.0; - float f0=ui->TxFreqSpinBox->value() - m_XIT; - int nwave=(nsym+2)*nsps; - int icmplx=0; - gen_ft4wave_(const_cast<int *>(itone),&nsym,&nsps,&fsample,&f0,foxcom_.wave, - foxcom_.wave,&icmplx,&nwave); + if (!should_block_generated_transmit (QString::fromLatin1 (msgsent), m_tune)) { + int nsym=103; + int nsps=4*576; + float fsample=48000.0; + float f0=ui->TxFreqSpinBox->value() - m_XIT; + int nwave=(nsym+2)*nsps; + int icmplx=0; + gen_ft4wave_(const_cast<int *>(itone),&nsym,&nsps,&fsample,&f0,foxcom_.wave, + foxcom_.wave,&icmplx,&nwave); + } } if(m_mode=="FST4" or m_mode=="FST4W") { int ichk=0; @@ -7986,84 +7644,136 @@ void MainWindow::guiUpdate() } genfst4_(message,&ichk,msgsent,const_cast<char *> (fst4msgbits), const_cast<int *>(itone), &iwspr, (FCL)37, (FCL)37); - int hmod=1; - if(m_config.x2ToneSpacing()) hmod=2; - if(m_config.x4ToneSpacing()) hmod=4; - int nsps=720; - if(m_TRperiod==30) nsps=1680; - if(m_TRperiod==60) nsps=3888; - if(m_TRperiod==120) nsps=8200; - if(m_TRperiod==300) nsps=21504; - if(m_TRperiod==900) nsps=66560; - if(m_TRperiod==1800) nsps=134400; - nsps=4*nsps; //48000 Hz sampling - int nsym=160; - float fsample=48000.0; - float dfreq=hmod*fsample/nsps; - float f0=ui->TxFreqSpinBox->value() - m_XIT + 1.5*dfreq; - if(m_mode=="FST4W") f0=ui->WSPRfreqSpinBox->value() - m_XIT + 1.5*dfreq; - int nwave=(nsym+2)*nsps; - int icmplx=0; - gen_fst4wave_(const_cast<int *>(itone),&nsym,&nsps,&nwave, - &fsample,&hmod,&f0,&icmplx,foxcom_.wave,foxcom_.wave); - - QString t = QString::fromStdString(message).trimmed(); + if (!should_block_generated_transmit (QString::fromLatin1 (msgsent), m_tune)) { + int hmod=1; + if(m_config.x2ToneSpacing()) hmod=2; + if(m_config.x4ToneSpacing()) hmod=4; + int nsps=720; + if(m_TRperiod==30) nsps=1680; + if(m_TRperiod==60) nsps=3888; + if(m_TRperiod==120) nsps=8200; + if(m_TRperiod==300) nsps=21504; + if(m_TRperiod==900) nsps=66560; + if(m_TRperiod==1800) nsps=134400; + nsps=4*nsps; //48000 Hz sampling + int nsym=160; + float fsample=48000.0; + float dfreq=hmod*fsample/nsps; + float f0=ui->TxFreqSpinBox->value() - m_XIT + 1.5*dfreq; + if(m_mode=="FST4W") f0=ui->WSPRfreqSpinBox->value() - m_XIT + 1.5*dfreq; + int nwave=(nsym+2)*nsps; + int icmplx=0; + gen_fst4wave_(const_cast<int *>(itone),&nsym,&nsps,&nwave, + &fsample,&hmod,&f0,&icmplx,foxcom_.wave,foxcom_.wave); + } } if(m_mode=="Q65") { int i3=-1; int n3=-1; - genq65_(message, &ichk,msgsent, const_cast<int *>(itone), &i3, &n3, (FCL)37, (FCL)37); - int nsps=1800; - if(m_TRperiod==30) nsps=3600; - if(m_TRperiod==60) nsps=7200; - if(m_TRperiod==120) nsps=16000; - if(m_TRperiod==300) nsps=41472; - int nsps4=4*nsps; //48000 Hz sampling - int nsym=85; - float fsample=48000.0; - int nwave=(nsym+2)*nsps4; - int icmplx=0; - float f0=ui->TxFreqSpinBox->value()-m_XIT; - double toneSpacing=fsample/nsps4; - genwave_(const_cast<int *>(itone),&nsym,&nsps4,&nwave, - &fsample,&toneSpacing,&f0,&icmplx,foxcom_.wave,foxcom_.wave); - } - - if(SpecOp::EU_VHF==m_specOp) { - if(m_ntx==2) m_xSent=ui->tx2->text().right(13); - if(m_ntx==3) m_xSent=ui->tx3->text().right(13); + int iflag=0; + if(m_specOp==SpecOp::Q65_PILEUP && !m_q65PileupCopiedLastRxCall.isEmpty () && + m_q65PileupCopiedLastRxCall == Radio::base_callsign (ui->dxCallEntry->text ())) { + iflag=1; + } + m_q65PileupCopiedLastRxCall.clear(); // single-consume: don't let a stale match ride a later Tx + genq65_(message, &ichk,msgsent, const_cast<int *>(itone), &i3, &n3, &iflag, (FCL)37, (FCL)37); + if (!should_block_generated_transmit (QString::fromLatin1 (msgsent), m_tune)) { + int nsps=1800; + if(m_TRperiod==30) nsps=3600; + if(m_TRperiod==60) nsps=7200; + if(m_TRperiod==120) nsps=16000; + if(m_TRperiod==300) nsps=41472; + int nsps4=4*nsps; //48000 Hz sampling + int nsym=85; + float fsample=48000.0; + int nwave=(nsym+2)*nsps4; + int icmplx=0; + float f0=ui->TxFreqSpinBox->value()-m_XIT; + double toneSpacing=fsample/nsps4; + genwave_(const_cast<int *>(itone),&nsym,&nsps4,&nwave, + &fsample,&toneSpacing,&f0,&icmplx,foxcom_.wave,foxcom_.wave); + } } + } + msgsent[msgsent_length]=0; + } - if(SpecOp::FIELD_DAY==m_specOp or SpecOp::RTTY==m_specOp) { - if(m_ntx==2 or m_ntx==3) { - QStringList t=ui->tx2->text().split(' ', SkipEmptyParts); - int n=t.size(); - if (n > 3) m_xSent=t.at(n-2) + " " + t.at(n-1); - } + QString const generated_message = QString::fromLatin1(msgsent); + if (should_block_generated_transmit (generated_message, m_tune)) { + m_currentMessageType = previous_message_type; + m_tx_when_ready = false; + ptt1Timer.stop (); + m_btxok = false; + m_bTxTime = false; + m_restart = false; + if (m_beaconTxController.txLifecycle () == BeaconTx::TxLifecycle::StartRequested) + { + auto const failedPlanId = m_beaconTxController.txPlanId (); + processBeaconActions (m_beaconTxController.txStartResult ( + failedPlanId, false)); + processBeaconActions (m_beaconTxController.txStopped (failedPlanId)); } + show_generated_message_error (); + if (m_auto) auto_tx_mode (false); + if (m_transmitting) { + stopTx (); + } else { + g_iptt = 0; } - msgsent[37]=0; + statusUpdate (); + return; } - { - auto temp = m_currentMessage; - m_currentMessage = QString::fromLatin1(msgsent); - if (m_currentMessage != temp) // check if tx message changed + clear_generated_message_error (); + if (m_lastMessageSent != previous_message + || m_lastMessageType != previous_message_type) { - statusUpdate (); + m_lastMessageSent = previous_message; + m_lastMessageType = previous_message_type; + } + m_currentMessage = generated_message; + if (m_currentMessage != previous_message) statusUpdate (); + + if(m_QSOProgress==REPORT || m_QSOProgress==ROGER_REPORT) m_bSentReport=true; + if(m_bSentReport and (m_QSOProgress<REPORT or m_QSOProgress>ROGER_REPORT)) m_bSentReport=false; + if(m_mode=="FT4" and m_bBestSPArmed) { + m_BestCQpriority=""; + m_bBestSPArmed=false; + ui->pbBestSP->setStyleSheet (""); + } + if(SpecOp::EU_VHF==m_specOp) { + if(m_ntx==2) m_xSent=ui->tx2->text().right(13); + if(m_ntx==3) m_xSent=ui->tx3->text().right(13); + } + if(SpecOp::FIELD_DAY==m_specOp or SpecOp::RTTY==m_specOp) { + if(m_ntx==2 or m_ntx==3) { + QStringList t=ui->tx2->text().split(' ', SkipEmptyParts); + int n=t.size(); + if (n > 3) m_xSent=t.at(n-2) + " " + t.at(n-1); + } + } + if (g_iptt == 1 && m_iptt0 == 0) { + if (m_mode != "JTTY") + { + beginTxEvidenceSession (); } + m_config.transceiver_ptt (true); + m_tx_when_ready = true; + if (m_tx_inhibited) startTxAudioAfterPttDelay (); } + m_bCallingCQ = 6 == m_ntx - || m_currentMessage.contains (QRegularExpression {"^(CQ|QRZ) "}); + || m_currentMessage.contains (cq_or_qrz_message_regexp); m_maxPoints=-1; if (m_tune) { m_currentMessage = "TUNE"; m_currentMessageType = -1; } + bool const superFoxFoxTx = m_mode=="FT8" && m_config.superFox() && m_specOp==SpecOp::FOX; if(m_restart) { - write_all("Tx",m_currentMessage); - if (m_config.TX_messages () and m_mode!="Echo") { + if(!superFoxFoxTx && m_mode!="JTTY") write_all("Tx",m_currentMessage); + if (m_config.TX_messages () and m_mode!="Echo" and !superFoxFoxTx) { ui->decodedTextBrowser2->displayTransmittedText(m_currentMessage.trimmed(),m_mode, ui->TxFreqSpinBox->value(),m_bFastMode,m_TRperiod,m_config.superFox()); } @@ -8170,11 +7880,13 @@ void MainWindow::guiUpdate() if (m_mode != "FST4W" && m_mode != "WSPR" && m_mode!="Echo") { - if(!m_tune) write_all("Tx",m_currentMessage); - if (m_config.TX_messages () && !m_tune && SpecOp::FOX!=m_specOp) - { - ui->decodedTextBrowser2->displayTransmittedText(current_message.trimmed(), - m_mode,ui->TxFreqSpinBox->value(),m_bFastMode,m_TRperiod,m_config.superFox()); + bool const superFoxFoxTx = m_mode=="FT8" && m_config.superFox() && m_specOp==SpecOp::FOX; + if(!m_tune && !superFoxFoxTx && m_mode!="JTTY") { + write_all("Tx",m_currentMessage); + } + if (m_config.TX_messages () && !m_tune && SpecOp::FOX!=m_specOp && m_mode != "JTTY") { + ui->decodedTextBrowser2->displayTransmittedText(current_message.trimmed(), + m_mode,ui->TxFreqSpinBox->value(),m_bFastMode,m_TRperiod,m_config.superFox()); } } @@ -8193,7 +7905,7 @@ void MainWindow::guiUpdate() statusUpdate (); } - if(!m_btxok && m_btxok0 && g_iptt==1) { + if((!m_btxok && m_btxok0 && g_iptt==1)) { stopTx(); if ("1" == m_env.value ("WSJT_TX_BOTH", "0")) { m_txFirst = !m_txFirst; @@ -8201,7 +7913,7 @@ void MainWindow::guiUpdate() } } - if(m_startAnother) { + if(m_startAnother && !m_wav_load_coordinator.isLoading ()) { if(m_mode=="MSK144") { m_wait++; } @@ -8233,35 +7945,78 @@ void MainWindow::guiUpdate() if(m_mode=="Echo" and !m_monitoring and !m_auto and !m_diskData) m_echoRunning=false; if(m_mode=="Q65") { - mem_qmap.lock(); - int n=0; - if(m_decoderBusy) n=1; - ipc_qmap[3]=n; - n=0; - if(m_transmitting) n=m_TRperiod; - ipc_qmap[4]=n; - if(ipc_qmap[0] > 0) { //ndecodes - memcpy(&qmapcom, (char*)ipc_qmap, sizeof(qmapcom)); //Fetch the new decode(s) - readWidebandDecodes(); + bool qmap_hasDecodes=false; + bool qmap_batchComplete=false; + int qmap_requestedKHz=0; + if (qmap_decoder_region_available && ipc_qmap && mem_qmap.lock ()) { + int n=0; + if(decoderBusy ()) n=1; + ipc_qmap->decodes.nWDecoderBusy=n; + n=0; + if(m_transmitting) n=m_TRperiod; + ipc_qmap->decodes.nWTransmitting=n; + if(ipc_qmap->decodes.ndecodes > 0) { + memcpy(&qmapcom, &ipc_qmap->decodes, sizeof(qmapcom)); //Fetch the new decode(s) + qmap_hasDecodes=true; + } + qmap_batchComplete=acknowledgeQMapDecodeBatch(ipc_qmap->decodes); + if(ipc_qmap->decodes.kHzRequested>0) { + qmap_requestedKHz=ipc_qmap->decodes.kHzRequested; + ipc_qmap->decodes.kHzRequested=0; + } + mem_qmap.unlock(); + } + if(qmap_hasDecodes) readWidebandDecodes(); + if(qmap_batchComplete) m_fetched=0; + if(qmap_requestedKHz>0) { + requestNominalFrequencyChange ( + (m_operatingFrequency.rx ()/1000000)*1000000 + 1000*qmap_requestedKHz, + FrequencyRequestOrigin::Automatic); + } + } else { + if (qmap_decoder_region_available && ipc_qmap && mem_qmap.lock ()) { + ipc_qmap->decodes.kHzRequested=0; + mem_qmap.unlock (); + } + } + + { + QByteArray qmap_decodeRow; + QMapClickAction qmap_clickAction=QMapClickAction::None; + bool qmap_hasClickRequest=false; + if (qmap_click_mailbox_available && ipc_qmap && mem_qmap.lock ()) { + if (ipc_qmap->click.action != QMapClickAction::None) { + qmap_decodeRow = QByteArray {ipc_qmap->click.selectedDecode, + static_cast<int> (QMapDecodeRowSize)}; + qmap_clickAction = ipc_qmap->click.action; + ipc_qmap->click.action = QMapClickAction::None; + qmap_hasClickRequest = true; + } + mem_qmap.unlock (); } - if(ipc_qmap[5]>0) { - setRig((m_freqNominal/1000000)*1000000 + 1000*ipc_qmap[5]); - ipc_qmap[5]=0; + // UI and rig updates must not hold the shared-memory lock used by QMAP's decoder. + if (qmap_clickAction == QMapClickAction::Disarm) { + if(m_mode=="Q65" && SpecOp::NONE==m_specOp && ui->autoButton->isChecked()) { + ui->autoButton->click(); + } + } else if (qmap_hasClickRequest) { + auto const record = parseQMapDecodeRecord (qmap_decodeRow); + if (record) qmapCallSandP (*record, + qmap_clickAction == QMapClickAction::SelectAndEnableTx); } - mem_qmap.unlock(); } //Once per second (onesec) if(nsec != m_sec0) { - + logDecoderProgress(); + // qDebug() << "AAA" << nsec % 60; // reset earlyDecodes for 2-stage or 3-stage decoding, or if QRG > 45 MHz - if (m_mode=="FT8" && !m_diskData && ((m_multithreadFT8 && m_ft8DecoderStart<2) or m_freqNominal>45000000)) { + if (m_mode=="FT8" && !m_diskData && ((m_multithreadFT8 && m_ft8DecoderStart<2) or m_operatingFrequency.rx ()>45000000)) { QDateTime now = QDateTime::currentDateTimeUtc(); int s = now.time().toString("ss").toInt(); - if (m_ft8DecoderStart<2 or m_freqNominal>45000000) { - if ((s == 7 || s == 22 ||s == 37 || s == 52) && m_decoderBusy) { - to_jt9(m_ihsym,-1,-1); //Allow jt9 to bail out early, if necessary - decodeDone(); //We better clear a hung decoder status at this point + if (m_ft8DecoderStart<2 or m_operatingFrequency.rx ()>45000000) { + if ((s == 7 || s == 22 ||s == 37 || s == 52) && decoderBusy ()) { + recoverDecoderAtBoundary ("FT8 early-decode boundary", false); } if (s == 10 || s == 25 ||s == 40 || s == 55) earlyDecodes = ""; } @@ -8294,12 +8049,12 @@ void MainWindow::guiUpdate() } if(m_mode=="FST4") chk_FST4_freq_range(); - m_currentBand=m_config.bands()->find(m_freqNominal); + m_currentBand=m_config.bands()->find(m_operatingFrequency.rx ()); if( SpecOp::HOUND == m_specOp ) { qint32 tHound=QDateTime::currentMSecsSinceEpoch()/1000 - m_tAutoOn; //To keep calling Fox, Hound must reactivate Enable Tx at least once every 2 minutes if(m_ntx==1 and m_auto) { - if(tHound >= 180 and tHound < 240 and watchdog_label.text() != " WD:1m ") { + if(tHound >= 180 and tHound < 240 and !normalWatchdogWarningActive ()) { watchdog_label.setText (" HWD:2m "); } if(tHound >= 240 and tHound < 300) { @@ -8385,7 +8140,7 @@ void MainWindow::guiUpdate() if(m_transmitting) { char s[42]; - if(SpecOp::FOX==m_specOp and ui->tabWidget->currentIndex()==1) { + if(SpecOp::FOX==m_specOp and ui->tabWidget->currentIndex()==fox_queue_tab_index) { snprintf(s,sizeof(s),"Tx: %d Slots",foxcom_.nslots); } else { snprintf(s,sizeof(s),"Tx: %s",msgsent); @@ -8407,13 +8162,15 @@ void MainWindow::guiUpdate() } else { s[40]=0; QString t{QString::fromLatin1(s)}; - if(SpecOp::FOX==m_specOp and ui->tabWidget->currentIndex()==1 and foxcom_.nslots==1) { + if(SpecOp::FOX==m_specOp and ui->tabWidget->currentIndex()==fox_queue_tab_index and foxcom_.nslots==1) { t=m_fm1.trimmed(); } - if(m_mode=="FT4") t="Tx: "+ m_currentMessage; + if(m_mode=="FT4" or m_mode == "JTTY") t="Tx: "+ m_currentMessage; tx_status_label.setText(t.trimmed()); } } + } else if(m_generated_message_error && !m_tx_watchdog) { + update_generated_message_error (); } else if(m_monitoring) { if (!m_tx_watchdog) { tx_status_label.setStyleSheet("QLabel{color: #000000; background-color: #00ff00}"); @@ -8456,6 +8213,11 @@ void MainWindow::guiUpdate() tx_status_label.setStyleSheet(""); tx_status_label.setText(""); } + if (m_tx_inhibited && !m_tx_watchdog && !m_generated_message_error) { + tx_status_label.setStyleSheet ( + "QLabel{color: #ffffff; background-color: #cc0000; font-weight: bold}"); + tx_status_label.setText (tr ("TX inhibited")); + } QDateTime t = QDateTime::currentDateTimeUtc(); QString utc = t.date().toString("yyyy MMM dd") + "\n " + @@ -8474,22 +8236,25 @@ void MainWindow::guiUpdate() Q_EMIT m_config.transceiver_volume(m_config.volume()); } + QString const cqOnlyText = m_config.highlight_73() ? QStringLiteral ("CQ/73") : QStringLiteral ("CQ only"); + if (ui->cbCQonly->text () != cqOnlyText) + { + ui->cbCQonly->setText (cqOnlyText); + updateMainWindowControlSizes (); + } if (m_config.highlight_73()) { - ui->cbCQonly->setText("CQ/73"); ui->cbCQonly->setToolTip("CQ or 73 messages only."); } else { - ui->cbCQonly->setText("CQ only"); ui->cbCQonly->setToolTip("CQ messages only."); } check_button_color(); - } //End of guiUpdate void MainWindow::useNextCall() { ui->dxCallEntry->setText(m_nextCall); m_nextCall=""; - if(m_nextGrid.contains(grid_regexp)) { + if(m_nextGrid.contains(MainWindow::grid_regexp)) { ui->dxGridEntry->setText(m_nextGrid); m_ntx=2; ui->txrb2->setChecked(true); @@ -8500,13 +8265,19 @@ void MainWindow::useNextCall() genStdMsgs(m_nextRpt); } -void MainWindow::startTx2() -{ +bool MainWindow::startTx2() +{ + if (m_mode == "JTTY" && !m_tune + && (!m_jttyTxActive || jttyTxCommittedSamples () <= 0)) { + return false; + } bool modulator_active; - bool tci_active = m_tci_audio; + bool const tci_active = (m_mode == "JTTY" && m_jttyTxActive) + ? m_jttyTxUsesTciAudio + : m_tci_audio; if (tci_active) modulator_active=m_tci_mod_active; else modulator_active=m_modulator->isActive (); - if (!modulator_active) { // TODO - not thread safe + if (!modulator_active) { // TODO - not thread safe double fSpread=0.0; double snr=99.0; QString t=ui->tx5->currentText(); @@ -8517,50 +8288,220 @@ void MainWindow::startTx2() if(t.mid(0,1)=="#") snr=t.mid(1,5).toDouble(); if(snr>0.0 or snr < -50.0) snr=99.0; if((m_ntx==6 or m_ntx==7) and m_config.force_call_1st() and - ui->respondComboBox->currentIndex()==0) { + autoRespondPolicy () == AutoRespondPolicy::None) { ui->cbAutoSeq->setChecked(true); - ui->respondComboBox->setCurrentIndex(1); + ui->respondComboBox->setCurrentIndex ( + ui->respondComboBox->findData (static_cast<int> (AutoRespondPolicy::First))); } + auto const beaconPlanId = m_beaconTxController.txPlanId (); + auto const beaconMessage = !m_tune + && m_beaconTxController.txLifecycle () == BeaconTx::TxLifecycle::StartRequested; transmit (snr); + if (beaconMessage) + { + processBeaconActions (m_beaconTxController.txStartResult (beaconPlanId, true)); + } ui->signal_meter_widget->setValue(0,0); if(m_mode=="Echo" and !m_tune) m_bTransmittedEcho=true; if((m_mode=="WSPR" or m_mode=="FST4W") and !m_tune) { if (m_config.TX_messages ()) { t = " Transmitting " + m_mode + " ----------------------- " + - m_config.bands ()->find (m_freqNominal); + m_config.bands ()->find (m_operatingFrequency.rx ()); t=beacon_start_time (m_TRperiod / 2) + ' ' + t.rightJustified (66, '-'); ui->decodedTextBrowser->insertText(t); } write_all("Tx",m_currentMessage); if(m_position != 0) ui->decodedTextBrowser->horizontalScrollBar()->setValue(m_position); } + return true; } + if (m_beaconTxController.txLifecycle () == BeaconTx::TxLifecycle::StartRequested) + { + processBeaconActions (m_beaconTxController.txStartResult ( + m_beaconTxController.txPlanId (), false)); + if (m_transmitting) stopTx (); + } + return false; +} + +void MainWindow::beginTxEvidenceSession () +{ + m_txEvidenceSession = TxEvidence::TxPlaybackDiagnostics::allocateSessionId (); + m_pendingTxStopReason = TxEvidence::TxStopReason::NormalEnd; +} + +void MainWindow::beginTxEvidenceGeneration (qint64 committedEndSample, bool targetKnown) +{ + if (!m_txEvidenceSession.isValid ()) + { + beginTxEvidenceSession (); + } + if (m_txEvidenceSourceSession == m_txEvidenceSession && + m_txEvidenceGeneration.isValid ()) + { + m_txPlaybackDiagnostics.stop (m_txEvidenceSourceSession, + m_txEvidenceGeneration, + TxEvidence::TxStopReason::NormalEnd, 0); + } + m_txEvidenceSourceSession = m_txEvidenceSession; + m_txEvidenceGeneration = TxEvidence::TxPlaybackDiagnostics::allocateGeneration (); + TxEvidence::TxStartSnapshot snapshot; + snapshot.session_id = m_txEvidenceSourceSession; + snapshot.generation = m_txEvidenceGeneration; + snapshot.mode = m_mode; + snapshot.sample_rate_hz = TX_SAMPLE_RATE; + snapshot.committed_end_sample = committedEndSample; + snapshot.target_known = targetKnown; + snapshot.diagnostic = QStringLiteral ("awaiting backend source commit"); + m_txPlaybackDiagnostics.commitStart (snapshot); + auto const sessionId = m_txEvidenceSourceSession; + auto const generation = m_txEvidenceGeneration; + auto const mode = m_mode; + QTimer::singleShot (0, this, [this, sessionId, generation, mode] { + LOG_INFO (QString ("TX playout evidence begin session=%1 generation=%2 mode=%3\n%4") + .arg (sessionId.value ()).arg (generation.value ()).arg (mode) + .arg (m_txPlaybackDiagnostics.diagnosticDump ())); + }); +} + +void MainWindow::recordTxSourceCommit (TxEvidence::TxStartSnapshot const& snapshot) +{ + if (!snapshot.session_id.isValid () || !snapshot.generation.isValid ()) return; + if (!m_txPlaybackDiagnostics.commitStart (snapshot)) + { + m_txPlaybackDiagnostics.commitTarget (snapshot.session_id, snapshot.generation, + snapshot.committed_end_sample, + snapshot.target_known, + snapshot.diagnostic); + } + if ((snapshot.mode == "WSPR" || snapshot.mode == "FST4W") + && snapshot.session_id == m_txEvidenceSourceSession + && snapshot.generation == m_txEvidenceGeneration) + { + processBeaconActions (m_beaconTxController.messageStarted ( + m_beaconTxController.txPlanId ())); + } + LOG_INFO (QString ("TX playout evidence source commit session=%1 generation=%2\n%3") + .arg (snapshot.session_id.value ()).arg (snapshot.generation.value ()) + .arg (m_txPlaybackDiagnostics.diagnosticDump ())); +} + +void MainWindow::recordRawTxPlayout (TxEvidence::TxRawPlayoutSnapshot const& snapshot) +{ + if (m_txEvidenceSourceSession.isValid () && m_txEvidenceGeneration.isValid ()) + { + m_txPlaybackDiagnostics.observe (m_txEvidenceSourceSession, + m_txEvidenceGeneration, snapshot); + } +} + +void MainWindow::noteTxStopReason (TxEvidence::TxStopReason reason) +{ + if (m_pendingTxStopReason == TxEvidence::TxStopReason::NormalEnd && + reason != TxEvidence::TxStopReason::NormalEnd) + { + m_pendingTxStopReason = reason; + } +} + +void MainWindow::noteTxModeChange (QString const& mode) +{ + if (mode != m_mode) cancelPendingFt8Decode ("mode changed"); + if (mode != m_mode && m_beaconTxController.active ()) + { + processBeaconActions (m_beaconTxController.exitMode ()); + } + if (mode != m_mode && (m_transmitting || g_iptt == 1 || m_jttyTxActive)) + { + noteTxStopReason (TxEvidence::TxStopReason::ModeChange); + } +} + +int MainWindow::txStopTailMs (bool tciAudio) const +{ + return TxEvidence::TxPlaybackDiagnostics::decisionFor ( + m_pendingTxStopReason, tciAudio || m_mode == "JTTY").tail_ms; +} + +void MainWindow::stopTxEvidence (int tailMs) +{ + if (!m_txEvidenceSession.isValid ()) return; + if (!m_txEvidenceGeneration.isValid () || + m_txEvidenceSourceSession != m_txEvidenceSession) + { + beginTxEvidenceGeneration (); + } + m_txPlaybackDiagnostics.stop (m_txEvidenceSession, m_txEvidenceGeneration, + m_pendingTxStopReason, tailMs); + auto const sessionId = m_txEvidenceSession; + auto const generation = m_txEvidenceGeneration; + QTimer::singleShot (tailMs + 1, this, [this, sessionId, generation] { + LOG_INFO (QString ("TX playout evidence stop session=%1 generation=%2\n%3") + .arg (sessionId.value ()).arg (generation.value ()) + .arg (m_txPlaybackDiagnostics.diagnosticDump ())); + }); + m_txEvidenceSession = TxEvidence::TxSessionId::invalid (); +} + +void MainWindow::captureJttyTxEvidenceTotals (qint64 servedSamples, + qint64 totalSamples, + QString const& diagnostic) +{ + if (!m_txEvidenceSourceSession.isValid () || !m_txEvidenceGeneration.isValid ()) return; + if (servedSamples >= 0) + { + m_txPlaybackDiagnostics.observeSourceProgress (m_txEvidenceSourceSession, + m_txEvidenceGeneration, + servedSamples, totalSamples, + diagnostic); + } + m_txPlaybackDiagnostics.commitTarget (m_txEvidenceSourceSession, + m_txEvidenceGeneration, + totalSamples > 0 ? totalSamples - 1 : -1, + totalSamples > 0, + servedSamples < 0 ? diagnostic : QString ()); } void MainWindow::stopTx() { - if (m_tci_audio) Q_EMIT m_config.transceiver_modulator_stop(); + bool const tciAudio = (m_mode == "JTTY" && m_transmitting) + ? m_jttyTxUsesTciAudio + : m_tci_audio; + int const stopTxDelayMs = txStopTailMs (tciAudio); + if (m_mode == "JTTY" && m_jttyTxActive) { + interruptJttyTx(); + } + if (tciAudio) Q_EMIT m_config.transceiver_modulator_stop(); else Q_EMIT endTransmitMessage (); + if (m_mode == "JTTY" && !tciAudio) { + Q_EMIT endJttyStream (); + } m_btxok = false; m_transmitting = false; g_iptt=0; - if (!m_tx_watchdog) { + if (!m_tx_watchdog && !m_generated_message_error) { tx_status_label.setStyleSheet(""); tx_status_label.setText(""); } - if (m_tci_audio) { - ptt0Timer.start(0); + if (tciAudio) { + ptt0Timer.start(stopTxDelayMs); } else { - ptt0Timer.start(200); //end-of-transmission sequencer delay + ptt0Timer.start(stopTxDelayMs); monitor (true); statusUpdate (); } + stopTxEvidence (stopTxDelayMs); } void MainWindow::stopTx2() { - if (m_tci_audio) { + // Preserve the originating plan IDs for delayed PTT-off completion; the live + // mode may no longer be the mode that started Tx or Tune. + auto const beaconTxPlanId = m_beaconTxController.txPlanId (); + auto const beaconTunePlanId = m_beaconTxController.tunePlanId (); + bool const tciAudio = (m_mode == "JTTY") ? m_jttyTxUsesTciAudio : m_tci_audio; + if (tciAudio) { Q_EMIT m_config.transceiver_ptt (false); //Lower PTT monitor (true); statusUpdate (); @@ -8573,15 +8514,34 @@ void MainWindow::stopTx2() on_stopTxButton_clicked (); m_nTx73 = 0; } - if(((m_mode=="WSPR" or m_mode=="FST4W") and m_ntr==-1) and !m_tuneup) { - m_wideGraph->setWSPRtransmitted(); - WSPR_scheduling (); - m_ntr=0; - } + processBeaconActions (m_beaconTxController.txStopped (beaconTxPlanId)); + if (m_beaconTxController.tuneKind () != BeaconTx::TuneKind::None) + { + processBeaconActions (m_beaconTxController.tuneCompleted (beaconTunePlanId)); + } keep_last_tx_label = true; last_tx_label.setText(tr ("Last Tx: %1").arg (m_currentMessage.trimmed())); } +QString MainWindow::expandTxMacros(QString const& message) const +{ + auto const parts = message.split (' ', SkipEmptyParts); + if (parts.isEmpty () || + (parts.front ().compare ("$DX", Qt::CaseInsensitive) != 0 && + parts.front ().compare ("$DXCALL", Qt::CaseInsensitive) != 0)) { + return message; + } + + auto const dxBase = Radio::base_callsign (m_hisCall); + if (dxBase.isEmpty ()) { + return message; + } + + auto const macroIndex = message.indexOf (parts.front ()); + auto const rest = message.mid (macroIndex + parts.front ().size ()).trimmed (); + return rest.isEmpty () ? dxBase : dxBase + " " + rest; +} + void MainWindow::ba2msg(QByteArray ba, char message[]) //ba2msg() { int iz=ba.length(); @@ -8625,6 +8585,7 @@ void MainWindow::set_dateTimeQSO(int m_ntx) void MainWindow::set_ntx(int n) //set_ntx() { + if (n != m_ntx) clear_generated_message_error (); m_ntx=n; } @@ -8632,6 +8593,7 @@ void MainWindow::on_txrb1_toggled (bool status) { if (status) { if (ui->tx1->isEnabled ()) { + clear_generated_message_error (); m_ntx = 1; set_dateTimeQSO (-1); // we reset here as tx2/tx3 is used for start times } @@ -8651,9 +8613,15 @@ bool MainWindow::elide_tx1_not_allowed () const || (my_callsign != m_baseCall && !shortList (my_callsign)); } -void MainWindow::on_txrb1_doubleClicked () +void MainWindow::toggle_tx1_enabled_preference () { ui->tx1->setEnabled (elide_tx1_not_allowed () || !ui->tx1->isEnabled ()); + m_tx1_enabled_preference = ui->tx1->isEnabled (); +} + +void MainWindow::on_txrb1_doubleClicked () +{ + toggle_tx1_enabled_preference (); if (!ui->tx1->isEnabled ()) { // leave time for clicks to complete before setting txrb2 QTimer::singleShot (500, ui->txrb2, SLOT (click ())); @@ -8664,6 +8632,7 @@ void MainWindow::on_txrb2_toggled (bool status) { // Tx 2 means we already have CQ'd so good reference if (status) { + clear_generated_message_error (); m_ntx=2; set_dateTimeQSO (m_ntx); } @@ -8673,6 +8642,7 @@ void MainWindow::on_txrb3_toggled(bool status) { // Tx 3 means we should have already have done Tx 1 so good reference if (status) { + clear_generated_message_error (); m_ntx=3; set_dateTimeQSO(m_ntx); } @@ -8681,23 +8651,20 @@ void MainWindow::on_txrb3_toggled(bool status) void MainWindow::on_txrb4_toggled (bool status) { if (status) { + clear_generated_message_error (); m_ntx=4; } } void MainWindow::on_txrb4_doubleClicked () { - // RR73 only allowed if not a type 2 compound callsign - auto const& my_callsign = m_config.my_callsign (); - auto is_compound = my_callsign != m_baseCall; - m_send_RR73 = !((is_compound && !shortList (my_callsign)) || m_send_RR73); - if(m_mode=="FT4") m_send_RR73=true; - genStdMsgs (m_rpt); + set_rr73_tx4 (!send_rr73_for_tx4 ()); } void MainWindow::on_txrb5_toggled (bool status) { if (status) { + clear_generated_message_error (); m_ntx = 5; } } @@ -8710,123 +8677,78 @@ void MainWindow::on_txrb5_doubleClicked () void MainWindow::on_txrb6_toggled(bool status) { if (status) { + clear_generated_message_error (); m_ntx=6; - if (ui->txrb6->text().contains (QRegularExpression {"^(CQ|QRZ) "})) set_dateTimeQSO(-1); + if (ui->txrb6->text().contains (cq_or_qrz_message_regexp)) set_dateTimeQSO(-1); } - if(m_mode=="MSK144" && !keep_msk144_frequency && m_msk144basefreq > 0 && !programStart && !m_band_changed) { - setRig(m_msk144basefreq); // reset MSK144 QSY - msk144qsy = false; + if(m_mode=="MSK144" && !programStart && !m_band_changed && !keep_msk144_frequency + && hasMsk144BaseFrequency ()) { + if (requestNominalFrequencyChange (m_msk144basefreq, FrequencyRequestOrigin::User)) + { + msk144qsy = false; + } } } -void MainWindow::on_txb1_clicked() -{ - if (ui->tx1->isEnabled ()) { - m_ntx=1; - m_QSOProgress = REPLYING; - ui->txrb1->setChecked(true); - if(m_transmitting) m_restart=true; - } - else { - on_txb2_clicked (); - } -} void MainWindow::on_txb1_doubleClicked() { - ui->tx1->setEnabled (elide_tx1_not_allowed () || !ui->tx1->isEnabled ()); + toggle_tx1_enabled_preference (); } -void MainWindow::on_txb2_clicked() -{ - m_ntx=2; - m_QSOProgress = REPORT; - ui->txrb2->setChecked(true); - if(m_transmitting) m_restart=true; -} -void MainWindow::on_txb3_clicked() -{ - m_ntx=3; - m_QSOProgress = ROGER_REPORT; - ui->txrb3->setChecked(true); - if(m_transmitting) m_restart=true; -} -void MainWindow::on_txb4_clicked() -{ - m_ntx=4; - m_QSOProgress = ROGERS; - ui->txrb4->setChecked(true); - if(m_transmitting) m_restart=true; -} void MainWindow::on_txb4_doubleClicked() { - // RR73 only allowed if not a type 2 compound callsign - auto const& my_callsign = m_config.my_callsign (); - auto is_compound = my_callsign != m_baseCall; - m_send_RR73 = !((is_compound && !shortList (my_callsign)) || m_send_RR73); - if(m_mode=="FT4") m_send_RR73=true; - genStdMsgs (m_rpt); + set_rr73_tx4 (!send_rr73_for_tx4 ()); } -void MainWindow::on_txb5_clicked() -{ - m_ntx=5; - m_QSOProgress = SIGNOFF; - ui->txrb5->setChecked(true); - if(m_transmitting) m_restart=true; -} void MainWindow::on_txb5_doubleClicked() { genStdMsgs (m_rpt, true); } -void MainWindow::on_txb6_clicked() + +void MainWindow::doubleClickOnCall2(QString const& line, QString const& word, Qt::KeyboardModifiers modifiers) { - m_ntx=6; - m_QSOProgress = CALLING; - set_dateTimeQSO(-1); - ui->txrb6->setChecked(true); - if(m_transmitting) m_restart=true; - if(m_mode=="MSK144" && !keep_msk144_frequency && m_msk144basefreq > 0 && !programStart && !m_band_changed) { - setRig(m_msk144basefreq); // reset MSK144 QSY - msk144qsy = false; - } + handleDecodeSelection(line, word, modifiers, + DecodedMessageReaction::SelectionOrigin::ManualLeftPane); } -void MainWindow::doubleClickOnCall2(Qt::KeyboardModifiers modifiers) +void MainWindow::doubleClickOnCall(QString const& line, QString const& word, Qt::KeyboardModifiers modifiers) { -//Confusing: come here after double-click on left text window, not right window. - m_decodedText2=true; - doubleClickOnCall(modifiers); - m_decodedText2=false; + handleDecodeSelection(line, word, modifiers, + DecodedMessageReaction::SelectionOrigin::ManualRightPane); } -void MainWindow::doubleClickOnCall(Qt::KeyboardModifiers modifiers) +void MainWindow::handleDecodeSelection( + QString const& line, QString const& word, Qt::KeyboardModifiers modifiers, + DecodedMessageReaction::SelectionOrigin selection_origin) { m_bMyCallStd=stdCall(m_config.my_callsign()); //ft8md m_bHisCallStd=stdCall(m_hisCall); //ft8md set_dateTimeQSO(-1); // reset our QSO start time - QTextCursor cursor; if(m_mode=="FST4W") { MessageBox::information_message (this, "Double-click not available for FST4W mode"); return; } - if(m_decodedText2) { - cursor=ui->decodedTextBrowser->textCursor(); - } else { - cursor=ui->decodedTextBrowser2->textCursor(); + if(m_mode=="JTTY") { + m_deCall = word; + ui->dxCallEntry->setText(m_deCall); + return; + } + DecodedText message {line.trimmed().left(61).remove("TU; ")}; + if(SpecOp::HOUND==m_specOp && (message.string().mid(4,2).contains("15") or message.string().mid(4,2).contains("45"))) { + statusBar()->showMessage(tr("Hound: select a Fox at :00 or :30."), 5000); + return; } - DecodedText message {cursor.block().text().trimmed().left(61).remove("TU; ")}; - if(SpecOp::HOUND==m_specOp && (message.string().mid(4,2).contains("15") or message.string().mid(4,2).contains("45"))) return; // ignore stations calling in the wrong time slot // if(message.string().contains(";") && message.string().contains("<")) { // QVector<qint32> Freq = {1840000,3573000,7074000,10136000,14074000,18100000,21074000,24915000,28074000,50313000,70154000,3575000,7047500,10140000,14080000,18104000,21140000,24919000,28180000,50318000}; // for(int i=0; i<Freq.length()-1; i++) { -// int kHzdiff=m_freqNominal - Freq[i]; +// int kHzdiff=m_operatingFrequency.rx () - Freq[i]; // if(qAbs(kHzdiff) < 3000 ) { // m_bTxTime=false; // if (m_auto) auto_tx_mode (false); @@ -8840,19 +8762,27 @@ void MainWindow::doubleClickOnCall(Qt::KeyboardModifiers modifiers) // } // } // } - if(modifiers==(Qt::ShiftModifier + Qt::ControlModifier + Qt::AltModifier)) { - //### What was the purpose of this ??? ### - cursor.setPosition(0); - } else { - cursor.setPosition(cursor.selectionStart()); - } - if(SpecOp::FOX==m_specOp and m_decodedText2) { + if(SpecOp::FOX==m_specOp + && selection_origin == DecodedMessageReaction::SelectionOrigin::ManualLeftPane) { if(m_houndQueue.count()<10 and m_nSortedHounds>0) { - QString t=cursor.block().text(); - selectHound(t, modifiers==(Qt::AltModifier)); // alt double-click gets put at top of queue + auto const hound_line = modifiers==(Qt::ShiftModifier + Qt::ControlModifier + Qt::AltModifier) + ? ui->decodedTextBrowser->document()->firstBlock().text() + : line; + selectHound(hound_line, modifiers==(Qt::AltModifier)); // alt double-click gets put at top of queue } return; } + QString hiscall; + QString hisgrid; + message.deCallAndGrid(/*out*/hiscall,hisgrid); + if (is77BitMode () && modifiers!=Qt::AltModifier + && Radio::is_77bit_nonstandard_callsign (m_config.my_callsign ()) + && Radio::is_77bit_nonstandard_callsign (hiscall)) { + auto const& msg = tr ("A QSO between two stations with nonstandard callsigns won't work.\n\n" + "Auto Seq would get stuck in an endless loop."); + MessageBox::information_message (this, msg); + return; + } int nmod = fmod(double(message.timeInSeconds()),2.0*m_TRperiod); if(ui->txFirstCheckBox->isVisible() && !ui->txFirstCheckBox->isEnabled() && ( (nmod!=0 && !ui->txFirstCheckBox->isChecked()) or @@ -8868,567 +8798,352 @@ void MainWindow::doubleClickOnCall(Qt::KeyboardModifiers modifiers) m_muted = true; // Don't play alert sounds again m_bDoubleClicked = true; m_hisCall0 = m_hisCall; - processMessage (message, modifiers); + processMessage (message, modifiers, selection_origin); // pressing ALT while double-clicking on a call only adds the callsign to DX Call Box if(SpecOp::FOX!=m_specOp && modifiers==Qt::AltModifier) { m_bDoubleClicked = false; if (m_auto) auto_tx_mode (false); } // MSK144 QSY: set RF freq so next received MSK144 signal is at 1500 Hz - if(m_mode=="MSK144" && message.frequencyOffset() > 0 && (modifiers==Qt::ControlModifier or modifiers==(Qt::ControlModifier+Qt::AltModifier))) { + if(m_mode=="MSK144" && hasMsk144BaseFrequency () && message.frequencyOffset() > 0 + && (modifiers==Qt::ControlModifier or modifiers==(Qt::ControlModifier+Qt::AltModifier))) { Frequency dial_frequency = m_msk144basefreq + (message.frequencyOffset() - 1500); - keep_msk144_frequency = true; - monitor (true); - setRig(dial_frequency); - ui->labDialFreq->setText (Radio::pretty_frequency_MHz_string (dial_frequency)); - msk144qsy = true; + if (nominalFrequencyChangeAllowed (FrequencyRequestOrigin::User)) + { + keep_msk144_frequency = true; + monitor (true); + if (requestNominalFrequencyChange (dial_frequency, FrequencyRequestOrigin::User)) + { + ui->labDialFreq->setText (Radio::pretty_frequency_MHz_string (dial_frequency)); + msk144qsy = true; + } + keep_msk144_frequency = false; + } if(modifiers==Qt::AltModifier or modifiers==(Qt::ControlModifier+Qt::AltModifier)) { m_bDoubleClicked = false; if (m_auto) auto_tx_mode (false); } - keep_msk144_frequency = false; } m_muted = false; } } -void MainWindow::processMessage (DecodedText const& message, Qt::KeyboardModifiers modifiers) -{ - // decode keyboard modifiers we are interested in - auto shift = modifiers.testFlag (Qt::ShiftModifier); - auto ctrl = modifiers.testFlag (Qt::ControlModifier); - auto auto_seq = ui->cbAutoSeq->isVisible () && ui->cbAutoSeq->isEnabled () && ui->cbAutoSeq->isChecked (); - // basic mode sanity checks - auto const& parts = message.clean_string ().split (' ', SkipEmptyParts); - if (parts.size () < 5) return; - - auto const& mode = parts.at (4).left (1); - if (("JT65" == m_mode && mode != "#") - || ("JT9" == m_mode && mode != "@") - || ("MSK144" == m_mode && !("&" == mode || "^" == mode)) - || ("Q65" == m_mode && mode.left (1) != ":")) { - return; //Currently we do auto-sequencing only in FT4, FT8, MSK144, FST4, and Q65 - } - - //Skip the rest if no decoded text extracted - int frequency = message.frequencyOffset(); - if (message.isTX()) { - if (!m_config.enable_VHF_features()) { - if(!shift) ui->RxFreqSpinBox->setValue(frequency); //Set Rx freq - if((ctrl or shift) and !ui->cbHoldTxFreq->isChecked ()) { - ui->TxFreqSpinBox->setValue(frequency); //Set Tx freq +DecodedMessageReaction::QsoReactionSnapshot MainWindow::qsoReactionSnapshot( + Qt::KeyboardModifiers modifiers) const +{ + return qsoReactionSnapshot(modifiers, DecodedMessageReaction::SelectionOrigin::None); +} + +DecodedMessageReaction::QsoReactionSnapshot MainWindow::qsoReactionSnapshot( + Qt::KeyboardModifiers modifiers, + DecodedMessageReaction::SelectionOrigin selection_origin) const +{ + DecodedMessageReaction::QsoReactionSnapshot snapshot; + snapshot.mode = m_mode; + snapshot.specOp = m_specOp; + snapshot.myCall = m_config.my_callsign(); + snapshot.baseCall = m_baseCall; + snapshot.dxCall = ui->dxCallEntry->text(); + snapshot.hisCall = m_hisCall; + snapshot.hisGrid = m_hisGrid; + snapshot.respondPolicy = autoRespondPolicy (); + snapshot.trPeriod = m_TRperiod; + snapshot.nominalFrequency = m_operatingFrequency.rx (); + snapshot.rxFrequency = ui->RxFreqSpinBox->value(); + snapshot.txFrequency = ui->TxFreqSpinBox->value(); + snapshot.qsoProgress = m_QSOProgress; + snapshot.selectedTxMessage = m_ntx; + snapshot.currentMessageType = m_currentMessageType; + snapshot.sentReport = m_bSentReport; + snapshot.shortMessages = m_bShMsgs; + snapshot.sendRr73 = send_rr73_for_tx4 (); + snapshot.transmitting = m_transmitting; + snapshot.transmittingSignoff = m_transmitting + && message_is_73(m_currentMessageType, m_currentMessage.split(' ', SkipEmptyParts)); + snapshot.doubleClicked = m_bDoubleClicked; + snapshot.doubleClickAfterCqFrequency = m_bDoubleClickAfterCQnnn; + snapshot.selectionOrigin = selection_origin != DecodedMessageReaction::SelectionOrigin::None + ? selection_origin + : (m_bDoubleClicked ? DecodedMessageReaction::SelectionOrigin::ManualLeftPane + : DecodedMessageReaction::SelectionOrigin::None); + snapshot.modifiers.shift = modifiers.testFlag(Qt::ShiftModifier); + snapshot.modifiers.ctrl = modifiers.testFlag(Qt::ControlModifier); + snapshot.modifiers.alt = modifiers.testFlag(Qt::AltModifier); + snapshot.fastMode = m_bFastMode; + snapshot.transceiverOnline = m_config.is_transceiver_online(); + snapshot.nominalQsyAllowed = rigFrequencyChangeDecision ( + RigFrequencyChangePolicy::ChangeKind::NominalQsy).allowed; + snapshot.enableVhfFeatures = m_config.enable_VHF_features(); + snapshot.holdTxFrequency = ui->cbHoldTxFreq->isChecked(); + snapshot.rxFrequencyEnabled = ui->RxFreqSpinBox->isEnabled(); + snapshot.tx1Enabled = ui->tx1->isEnabled(); + snapshot.autoEnabled = m_auto; + snapshot.autoButtonChecked = ui->autoButton->isChecked(); + snapshot.autoReply = m_bAutoReply; + snapshot.callingCq = m_bCallingCQ; + snapshot.sentFirst73 = m_sentFirst73; + snapshot.autoSequenceChecked = ui->cbAutoSeq->isChecked(); + snapshot.autoSequenceEnabled = ui->cbAutoSeq->isVisible() + && ui->cbAutoSeq->isEnabled() && ui->cbAutoSeq->isChecked(); + snapshot.quickCall = m_config.quick_call(); + snapshot.repeatTx = m_config.repeat_Tx(); + snapshot.loggingEnabled = m_config.prompt_to_log() || m_config.autoLog(); + snapshot.contestHintShown = m_contestModeHintShown; + snapshot.ncccSprint = m_config.NCCC_Sprint(); + snapshot.tx73Count = m_nTx73; + snapshot.waitFeaturesEnabled = m_config.Wait_features_enabled(); + snapshot.waitAndCall = wait_and_call; + snapshot.noWaitAndCall = no_wait_and_call; + snapshot.waitAndCallControlChecked = ui->DX_Call_Button->isChecked(); + snapshot.fullDuplexEnabled = ui->actionFull_Duplex_Mode->isChecked(); + snapshot.txing = m_txing; + return snapshot; +} + +void MainWindow::applyQsoReactionPlan(DecodedMessageReaction::QsoReactionPlan const& plan, + DecodedText const& message, bool * block_right_display) +{ + bool contestHintQueued = false; + DecodedMessageReaction::ContestHint contestHint {}; + for (auto const& effect : plan.effects) { + if (effect.kind == DecodedMessageReaction::QsoReactionEffect::Kind::QueueContestHint) { + m_contestModeHintShown = true; + if (!contestHintQueued) { + contestHint = effect.contestHint; + contestHintQueued = true; } + continue; } - return; - } - - // check for CQ with listening frequency - if (parts.size () >= 7 - && m_bFastMode - && "CQ" == parts[5] - && m_config.is_transceiver_online ()) { - bool ok; - auto kHz = parts[6].toUInt (&ok); - if (ok && kHz >= 10 && 3 == parts[6].size ()) { - // QSY Freq for answering CQ nnn - setRig (m_freqNominal / 1000000 * 1000000 + 1000 * kHz); - ui->decodedTextBrowser2->displayQSY (QString {"QSY %1"}.arg (m_freqNominal / 1e6, 7, 'f', 3)); - if(m_mode=="MSK144") m_msk144basefreq = m_freqNominal / 1000000 * 1000000 + 1000 * kHz; // MSK144 QSY - } - } - - int nmod = fmod(double(message.timeInSeconds()),2.0*m_TRperiod); - m_txFirst=(nmod!=0); - if(SpecOp::HOUND == m_specOp) m_txFirst=false; //Hound must not transmit first - if(SpecOp::FOX == m_specOp) m_txFirst=true; //Fox must always transmit first - ui->txFirstCheckBox->setChecked(m_txFirst); - - auto const& message_words = message.messageWords (); - if (message_words.size () < 3) return; - - QString hiscall; - QString hisgrid; - message.deCallAndGrid(/*out*/hiscall,hisgrid); - - // prevent starting a QSO with yourself - if (m_bDoubleClicked && hiscall==m_baseCall) return; - - // don't call CQ when double-clicking on the final "73" message of your QSO - if (m_bDoubleClicked && message.clean_string().remove("<").remove(">").contains((" " + m_baseCall + " ")) - && message.clean_string().remove("<").remove(">").contains(" " + hiscall + " ") && message.clean_string().mid(22).contains(" 73")) return; - - if(message.clean_string ().contains(hiscall+"/R")) { - hiscall+="/R"; - ui->dxCallEntry->setText(hiscall); - } - if(message.clean_string ().contains(hiscall+"/P")) { - hiscall+="/P"; - ui->dxCallEntry->setText(hiscall); - } - - QStringList w=message.clean_string ().mid(22).remove("<").remove(">").split(" ",SkipEmptyParts); - int nw=w.size(); - if(nw>=4) { - if(message_words.size()<4) return; - int n=w.at(nw-2).toInt(); - if(n>=520001 and n<=592047) { - hiscall=w.at(1); - hisgrid=w.at(nw-1); - } + applyQsoReactionEffect(effect, message, block_right_display); } - - bool is_73 = message_words.filter (QRegularExpression {"^(73|RR73)$"}).size (); - if (!is_73 and !message.isStandardMessage() and !message.clean_string ().contains("<")) { - qDebug () << "Not processing message - hiscall:" << hiscall << "hisgrid:" << hisgrid - << message.clean_string () << message.isStandardMessage(); - return; + if (contestHintQueued) { + QTimer::singleShot(0, this, [this, contestHint] {showContestHint(contestHint);}); } +} - if ((message.isJT9 () and m_mode != "JT9" and m_mode != "JT4") or - (message.isJT65 () and m_mode != "JT65" and m_mode != "JT4")) { - // We are not allowing mode change, so don't process decode - return; +void MainWindow::applyQsoReactionEffect(DecodedMessageReaction::QsoReactionEffect const& effect, + DecodedText const& message, bool * block_right_display) +{ + using Effect = DecodedMessageReaction::QsoReactionEffect; + switch (effect.kind) { + case Effect::Kind::SetRxFrequency: + ui->RxFreqSpinBox->setValue(effect.intValue); + break; + case Effect::Kind::SetTxFrequency: + ui->TxFreqSpinBox->setValue(effect.intValue); + break; + case Effect::Kind::ApplyFastCqQsy: + RigFrequencyChangePolicy::commitIfAccepted ( + [this, &effect] { + return requestNominalFrequencyChange ( + effect.frequency, + effect.userInitiated ? FrequencyRequestOrigin::User : FrequencyRequestOrigin::Automatic); + }, + [this, &effect] { + ui->decodedTextBrowser2->displayQSY (effect.text); + if (effect.boolValue) m_msk144basefreq = effect.frequency; + }); + break; + case Effect::Kind::RejectNominalQsy: + nominalFrequencyChangeAllowed (FrequencyRequestOrigin::User); + break; + case Effect::Kind::SetTxFirst: + m_txFirst = effect.boolValue; + ui->txFirstCheckBox->setChecked(m_txFirst); + break; + case Effect::Kind::SetTxMessage: + setTxMsg(effect.intValue); + break; + case Effect::Kind::SetTxMessageIndex: + m_ntx = effect.intValue; + break; + case Effect::Kind::CheckTxMessage: + txNextButtons().at(effect.intValue - 1)->setChecked(true); + break; + case Effect::Kind::ClickTxMessage: + txNextButtons().at(effect.intValue - 1)->click(); + break; + case Effect::Kind::SetQsoProgress: + m_QSOProgress = effect.progress; + break; + case Effect::Kind::SetDxCall: + ui->dxCallEntry->setText(effect.text); + break; + case Effect::Kind::ClearDxGrid: + ui->dxGridEntry->clear(); + break; + case Effect::Kind::SetDxGrid: + if (ui->dxGridEntry->text().mid(0, 4) != effect.text) ui->dxGridEntry->setText(effect.text); + break; + case Effect::Kind::SetReport: + ui->rptSpinBox->setValue(effect.intValue); + break; + case Effect::Kind::SetReceivedExchange: + m_xRcvd = effect.text; + break; + case Effect::Kind::SetCallingCq: + m_bCallingCQ = effect.boolValue; + break; + case Effect::Kind::SetMaxPoints: + m_maxPoints = effect.intValue; + break; + case Effect::Kind::SetRestart: + m_restart = effect.boolValue; + break; + case Effect::Kind::SetDoubleClicked: + m_bDoubleClicked = effect.boolValue; + break; + case Effect::Kind::SetDoubleClickAfterCqFrequency: + m_bDoubleClickAfterCQnnn = effect.boolValue; + break; + case Effect::Kind::SetTuMessage: + m_bTUmsg = effect.boolValue; + break; + case Effect::Kind::SetNextCall: + m_nextCall = effect.text; + break; + case Effect::Kind::SetNoLogging: + no_logging = effect.boolValue; + break; + case Effect::Kind::SetNoWaitAndCall: + no_wait_and_call = effect.boolValue; + break; + case Effect::Kind::SetBlockRightDisplay: + if (block_right_display) *block_right_display = effect.boolValue; + break; + case Effect::Kind::SetAutoEnabled: + auto_tx_mode(effect.boolValue); + break; + case Effect::Kind::RefreshQsoPaneIfChanged: + refreshQsoPane(message); + break; + case Effect::Kind::Lookup: + lookup(); + break; + case Effect::Kind::CaptureHisGrid: + m_hisGrid = ui->dxGridEntry->text(); + break; + case Effect::Kind::ExtractReceivedReport: + message.report(m_baseCall, Radio::base_callsign(ui->dxCallEntry->text()), m_rptRcvd); + break; + case Effect::Kind::GenerateStandardMessages: + genStdMsgs(QString::number(ui->rptSpinBox->value())); + break; + case Effect::Kind::RecordRr73Received: + m_dateTimeRcvdRR73 = QDateTime::currentDateTimeUtc(); + break; + case Effect::Kind::RequestLogQso: + logQSOTimer.start(0); + break; + case Effect::Kind::RequestLogQsoUnlessSuppressed: + if (!no_logging) logQSOTimer.start(0); + break; + case Effect::Kind::CeaseAutoTx: + cease_auto_Tx_after_QSO(); + break; + case Effect::Kind::StopTx: + on_stopTxButton_clicked(); + break; + case Effect::Kind::ClickStopTx: + ui->stopTxButton->click(); + break; + case Effect::Kind::LogStopped: + LOG_INFO("STOPPED!"); + break; + case Effect::Kind::StartTxAgainTimer: + TxAgainTimer.start(effect.intValue); + break; + case Effect::Kind::ResetWatchdog: + tx_watchdog(false); + break; + case Effect::Kind::StopWaitCallTimer: + stopWCTimer.stop(); + break; + case Effect::Kind::DisableWaitAndCallControl: + if (ui->DX_Call_Button->isChecked()) ui->DX_Call_Button->click(); + break; + case Effect::Kind::StartWaitReplyTimer: + stopWRTimer.start(effect.intValue); + break; + case Effect::Kind::StartWaitCallTimer: + stopWCTimer.start(effect.intValue); + break; + case Effect::Kind::ScheduleStopTx: + QTimer::singleShot(effect.intValue, this, [this] {on_stopTxButton_clicked();}); + break; + case Effect::Kind::ScheduleNcccAutoReset: + QTimer::singleShot(effect.intValue, this, [this] { + auto_tx_mode(false); + if (m_auto) ui->autoButton->click(); + }); + break; + case Effect::Kind::ScheduleNoLoggingReset: + QTimer::singleShot(effect.intValue, this, [=] {no_logging = false;}); + break; + case Effect::Kind::ScheduleAutoFlagOff: + QTimer::singleShot(effect.intValue, this, [=] {m_auto = false;}); + break; + case Effect::Kind::QueueContestHint: + break; + case Effect::Kind::ProcessSyntheticMessageNow: + processSyntheticMessage(message); + break; } +} - // ignore calls by other hounds - if (SpecOp::HOUND == m_specOp - && message.messageWords ().indexOf (QRegularExpression {R"(R\+-[0-9]+)"}) >= 1) - { - return; - } - - QString firstcall = message.call(); - if(firstcall.length()>=4 and firstcall.mid(0,3)=="CQ ") firstcall="CQ"; - if(!m_bFastMode and (!m_config.enable_VHF_features() or m_mode=="FT8" or m_mode=="FT4" or m_mode=="FST4")) { - // Don't change Tx freq if in a fast mode, or VHF features enabled; also not if a - // station is calling me, unless CTRL or SHIFT is held down. - if ((Radio::is_callsign (firstcall) - && firstcall != m_config.my_callsign () && firstcall != m_baseCall - && firstcall != "DE") - || "CQ" == firstcall || "QRZ" == firstcall || ctrl || shift) { - if (((SpecOp::HOUND != m_specOp) || m_mode != "FT8") - && (!ui->cbHoldTxFreq->isChecked () || shift || ctrl)) { - ui->TxFreqSpinBox->setValue(frequency); - } - if(m_mode != "JT4" && m_mode != "JT65" && !m_mode.startsWith ("JT9") && - m_mode != "Q65" && m_mode!="FT8" && m_mode!="FT4" && m_mode!="FST4") { - return; - } - } +void MainWindow::showContestHint(DecodedMessageReaction::ContestHint hint) +{ + if (hint == DecodedMessageReaction::ContestHint::EuVhf) { + MessageBox::information_message(this, tr( + "Should you switch to EU VHF Contest mode?\n\n" + "To do so, check 'Special operating activity' and\n" + "'EU VHF Contest' on the Settings | Advanced tab.")); + } else if (hint == DecodedMessageReaction::ContestHint::FieldDay) { + MessageBox::information_message(this, tr("Should you switch to ARRL Field Day mode?")); + } else { + MessageBox::information_message(this, tr("Should you switch to RTTY contest mode?")); } +} - // prior DX call (possible QSO partner) - auto qso_partner_base_call = Radio::base_callsign (ui->dxCallEntry->text ()); - auto base_call = Radio::base_callsign (hiscall); - -// Determine appropriate response to received message - auto dtext = " " + message.clean_string () + " "; - dtext=dtext.remove("<").remove(">"); - if(dtext.contains (" " + m_baseCall + " ") - || dtext.contains ("<" + m_baseCall + "> ") -//###??? || dtext.contains ("<" + m_baseCall + " " + hiscall + "> ") - || dtext.contains ("/" + m_baseCall + " ") - || dtext.contains (" " + m_baseCall + "/") - || (firstcall == "DE")) { - - QString w2; - int nw=w.size(); - if(nw>=3) w2=w.at(2); - int nrpt=w2.toInt(); - QString w34; - if(nw>=4) { -// w34=w.at(nw-2); - nrpt=w.at(nw-2).toInt(); - w34=w.at(nw-1); - } - bool bRTTY = (nrpt>=529 and nrpt<=599); - bool bEU_VHF_w2=(nrpt>=520001 and nrpt<=594000); - if(bEU_VHF_w2 and SpecOp::EU_VHF!=m_specOp) { - auto const& msg = tr("Should you switch to EU VHF Contest mode?\n\n" - "To do so, check 'Special operating activity' and\n" - "'EU VHF Contest' on the Settings | Advanced tab."); - MessageBox::information_message (this, msg); - } - - QStringList t=message.clean_string ().split(' ', SkipEmptyParts); - int n=t.size(); - QString t0=t.at(n-2); - QString t1=t0.right(1); - bool bFieldDay_msg = (t1>="A" and t1<="F" and t0.size()<=3 and n>=9); - int m=t0.remove(t1).toInt(); - if(m < 1) bFieldDay_msg=false; - if(bFieldDay_msg) { - m_xRcvd=t.at(n-2) + " " + t.at(n-1); - t0=t.at(n-3); - } - if(bFieldDay_msg and SpecOp::FIELD_DAY!=m_specOp) { - // ### Should be in ARRL Field Day mode ??? ### - MessageBox::information_message (this, tr ("Should you switch to ARRL Field Day mode?")); - } - - if(bRTTY and SpecOp::RTTY != m_specOp) { - // ### Should be in RTTY contest mode ??? ### - MessageBox::information_message (this, tr ("Should you switch to RTTY contest mode?")); - } - - // This is necessary to prevent crashes caused by double-clicking messages with <...> in certain QSO situations. - if((SpecOp::EU_VHF==m_specOp or SpecOp::RTTY==m_specOp or SpecOp::FIELD_DAY==m_specOp) - and message.string().contains("<...>")) return; - - if(SpecOp::EU_VHF==m_specOp and message_words.at(2).contains(m_baseCall) and - (!message_words.at(3).contains(qso_partner_base_call)) and (!m_bDoubleClicked)) { - return; - } - - bool bContestOK=(m_mode=="FT4" or m_mode=="FT8" or m_mode=="Q65" or m_mode=="MSK144"); - if(message_words.size () > 4 // enough fields for a normal message - && (message_words.at(2).contains(m_baseCall) || "DE" == message_words.at(2)) - && (message_words.at(3).contains(qso_partner_base_call) or m_bDoubleClicked - or bEU_VHF_w2 or (m_QSOProgress==CALLING))) { - if(message_words.at(4).contains(grid_regexp) and SpecOp::EU_VHF!=m_specOp) { - if((SpecOp::NA_VHF==m_specOp or SpecOp::WW_DIGI==m_specOp or - SpecOp::ARRL_DIGI==m_specOp or SpecOp::Q65_PILEUP==m_specOp) - and bContestOK) { - setTxMsg(3); - m_QSOProgress=ROGER_REPORT; - // FT4 NS (NCCC Sprints): Log QSO after sending "hiscall mycall R mygrid" - if (SpecOp::NA_VHF==m_specOp && m_mode=="FT4" && m_config.NCCC_Sprint()) { - if (m_auto && (m_config.prompt_to_log() || m_config.autoLog())) logQSOTimer.start(0); - QTimer::singleShot (int(850.0*m_TRperiod), [=] { - auto_tx_mode(false); - if (m_auto) ui->autoButton->click(); - }); - if (m_config.prompt_to_log() || m_config.autoLog()) { // prevent dupe logbook entries - no_logging = true; - QTimer::singleShot (20000, [=] {no_logging = false;}); - } - } - } else { - if(m_mode=="JT65" and message_words.size()>5 and message_words.at(5)=="OOO") { - setTxMsg(3); - m_QSOProgress=ROGER_REPORT; - } else { - setTxMsg(2); - m_QSOProgress=REPORT; - } - } - } else if(w34.contains(grid_regexp) and SpecOp::EU_VHF==m_specOp) { +void MainWindow::refreshQsoPane(DecodedText const& message) +{ + QString const previous = m_QSOText.trimmed(); + QString const current = message.clean_string().trimmed(); + if (previous == current || message.isTX()) return; - if(nrpt==0) { - setTxMsg(2); - m_QSOProgress=REPORT; - } else { - if(w2=="R") { - setTxMsg(4); - m_QSOProgress=ROGERS; - } else { - setTxMsg(3); - m_QSOProgress=ROGER_REPORT; - } - } - } else if(SpecOp::RTTY == m_specOp and bRTTY) { - if(w2=="R") { - setTxMsg(4); - m_QSOProgress=ROGERS; - } else { - setTxMsg(3); - m_QSOProgress=ROGER_REPORT; - } - m_xRcvd=t[n-2] + " " + t[n-1]; - } else if(SpecOp::FIELD_DAY==m_specOp and bFieldDay_msg) { - if(t0=="R") { - setTxMsg(4); - m_QSOProgress=ROGERS; - } else { - setTxMsg(3); - m_QSOProgress=ROGER_REPORT; - } - } else { // no grid on end of msg - auto const& word_3 = message_words.at (4); - auto word_3_as_number = word_3.toInt (); - if (("RRR" == word_3 - || (word_3_as_number == 73 && ROGERS == m_QSOProgress) - || "RR73" == word_3 - || ("R" == word_3 && m_QSOProgress != REPORT))) { - if(m_mode=="FT4" and "RR73" == word_3) m_dateTimeRcvdRR73=QDateTime::currentDateTimeUtc(); - m_bTUmsg=false; - m_nextCall=""; //### Temporary: disable use of "TU;" message - if(SpecOp::RTTY == m_specOp and m_nextCall!="") { - // We're in RTTY contest and have "nextCall" queued up: send a "TU; ..." message - if (m_config.prompt_to_log() || m_config.autoLog()) { - logQSOTimer.start(0); - } - else { - cease_auto_Tx_after_QSO (); - } - ui->tx3->setText(ui->tx3->text().remove("TU; ")); - useNextCall(); - QString t="TU; " + ui->tx3->text(); - ui->tx3->setText(t); - m_bTUmsg=true; - } else { - if (false) // Always Send 73 after receiving RRR or RR73, even in contest mode. - { - if (m_config.prompt_to_log() || m_config.autoLog()) { - if (!(m_mode=="FT4" && SpecOp::NA_VHF==m_specOp && m_config.NCCC_Sprint())) logQSOTimer.start(0); - } - else { - cease_auto_Tx_after_QSO (); - } - m_ntx=6; - ui->txrb6->setChecked(true); - } - else if (word_3.contains (QRegularExpression {"^R(?!R73|RR)"}) - && m_QSOProgress != ROGER_REPORT) - { - m_ntx=4; - ui->txrb4->setChecked(true); - } - else if ((m_QSOProgress > CALLING && m_QSOProgress < ROGERS) - || word_3.contains (QRegularExpression {"^RR(?:R|73)$"})) - { - m_ntx=5; - ui->txrb5->setChecked(true); - } - else if (ROGERS == m_QSOProgress) - { - if (m_config.prompt_to_log() || m_config.autoLog()) { - if (!(m_mode=="FT4" && SpecOp::NA_VHF==m_specOp && m_config.NCCC_Sprint())) logQSOTimer.start(0); - } - else { - cease_auto_Tx_after_QSO (); - } - if ((m_mode=="MSK144" or (m_mode=="Q65" && m_config.repeat_Tx())) && !m_send_RR73) { // ensure that 73 is sent when using RRR - ui->txrb5->click(); - QTimer::singleShot (int(1000*m_TRperiod), [=] {m_auto=false;}); - } else { - m_ntx=6; - ui->txrb6->setChecked(true); - } - } - else - { - // just work them (again) - if (ui->tx1->isEnabled ()) { - m_ntx = 1; - m_QSOProgress = REPLYING; - ui->txrb1->setChecked (true); - } else { - m_ntx=2; - m_QSOProgress = REPORT; - ui->txrb2->setChecked (true); - } - } - } - if (m_QSOProgress >= ROGER_REPORT) - { - m_QSOProgress = SIGNOFF; - } - } else if((m_QSOProgress >= REPORT - || (m_QSOProgress >= REPLYING && - (m_mode=="MSK144" or m_mode=="FT8" or m_mode=="FT4" || "Q65" == m_mode))) - && word_3.startsWith ('R')) { - m_ntx=4; - m_QSOProgress = ROGERS; - if(SpecOp::RTTY == m_specOp) { - int n=t.size(); - int nRpt=t[n-2].toInt(); - if(nRpt>=529 and nRpt<=599) m_xRcvd=t[n-2] + " " + t[n-1]; - } - ui->txrb4->setChecked(true); - } else if (m_QSOProgress >= CALLING) - { - if ((word_3_as_number >= -50 && word_3_as_number <= 49) - || (word_3_as_number >= 529 && word_3_as_number <= 599)) - { - if(SpecOp::EU_VHF==m_specOp or - SpecOp::FIELD_DAY==m_specOp or - SpecOp::RTTY==m_specOp) - { - setTxMsg(2); - m_QSOProgress=REPORT; - } - else - { - if (word_3.startsWith ("R-") || word_3.startsWith ("R+")) - { - setTxMsg(4); - m_QSOProgress=ROGERS; - } - else - { - setTxMsg (3); - m_QSOProgress = ROGER_REPORT; - } - } - } - } - else - { // nothing for us - return; - } - } - } - else if (5 == message_words.size () - && m_baseCall == message_words.at (1)) { - // dual Fox style message, possibly from MSHV - if (m_config.prompt_to_log() || m_config.autoLog()) { - logQSOTimer.start(0); - } - else { - cease_auto_Tx_after_QSO (); - } - m_ntx=6; - ui->txrb6->setChecked(true); - } - else if (m_QSOProgress >= ROGERS - && message_words.size () > 3 && message_words.at (2).contains (m_baseCall) - && message_words.at (3) == "73") { - // 73 back to compound call holder - m_ntx=5; - ui->txrb5->setChecked(true); - m_QSOProgress = SIGNOFF; - } - else if (!(m_bAutoReply && (m_QSOProgress > CALLING))) { - if ((message_words.size () > 5 && message_words.at (2).contains (m_baseCall) - && message_words.at (5) == "OOO")) { - // EME short code report or MSK144/FT8 contest mode reply, send back Tx3 - m_ntx=3; - m_QSOProgress = ROGER_REPORT; - ui->txrb3->setChecked (true); - } else if (!is_73) { // don't respond to sign off messages - m_ntx=2; - m_QSOProgress = REPORT; - ui->txrb2->setChecked(true); - if (m_bDoubleClickAfterCQnnn and m_transmitting) { - on_stopTxButton_clicked(); - TxAgainTimer.start(1500); - } - m_bDoubleClickAfterCQnnn=false; - } - else { - return; // nothing we need to respond to - } - } - else { // nothing for us - return; - } - } - else if (firstcall == "DE" && message_words.size () > 4 && message_words.at (4) == "73") { - if (m_QSOProgress >= ROGERS && base_call == qso_partner_base_call && m_currentMessageType) { - // 73 back to compound call holder - m_ntx=5; - ui->txrb5->setChecked(true); - m_QSOProgress = SIGNOFF; - } else { - // treat like a CQ/QRZ - if (ui->tx1->isEnabled ()) { - m_ntx = 1; - m_QSOProgress = REPLYING; - ui->txrb1->setChecked (true); - } else { - m_ntx=2; - m_QSOProgress = REPORT; - ui->txrb2->setChecked (true); - } - } - } - else if (is_73 && !message.isStandardMessage ()) { - m_ntx=5; - ui->txrb5->setChecked(true); - m_QSOProgress = SIGNOFF; - } else if (!(m_auto && m_ntx == 3 && message.string().contains("73 "))) { // don't interrupt Tx3 transmissions - // just work them - if (ui->tx1->isEnabled ()) { - m_ntx = 1; - m_QSOProgress = REPLYING; - ui->txrb1->setChecked (true); + if (m_mode == "MSK144" && m_config.insert_blank() && m_band_changed + && m_currentBandPeriod == m_currentBand && !BlankLineInserted) { + if (ui->actionUse_Dark_Style->isChecked()) { + ui->decodedTextBrowser2->insertText( + "------------------- " + m_currentBandPeriod + " -----------------", "#a2a2a2", "#000000"); } else { - m_ntx=2; - m_QSOProgress = REPORT; - ui->txrb2->setChecked (true); - } - } - // if we get here then we are reacting to the message - if (m_bAutoReply) m_bCallingCQ = CALLING == m_QSOProgress; - m_maxPoints=-1; - if (ui->RxFreqSpinBox->isEnabled () and m_mode != "MSK144" and !shift) { - ui->RxFreqSpinBox->setValue (frequency); //Set Rx freq - } - - QString s1 = m_QSOText.trimmed (); - QString s2 = message.clean_string ().trimmed(); - if (s1!=s2 and !message.isTX()) { - // insert blank line in decodedTextBrowser2 when band was changed for MSK144 - if (m_mode=="MSK144" && m_config.insert_blank () && m_band_changed && (m_currentBandPeriod == m_currentBand) && !BlankLineInserted) { - if (ui->actionUse_Dark_Style->isChecked()) { - ui->decodedTextBrowser2->insertText(("------------------- " + m_currentBandPeriod + " -----------------"), "#a2a2a2", "#000000"); - } else { - ui->decodedTextBrowser2->insertLineSpacer ("------------------- " + m_currentBandPeriod + " -----------------"); - } - BlankLineInserted = true; - m_band_changed = false; + ui->decodedTextBrowser2->insertLineSpacer( + "------------------- " + m_currentBandPeriod + " -----------------"); } - if (!s2.contains(m_baseCall) or m_mode=="MSK144") { // Taken care of elsewhere if for_us and slow mode - ui->decodedTextBrowser2->displayDecodedText (message, m_config.my_callsign (), m_mode, m_config.DXCC (), - m_logBook, m_currentBand, m_config.ppfx (), false, false, 0.0, false, -99, "", m_muted); - } - m_QSOText = s2; + BlankLineInserted = true; + m_band_changed = false; } - - if (Radio::is_callsign (hiscall) - && (base_call != qso_partner_base_call || base_call != hiscall)) { - if (qso_partner_base_call != base_call) { - // clear the DX grid if the base call of his call is different - // from the current DX call - ui->dxGridEntry->clear (); - } - // his base call different or his call more qualified - // i.e. compound version of same base call - if (!((s2.contains(" " + m_config.my_callsign() + " ") && s2.mid(22).contains(" 73")) && (ui->respondComboBox->currentText()=="CQ: Max dB" - or ui->respondComboBox->currentText()=="CQ: Max dB"))) ui->dxCallEntry->setText (hiscall); + if (!current.contains(m_baseCall) || m_mode == "MSK144") { + ui->decodedTextBrowser2->displayDecodedText( + message, m_config.my_callsign(), m_mode, m_config.DXCC(), m_logBook, m_currentBand, + m_config.ppfx(), false, false, 0.0, false, -99, "", m_muted); } - if (hisgrid.contains (grid_regexp)) { - if(ui->dxGridEntry->text().mid(0,4) != hisgrid) ui->dxGridEntry->setText(hisgrid); - } - lookup(); - m_hisGrid = ui->dxGridEntry->text(); - - if (m_bDoubleClicked) - { - // extract our report if present - message.report (m_baseCall, Radio::base_callsign(ui->dxCallEntry->text()), m_rptRcvd); - } - - if (!m_bSentReport || base_call != qso_partner_base_call || m_mode == "FT8" || m_mode == "FT4" - || m_mode == "FST4") // Change report within a QSO - { - auto n = message.report ().toInt (); - if(m_mode=="MSK144" and m_bShMsgs) { - if(n<=-2) n=-3; - if(n>=-1 and n<=1) n=0; - if(n>=2 and n<=4) n=3; - if(n>=5 and n<=7) n=6; - if(n>=8 and n<=11) n=10; - if(n>=12 and n<=14) n=13; - if(n>=15) n=16; - } - ui->rptSpinBox->setValue (n); - } -// Don't genStdMsgs if we're already sending 73, or a "TU; " msg is queued. - m_bTUmsg=false; //### Temporary: disable use of "TU;" messages - if (!m_nTx73 and !m_bTUmsg) { - genStdMsgs (QString::number (ui->rptSpinBox->value ())); - } - if(m_transmitting) m_restart=true; - if (auto_seq && !m_bDoubleClicked && m_mode!="FT4") { - return; - } - if(m_config.quick_call() && m_bDoubleClicked) auto_tx_mode(true); - m_bDoubleClicked=false; + m_QSOText = current; +} +void MainWindow::processMessage(DecodedText const& message, Qt::KeyboardModifiers modifiers, + DecodedMessageReaction::SelectionOrigin selection_origin) +{ + auto const snapshot = qsoReactionSnapshot(modifiers, selection_origin); + applyQsoReactionPlan(DecodedMessageReaction::planProcessMessage(message, snapshot), message); } +void MainWindow::processSyntheticMessage(DecodedText const& message) +{ + auto snapshot = qsoReactionSnapshot(); + snapshot.selectionOrigin = DecodedMessageReaction::SelectionOrigin::Synthetic; + applyQsoReactionPlan(DecodedMessageReaction::planProcessMessage(message, snapshot), message); +} void MainWindow::setTxMsg(int n) { m_ntx=n; @@ -9451,13 +9166,13 @@ void MainWindow::genCQMsg () if(stdCall (my_callsign) || is_type_two) { msgtype (QString {"CQ %1 %2 %3"} - .arg (m_freqNominal / 1000 - m_freqNominal / 1000000 * 1000, 3, 10, QChar {'0'}) + .arg (m_operatingFrequency.rx () / 1000 - m_operatingFrequency.rx () / 1000000 * 1000, 3, 10, QChar {'0'}) .arg (my_callsign) .arg (grid.left (4)), ui->tx6); } else { msgtype (QString {"CQ %1 %2"} - .arg (m_freqNominal / 1000 - m_freqNominal / 1000000 * 1000, 3, 10, QChar {'0'}) + .arg (m_operatingFrequency.rx () / 1000 - m_operatingFrequency.rx () / 1000000 * 1000, 3, 10, QChar {'0'}) .arg (my_callsign), ui->tx6); } @@ -9534,6 +9249,30 @@ bool MainWindow::is77BitMode () const || "FST4" == m_mode || "Q65" == m_mode; } +bool MainWindow::rr73_tx4_allowed () const +{ + return Rr73Policy::tx4AllowsRr73 (m_mode, m_bShMsgs); +} + +bool MainWindow::send_rr73_for_tx4 () const +{ + return rr73_tx4_allowed () && ("FT4" == m_mode || m_send_RR73); +} + +void MainWindow::set_rr73_tx4 (bool enabled) +{ + if (enabled && !rr73_tx4_allowed ()) { + auto mode = m_bShMsgs ? tr ("%1 shorthand-message mode").arg (m_mode) : m_mode; + MessageBox::information_message (this, tr ( + "RR73 is not available in %1. Tx4 uses RRR in this mode.").arg (mode)); + return; + } + + m_send_RR73 = enabled; + if ("FT4" == m_mode) m_send_RR73 = true; + genStdMsgs (m_rpt); +} + void MainWindow::ScrollBarPosition(int n) { m_position=n; } @@ -9558,7 +9297,6 @@ void MainWindow::genStdMsgs(QString rpt, bool unconditional) auto is_type_one = !is77BitMode () && is_compound && shortList (my_callsign); auto const& my_grid = m_config.my_grid ().left (4); auto const& hisBase = Radio::base_callsign (hisCall); - save_dxbase_(const_cast <char *> ((hisBase + " ").left(6).toLatin1().constData()), (FCL)6); auto eme_short_codes = m_config.enable_VHF_features () && ui->cbShMsgs->isChecked () && m_mode == "JT65"; @@ -9619,7 +9357,7 @@ void MainWindow::genStdMsgs(QString rpt, bool unconditional) t1 = t1.asprintf("%4.4d",ui->sbSerialNumber->value()); sent=rst + t1; } - if(t1.contains(QRegularExpression {"\\d\\d\\d\\d"})) { + if(t1.contains(four_digit_regexp)) { t1 = m_config.RTTY_Exchange(); } } @@ -9670,13 +9408,13 @@ void MainWindow::genStdMsgs(QString rpt, bool unconditional) t=t0 + "R" + rpt; msgtype(t, ui->tx3); } - m_send_RR73=false; } - t=t0 + (m_send_RR73 ? "RR73" : "RRR"); + auto send_rr73 = send_rr73_for_tx4 (); + t=t0 + (send_rr73 ? "RR73" : "RRR"); if((m_mode=="MSK144" and !m_bShMsgs) or m_mode=="FT8" or m_mode=="FT4" || m_mode == "FST4" || m_mode == "Q65") { - if(!bHisCall and bMyCall) t=hisCall + " <" + my_callsign + "> " + (m_send_RR73 ? "RR73" : "RRR"); - if(bHisCall and !bMyCall) t="<" + hisCall + "> " + my_callsign + " " + (m_send_RR73 ? "RR73" : "RRR"); + if(!bHisCall and bMyCall) t=hisCall + " <" + my_callsign + "> " + (send_rr73 ? "RR73" : "RRR"); + if(bHisCall and !bMyCall) t="<" + hisCall + "> " + my_callsign + " " + (send_rr73 ? "RR73" : "RRR"); } if ((m_mode=="JT4" || m_mode=="Q65") && m_bShMsgs) t="@1500 (RRR)"; msgtype(t, ui->tx4); @@ -9791,12 +9529,7 @@ void MainWindow::clearDX () if (m_config.clear_DXgrid () or (SpecOp::HOUND == m_specOp && m_config.superFox())) ui->dxGridEntry->clear (); if (!keepTx5) ui->tx5->setCurrentText(""); // clear tx5 if (ui->respondComboBox->isVisible()) { - Dpoints=0; // reset points - maxDPoints=0; // reset points - dBpoints=-28; // reset points - dBpoints2=99; // reset points - maxdBPoints=-28; // reset points - mindBPoints=99; // reset points + m_autoRespondScores.reset(); } m_lastCallsign.clear (); m_rptSent.clear (); @@ -9830,7 +9563,7 @@ void MainWindow::lookup() for(int i=0; i<999999; i++) { n=f.readLine(c,sizeof(c)); if(n <= 0) { - if(!hisgrid0.contains(grid_regexp)) { + if(!hisgrid0.contains(MainWindow::grid_regexp)) { ui->dxGridEntry->clear(); } break; @@ -9855,116 +9588,8 @@ void MainWindow::lookup() } } -void MainWindow::on_lookupButton_clicked() //Lookup button -{ - qint64 ms=QDateTime::currentMSecsSinceEpoch(); - lookup(); - if((ms-m_msErase)<500) { - QString hisCall=ui->dxCallEntry->text(); - if (hisCall !="") QDesktopServices::openUrl (QUrl {"https://www.qrz.com/db/" + hisCall}); - } - m_msErase=ms; -} - -void MainWindow::on_addButton_clicked() //Add button -{ - if(!ui->dxGridEntry->text ().size ()) { - MessageBox::warning_message (this, tr ("Add to CALL3.TXT") - , tr ("Please enter a valid grid locator")); - return; - } - m_call3Modified=false; - QString hisCall=ui->dxCallEntry->text(); - QString hisgrid=ui->dxGridEntry->text(); - QString newEntry=hisCall + "," + hisgrid; - - // int ret = MessageBox::query_message(this, tr ("Add to CALL3.TXT"), - // tr ("Is %1 known to be active on EME?").arg (newEntry)); - // if(ret==MessageBox::Yes) { - // newEntry += ",EME,,"; - // } else { - newEntry += ",,,"; - // } - - QFile f1 {m_config.writeable_data_dir ().absoluteFilePath ("CALL3.TXT")}; - if(!f1.open(QIODevice::ReadWrite | QIODevice::Text)) { - MessageBox::warning_message (this, tr ("Add to CALL3.TXT") - , tr ("Cannot open \"%1\" for read/write: %2") - .arg (f1.fileName ()).arg (f1.errorString ())); - return; - } - if(f1.size()==0) { - QTextStream out(&f1); - out << "ZZZZZZ" -#if QT_VERSION >= QT_VERSION_CHECK (5, 15, 0) - << Qt::endl -#else - << endl -#endif - ; - f1.seek (0); - } - QFile f2 {m_config.writeable_data_dir ().absoluteFilePath ("CALL3.TMP")}; - if(!f2.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text)) { - MessageBox::warning_message (this, tr ("Add to CALL3.TXT") - , tr ("Cannot open \"%1\" for writing: %2") - .arg (f2.fileName ()).arg (f2.errorString ())); - return; - } - { - QTextStream in(&f1); //Read from CALL3.TXT - QTextStream out(&f2); //Copy into CALL3.TMP - QString hc=hisCall; - QString hc1=""; - QString hc2="000000"; - QString s; - do { - s=in.readLine(); - hc1=hc2; - if(s.mid(0,2)=="//") { - out << s + QChar::LineFeed; //Copy all comment lines - } else { - int i1=s.indexOf(","); - hc2=s.mid(0,i1); - if(hc>hc1 && hc<hc2) { - out << newEntry + QChar::LineFeed; - out << s + QChar::LineFeed; - m_call3Modified=true; - } else if(hc==hc2) { - QString t {tr ("%1\nis already in CALL3.TXT" - ", do you wish to replace it?").arg (s)}; - int ret = MessageBox::query_message (this, tr ("Add to CALL3.TXT"), t); - if(ret==MessageBox::Yes) { - out << newEntry + QChar::LineFeed; - m_call3Modified=true; - } - } else { - if(s!="") out << s + QChar::LineFeed; - } - } - } while(!s.isNull()); - if(hc>hc1 && !m_call3Modified) out << newEntry + QChar::LineFeed; - } - if(m_call3Modified) { - auto const& old_path = m_config.writeable_data_dir ().absoluteFilePath ("CALL3.OLD"); - QFile f0 {old_path}; - if (f0.exists ()) f0.remove (); - f1.copy (old_path); // copying as we want to - // preserve symlinks - f1.open (QFile::WriteOnly | QFile::Text); // truncates - f2.seek (0); - QByteArray tmp = f2.readAll(); - if (tmp != (const char*)NULL) f1.write (tmp); // copy contents - else qDebug() << "tmp==NULL at f1.write"; - f2.remove (); - } -} -void MainWindow::on_ignoreButton_clicked() //Ignore button -{ - addCallsignToignoreList(); -} void MainWindow::msgtype(QString t, QLineEdit* tx) //msgtype() { @@ -10014,6 +9639,7 @@ void MainWindow::msgtype(QString t, QLineEdit* tx) //msgtype() void MainWindow::on_tx1_editingFinished() //tx1 edited { + if (m_ntx==1) clear_generated_message_error (); if (SpecOp::HOUND==m_specOp && m_config.superFox() && !m_bDoubleClicked) { clearDX(); return; @@ -10026,10 +9652,12 @@ void MainWindow::on_tx2_editingFinished() //tx2 edited { QString t=ui->tx2->text(); msgtype(t, ui->tx2); + if (m_ntx==2) clear_generated_message_error (); } void MainWindow::on_tx3_editingFinished() //tx3 edited { + if (m_ntx==3) clear_generated_message_error (); if (SpecOp::HOUND==m_specOp && m_config.superFox() && !m_bDoubleClicked) { clearDX(); return; @@ -10042,11 +9670,13 @@ void MainWindow::on_tx4_editingFinished() //tx4 edited { QString t=ui->tx4->text(); msgtype(t, ui->tx4); + if (m_ntx==4) clear_generated_message_error (); } void MainWindow::on_tx5_currentTextChanged (QString const& text) //tx5 edited { msgtype(text, ui->tx5->lineEdit ()); + if (m_ntx==5) clear_generated_message_error (); } void MainWindow::on_tx6_editingFinished() //tx6 edited @@ -10061,77 +9691,66 @@ void MainWindow::on_tx6_editingFinished() //tx6 edited if(t1.size()<=3 and t1.contains(NN3)) m_CQtype="CQ " + t1; } msgtype(t, ui->tx6); + if (m_ntx==6) clear_generated_message_error (); } -void MainWindow::on_RoundRobin_currentTextChanged(QString text) +void MainWindow::on_RoundRobin_currentTextChanged(QString) { - ui->sbTxPercent->setEnabled (text == tr ("Random")); + ui->sbTxPercent->setEnabled ( + configuredRoundRobinPolicy ().kind == BeaconTx::RoundRobinPolicy::Kind::Random); + m_beaconTxController.setRoundRobinPolicy (beaconRoundRobinPolicy ()); } -void MainWindow::on_DX_Call_Button_clicked (bool checked) -{ - if((m_mode=="FT8" or m_mode=="FT4" or m_mode=="Q65" or m_mode=="FST4" or m_mode=="MSK144") && - (m_specOp==SpecOp::NONE or m_specOp==SpecOp::HOUND) && ui->cbAutoSeq->isChecked() && checked - && (m_hisCall!="" or (m_mode=="FT8" && m_specOp==SpecOp::HOUND))) { - wait_and_call = true; // toggle Wait & Call on when allowed - } else { - wait_and_call = false; // toggle Wait & Call off in any other case - ui->DX_Call_Button->setChecked (false); - if (m_specOp==SpecOp::HOUND && m_config.superFox() && !m_auto) clearDX(); - } - check_button_color(); -} void MainWindow::wheelEvent(QWheelEvent *event) // mouse wheel events { - if(ui->labDialFreq->hasFocus() && !m_transmitting) { // kHz + or - - Frequency dial_frequency {m_rigState.ptt () && m_rigState.split () ? - m_rigState.tx_frequency () : m_rigState.frequency ()}; + if(ui->labDialFreq->hasFocus()) { // kHz + or - + Frequency dial_frequency {m_rigState.ptt () ? + (m_rigState.split () ? m_operatingFrequency.correctedTx (m_astroCorrection.tx) + : m_operatingFrequency.tx ()) : + m_operatingFrequency.correctedRx (m_astroCorrection.rx)}; if (event->angleDelta().x() > 2 or event->angleDelta().y() > 2) { dial_frequency = dial_frequency + 1000; - ui->labDialFreq->setText (Radio::pretty_frequency_MHz_string (dial_frequency)); } else if (event->angleDelta().x() < -2 or event->angleDelta().y() < -2) { dial_frequency = dial_frequency - 1000; + } + Frequency requested_frequency = dial_frequency; + if (m_astroWidget && m_astroWidget->doppler_tracking() + && m_astroWidget->DopplerMethod()!=0) { + requested_frequency -= m_astroCorrection.rx; + } + if (requestNominalFrequencyChange (requested_frequency, FrequencyRequestOrigin::User)) { ui->labDialFreq->setText (Radio::pretty_frequency_MHz_string (dial_frequency)); + setXIT (ui->TxFreqSpinBox->value ()); } - if (m_astroWidget && m_astroWidget->doppler_tracking() && m_astroWidget->DopplerMethod()!=0) { - setRig(dial_frequency - m_astroCorrection.rx); - } else { - setRig(dial_frequency); - } - setXIT (ui->TxFreqSpinBox->value ()); - ui->labDialFreq->clearFocus(); + ui->labDialFreq->clearFocus(); } } void MainWindow::mousePressEvent(QMouseEvent *event) // mouse press events { - if(ui->labDialFreq->hasFocus() && !m_transmitting) { // kHz + or - + if(ui->labDialFreq->hasFocus()) { // kHz + or - if (event->button() & Qt::RightButton) { - m_bandEdited = true; - band_changed(m_freqNominal+1000); + requestBandChange (m_operatingFrequency.rx () + 1000, FrequencyRequestOrigin::User); } else if (event->button() & Qt::LeftButton) { - m_bandEdited = true; - band_changed(m_freqNominal-1000); + requestBandChange (m_operatingFrequency.rx () - 1000, FrequencyRequestOrigin::User); } ui->labDialFreq->clearFocus(); } if(ui->tuneButton->hasFocus() && (event->button() & Qt::RightButton)) { // Tune button - m_config.transceiver_tune (false); // reset any prior rig tuning - blocked=true; - m_config.transceiver_tune (true); // toggle rig tuning - blocked=false; - if(ui->tuneButton->text()=="Tuning") { // reset Tune button by another right-click + if (rigTuneTimer.isActive ()) { + rigTuneTimer.stop (); ui->tuneButton->setChecked(false); ui->tuneButton->setText("Tune"); m_config.transceiver_tune (false); // reset rig tuning } else { + m_config.transceiver_tune (false); // reset any prior rig tuning + blocked=true; + m_config.transceiver_tune (true); + blocked=false; ui->tuneButton->setChecked(true); ui->tuneButton->setText("Tuning"); - QTimer::singleShot (6000, [=] { // reset Tune button after 6 seconds - ui->tuneButton->setChecked(false); - ui->tuneButton->setText("Tune"); - }); + rigTuneTimer.start (6000); } ui->tuneButton->clearFocus(); } @@ -10140,12 +9759,7 @@ void MainWindow::mousePressEvent(QMouseEvent *event) // mouse press events ui->dxGridEntry->clear (); // clear dxGridEntry if (!keepTx5) ui->tx5->setCurrentText(""); // clear tx5 if (ui->respondComboBox->isVisible()) { - Dpoints=0; // reset points - maxDPoints=0; // reset points - dBpoints=-28; // reset points - dBpoints2=99; // reset points - maxdBPoints=-28; // reset points - mindBPoints=99; // reset points + m_autoRespondScores.reset(); } ui->DX_Call_Button->clearFocus(); } @@ -10153,16 +9767,11 @@ void MainWindow::mousePressEvent(QMouseEvent *event) // mouse press events ui->decodedTextBrowser2->erase (); ui->EraseButton->clearFocus(); } - if(ui->txFirstCheckBox->isVisible() && ui->txFirstCheckBox->hasFocus() && (event->button() & Qt::RightButton)) { - ui->txFirstCheckBox->setEnabled(false); // freeze txFirstCheckBox - ui->txFirstCheckBox->clearFocus(); - } - if(ui->msk144Button->hasFocus() && (event->button() & Qt::RightButton)) { - ui->txFirstCheckBox->setEnabled(true); // unfreeze txFirstCheckBox - ui->ft8Button->clearFocus(); - ui->msk144Button->clearFocus(); - } if(ui->q65Button->hasFocus() && (event->button() & Qt::RightButton)) { // switch to Q65_Pileup mode + if (m_specOp != SpecOp::Q65_PILEUP) { + m_q65PileupCopiedLastRxCall.clear(); + m_q65PileupCopiedCallers.clear(); + } m_config.setSpecial_Q65_Pileup(); m_specOp=m_config.special_op_id(); on_actionQ65_triggered(); @@ -10176,14 +9785,13 @@ void MainWindow::mousePressEvent(QMouseEvent *event) // mouse press events keep_frequency = true; not_erase = true; // prevent erasing the decodedTextBrowser m_config.toggle_SF(); - QTimer::singleShot (250, [=] { + QTimer::singleShot (250, this, [=] { keep_frequency = false; not_erase = false; }); on_actionFT8_triggered(); ui->houndButton->clearFocus(); - ui->labDXped->setStyleSheet("QLabel {background-color: red; color: white;}"); - QTimer::singleShot (250, [=] {keep_frequency = false;}); + QTimer::singleShot (250, this, [=] {keep_frequency = false;}); } // Search callsign on qrz.com, qrzcq.com or hamqth.com if(ui->lookupButton->hasFocus() && (event->button() & Qt::RightButton)) { // search callsign on QRZ.com @@ -10202,7 +9810,16 @@ void MainWindow::mousePressEvent(QMouseEvent *event) // mouse press events ui->ignoreButton->clearFocus(); } // Wait & Pounce - if(ui->autoButton->hasFocus() && (event->button() & Qt::RightButton) && ui->respondComboBox->currentText()!="CQ: None") { + if(ui->autoButton->hasFocus() && (event->button() & Qt::RightButton)) { + if (!pounce && autoRespondPolicy () == AutoRespondPolicy::None) { + auto const message = tr ("Wait & Pounce requires a CQ response mode.\n" + "Change CQ: None to another option."); + ui->respondComboBox->setFocus(Qt::OtherFocusReason); + QTimer::singleShot (100, this, [this, message] { + QToolTip::showText(ui->respondComboBox->mapToGlobal(ui->respondComboBox->rect().bottomLeft()), + message, ui->respondComboBox, QRect {}, 5000); + }); + } else { if (!pounce && !m_auto && m_config.Wait_features_enabled() && SpecOp::FOX!=m_specOp) { pounce = true; check_button_color(); @@ -10213,18 +9830,16 @@ void MainWindow::mousePressEvent(QMouseEvent *event) // mouse press events check_button_color(); } ui->autoButton->clearFocus(); + } } if(ui->DecodeButton->hasFocus() && (event->button() & Qt::RightButton)) { // Decode button - if(m_decoderBusy) { - to_jt9(m_ihsym,-1,-1); //Allow jt9 to bail out early, if necessary - decodeDone(); //Clear a hung decoder status - } + clearHungDecoderStatus("Decode button right-click"); ui->DecodeButton->clearFocus(); } if(ui->ft8Button->hasFocus() && (event->button() & Qt::RightButton)) { // Switch contest mode on/off keep_frequency = true; not_erase = true; // prevent erasing the decodedTextBrowser - QTimer::singleShot (350, [=] {not_erase = false;}); + QTimer::singleShot (350, this, [=] {not_erase = false;}); m_specOp=m_config.special_op_id(); if (!m_config.bSpecialOp()) { m_config.setSpecial_On(); @@ -10262,14 +9877,14 @@ void MainWindow::mousePressEvent(QMouseEvent *event) // mouse press events "Fox-and-Hound operation is available only in FT8 mode.\nGo back and change your selection."); } ui->labDXped->setVisible(SpecOp::NONE != m_specOp); - if ((!verified && ui->labDXped->isVisible()) or ui->labDXped->text()!="Super Hound") - ui->labDXped->setStyleSheet("QLabel {background-color: red; color: white;}"); + if (!isSuperHoundOperation ()) m_houndVerified = false; + updateHoundVerificationStyle (); set_mode(m_mode); configActiveStations(); check_button_color(); ui->ft8Button->clearFocus(); statusChanged(); - QTimer::singleShot (250, [=] {keep_frequency = false;}); + QTimer::singleShot (250, this, [=] {keep_frequency = false;}); } // freeze the Tx5 text if(ui->txb5->hasFocus() && (event->button() & Qt::RightButton)) { @@ -10284,66 +9899,39 @@ void MainWindow::mousePressEvent(QMouseEvent *event) // mouse press events } // Toggle FT8 DXp frequencies if(ui->pb80->hasFocus() && (event->button() & Qt::RightButton) && (m_mode=="FT8" || m_mode=="FT4")) { - keep_frequency = true; - setRig(3567000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - setXIT (ui->TxFreqSpinBox->value ()); + requestAlternateBandFrequency (3567000); ui->pb80->clearFocus(); } if(ui->pb40->hasFocus() && (event->button() & Qt::RightButton) && (m_mode=="FT8" || m_mode=="FT4")) { - keep_frequency = true; - setRig(7056000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - setXIT (ui->TxFreqSpinBox->value ()); + requestAlternateBandFrequency (7056000); ui->pb40->clearFocus(); } if(ui->pb30->hasFocus() && (event->button() & Qt::RightButton) && (m_mode=="FT8" || m_mode=="FT4")) { - keep_frequency = true; - setRig(10131000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - setXIT (ui->TxFreqSpinBox->value ()); + requestAlternateBandFrequency (10131000); ui->pb30->clearFocus(); } if(ui->pb20->hasFocus() && (event->button() & Qt::RightButton) && (m_mode=="FT8" || m_mode=="FT4")) { - keep_frequency = true; - setRig(14090000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - setXIT (ui->TxFreqSpinBox->value ()); + requestAlternateBandFrequency (14090000); ui->pb20->clearFocus(); } if(ui->pb17->hasFocus() && (event->button() & Qt::RightButton) && (m_mode=="FT8" || m_mode=="FT4")) { - keep_frequency = true; - setRig(18095000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - setXIT (ui->TxFreqSpinBox->value ()); + requestAlternateBandFrequency (18095000); ui->pb17->clearFocus(); } if(ui->pb15->hasFocus() && (event->button() & Qt::RightButton) && (m_mode=="FT8" || m_mode=="FT4")) { - keep_frequency = true; - setRig(21091000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - setXIT (ui->TxFreqSpinBox->value ()); + requestAlternateBandFrequency (21091000); ui->pb15->clearFocus(); } if(ui->pb12->hasFocus() && (event->button() & Qt::RightButton) && (m_mode=="FT8" || m_mode=="FT4")) { - keep_frequency = true; - setRig(24911000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - setXIT (ui->TxFreqSpinBox->value ()); + requestAlternateBandFrequency (24911000); ui->pb12->clearFocus(); } if(ui->pb10->hasFocus() && (event->button() & Qt::RightButton) && (m_mode=="FT8" || m_mode=="FT4")) { - keep_frequency = true; - setRig(28091000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - setXIT (ui->TxFreqSpinBox->value ()); + requestAlternateBandFrequency (28091000); ui->pb10->clearFocus(); } if(ui->pb6->hasFocus() && (event->button() & Qt::RightButton) && m_mode=="FT8") { - keep_frequency = true; - setRig(50323000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - setXIT (ui->TxFreqSpinBox->value ()); + requestAlternateBandFrequency (50323000); ui->pb6->clearFocus(); } if(ui->pb2->hasFocus() && (event->button() & Qt::RightButton)) { @@ -10352,45 +9940,44 @@ void MainWindow::mousePressEvent(QMouseEvent *event) // mouse press events f = 222174000; } else { f = 70154000; - if (m_mode=="MSK144") { + if (m_mode=="MSK144" + && nominalFrequencyChangeAllowed (FrequencyRequestOrigin::User)) { ui->sbTR->setValue (m_msk144_tr6); programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); + QTimer::singleShot (250, this, [=] {programStart = false;}); } } - auto const& row = m_config.frequencies ()->best_working_frequency (f); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(f); - QTimer::singleShot (250, [=] {keep_frequency = false;}); + if (nominalFrequencyChangeAllowed (FrequencyRequestOrigin::User)) { + auto const row = m_config.frequencies ()->best_working_frequency (f); + if (row >= 0) { + ui->bandComboBox->setCurrentIndex (row); + on_bandComboBox_activated (row); + } else { + requestAlternateBandFrequency (f); + } } - setXIT (ui->TxFreqSpinBox->value ()); ui->pb2->clearFocus(); } if(ui->pb70->hasFocus() && (event->button() & Qt::RightButton)) { - auto const& row = m_config.frequencies ()->best_working_frequency (1296174000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(1296174000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); + if (nominalFrequencyChangeAllowed (FrequencyRequestOrigin::User)) { + auto const row = m_config.frequencies ()->best_working_frequency (1296174000); + if (row >= 0) { + ui->bandComboBox->setCurrentIndex (row); + on_bandComboBox_activated (row); + } else { + requestAlternateBandFrequency (1296174000); + } } - setXIT (ui->TxFreqSpinBox->value ()); ui->pb70->clearFocus(); } if (ui->pbBandHopping->hasFocus() && event->button() & Qt::RightButton) { // Band Hopping button if(ui->pbBandHopping->isChecked()) { - bandHopping(); // Force band hopping to switch to the next selected frequency + bandHopping(true); // Force band hopping to switch to the next selected frequency } else { // Testing the default audio device #ifdef WIN32 QAudioOutput info(QAudioDeviceInfo::defaultOutputDevice()); - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config.voicesPath() + "/"; + QString audioPath = m_config.voice_directory ().absolutePath (); QAudioFormat format; format.setCodec("audio/pcm"); format.setSampleRate (48000); @@ -10404,8 +9991,7 @@ void MainWindow::mousePressEvent(QMouseEvent *event) // mouse press events effect->open(QIODevice::ReadOnly); audio->start(effect); #else - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config.voicesPath() + "/"; - QSound::play(audioPath + "Testing_long.wav"); // for Linux and macOS + QSound::play (m_config.voice_directory ().absoluteFilePath ("Testing_long.wav")); // for Linux and macOS #endif } ui->pbBandHopping->clearFocus(); @@ -10414,6 +10000,7 @@ void MainWindow::mousePressEvent(QMouseEvent *event) // mouse press events void MainWindow::on_dxCallEntry_textChanged (QString const& call) { + m_q65PileupCopiedLastRxCall.clear(); if (SpecOp::HOUND==m_specOp && m_config.superFox() && !(m_bDoubleClicked or (m_hisCall0 != "" && (call.left(6).contains(m_hisCall0) or call.right(6).contains(m_hisCall0)))) && !ui->DX_Call_Button->isChecked()) { // allow Wait & Call @@ -10433,7 +10020,6 @@ void MainWindow::on_dxCallEntry_textChanged (QString const& call) void MainWindow::on_dxCallEntry_editingFinished() { auto const& dxBase = Radio::base_callsign (m_hisCall); - save_dxbase_(const_cast <char *> ((dxBase + " ").left (6).toLatin1().constData()), (FCL)6); if(m_QSYMessageCreatorWidget) m_QSYMessageCreatorWidget->getDxBase(QString(dxBase)); } @@ -10476,21 +10062,6 @@ void MainWindow::on_dxGridEntry_textChanged (QString const& grid) } } -void MainWindow::on_genStdMsgsPushButton_clicked() //genStdMsgs button -{ - ui->pbBandHopping->setChecked(false); // disable band hopping - genStdMsgs(m_rpt); - if (!m_bDoubleClicked && m_hisCall!="") { - if (ui->tx1->isEnabled ()) { - QTimer::singleShot (0, ui->txrb1, SLOT (click ())); // Go to Tx1 - } else { - QTimer::singleShot (0, ui->txrb2, SLOT (click ())); // Go to Tx2 if Tx1 is disabled - } - m_bMyCallStd=stdCall(m_config.my_callsign()); //ft8md - m_bHisCallStd=stdCall(m_hisCall); //ft8md - - } -} void MainWindow::cease_auto_Tx_after_QSO () { @@ -10504,94 +10075,6 @@ void MainWindow::cease_auto_Tx_after_QSO () } } -void MainWindow::on_logQSOButton_clicked() //Log QSO button -{ - if (!((m_config.repeat_Tx() or !m_send_RR73) && (m_mode=="MSK144" or m_mode=="Q65"))) { - if (SpecOp::NA_VHF==m_specOp && m_mode=="FT4" && m_config.NCCC_Sprint()) { - QTimer::singleShot (int(850.0*m_TRperiod), [=] {cease_auto_Tx_after_QSO ();}); - } else { - cease_auto_Tx_after_QSO (); - } - } - - if (!m_hisCall.size ()) { - MessageBox::warning_message (this, tr ("Warning: DX Call field is empty.")); - if ((SpecOp::NA_VHF == m_specOp or SpecOp::WW_DIGI == m_specOp) && m_config.autoLog()) return; // prevent program crash - } - // m_dateTimeQSOOn should really already be set but we'll ensure it gets set to something just in case - if (!m_dateTimeQSOOn.isValid ()) { - auto now = QDateTime::currentDateTimeUtc(); - m_dateTimeQSOOn = now.addSecs (-(m_ntx - 2) * int(m_TRperiod) - - int(fmod(double(now.time().second()),m_TRperiod))); - } - auto dateTimeQSOOff = QDateTime::currentDateTimeUtc(); - if (dateTimeQSOOff < m_dateTimeQSOOn) dateTimeQSOOff = m_dateTimeQSOOn; - QString grid=m_hisGrid; - if(grid=="....") grid=""; - - // Optionally replace empty grids by "ZZ00" - if(m_config.ZZ00() && m_hisGrid=="" && m_specOp!=SpecOp::NONE && m_specOp!=SpecOp::FOX && m_specOp!=SpecOp::HOUND) m_hisGrid = "ZZ00"; - - switch( m_specOp ) - { - case SpecOp::NA_VHF: - m_xSent=m_config.my_grid().left(4); - m_xRcvd=m_hisGrid.left(4); - break; - case SpecOp::EU_VHF: - m_rptSent=m_xSent.split(" ").at(0).left(2); - m_rptRcvd=m_xRcvd.split(" ").at(0).left(2); - if(m_xRcvd.split(" ").size()>=2) m_hisGrid=m_xRcvd.split(" ").at(1); - grid=m_hisGrid; - ui->dxGridEntry->setText(grid); - break; - case SpecOp::FIELD_DAY: - m_rptSent=m_xSent.split(" ").at(0); - m_rptRcvd=m_xRcvd.split(" ").at(0); - break; - case SpecOp::RTTY: - m_rptSent=m_xSent.split(" ").at(0); - m_rptRcvd=m_xRcvd.split(" ").at(0); - break; - case SpecOp::WW_DIGI: - m_xSent=m_config.my_grid().left(4); - m_xRcvd=m_hisGrid.left(4); - break; - case SpecOp::ARRL_DIGI: - m_xSent=m_config.my_grid().left(4); - m_xRcvd=m_hisGrid.left(4); - break; - case SpecOp::Q65_PILEUP: - m_xSent=m_config.my_grid().left(4); - m_xRcvd=m_hisGrid; - break; - default: break; - } - - m_logDlg->initLogQSO (m_hisCall, grid, m_mode, m_rptSent, m_rptRcvd, - m_dateTimeQSOOn, dateTimeQSOOff, m_freqNominal + - ui->TxFreqSpinBox->value(), m_noSuffix, m_xSent, m_xRcvd); - m_inQSOwith=""; - if (ui->respondComboBox->isVisible() && ui->respondComboBox->currentText() != "CQ: None") { - Dpoints=0; // reset points - maxDPoints=0; // reset points - dBpoints=-28; // reset points - dBpoints2=99; // reset points - maxdBPoints=-28; // reset points - mindBPoints=99; // reset points - } - QTimer::singleShot (2000, [=] { - pounce = false; - filtered = false; - read_txLog(); - check_button_color(); - }); - QTimer::singleShot (7000, [=] { - read_txLog(); - }); - stopWRTimer.stop(); // Stop any Wait & Reply timeout - stopWCTimer.stop(); // Stop any Wait & Call timeout -} void MainWindow::acceptQSO (QDateTime const& QSO_date_off, QString const& call, QString const& grid , Frequency dial_freq, QString const& mode @@ -10642,7 +10125,7 @@ void MainWindow::acceptQSO (QDateTime const& QSO_date_off, QString const& call, blocked=true; // needed to clear DXgrid only optionally if (m_config.clear_DXcall ()) clearDX (); if (m_config.clear_DXgrid ()) ui->dxGridEntry->clear (); - QTimer::singleShot (50, [=] {blocked = false;}); // needed to clear DXgrid only optionally + QTimer::singleShot (50, this, [=] {blocked = false;}); // needed to clear DXgrid only optionally m_dateTimeQSOOn = QDateTime {}; if(m_specOp!=SpecOp::NONE and m_specOp!=SpecOp::FOX and m_specOp!=SpecOp::HOUND) { ui->sbSerialNumber->setValue(ui->sbSerialNumber->value() + 1); @@ -10694,78 +10177,75 @@ void MainWindow::updateRate() m_ActiveStationsWidget->setBandChanges(nbc); } -qint64 MainWindow::nWidgets(QString t) -{ - Q_ASSERT(t.length()==N_WIDGETS); - qint64 n=0; - for(int i=0; i<N_WIDGETS; i++) { - n=n + n + t.mid(i,1).toInt(); - } - return n; -} - -void MainWindow::displayWidgets(qint64 n) -{ - /* See text file "displayWidgets.txt" for widget numbers */ - qint64 j=qint64(1)<<(N_WIDGETS-1); - bool b; - for(int i=0; i<N_WIDGETS; i++) { - b=(n&j) != 0; - if(i==0) ui->txFirstCheckBox->setVisible(b); - if(i==1) ui->TxFreqSpinBox->setVisible(b); - if(i==2) ui->RxFreqSpinBox->setVisible(b); - if(i==3) ui->sbFtol->setVisible(b); - if(i==4) ui->rptSpinBox->setVisible(b); - if(i==5) ui->sbTR->setVisible(b); - if(i==6) { - ui->sbCQTxFreq->setVisible (b); - ui->cbCQTx->setVisible (b); - auto is_compound = m_config.my_callsign () != m_baseCall; - ui->cbCQTx->setEnabled (b && (!is_compound || shortList (m_config.my_callsign ()))); - } - if(i==7) ui->cbShMsgs->setVisible(b); - if(i==8) ui->cbFast9->setVisible(b); - if(i==9) ui->cbAutoSeq->setVisible(b); - if(i==10) ui->cbTx6->setVisible(b); - // if(i==11) ui->pbTxMode->setVisible(b); - if(i==12) ui->pbR2T->setVisible(b); - if(i==13) ui->pbT2R->setVisible(b); - if(i==14) ui->cbHoldTxFreq->setVisible(b); - if(i==15) ui->sbSubmode->setVisible(b); - if(i==16) ui->syncSpinBox->setVisible(b); - if(i==17) ui->WSPR_controls_widget->setVisible(b); - if(i==18) ui->ClrAvgButton->setVisible(b); - if(i==19) ui->actionQuickDecode->setEnabled(b); - if(i==19) ui->actionMediumDecode->setEnabled(b); - if(i==19) ui->actionDeepestDecode->setEnabled(b); - if(i==20) ui->actionInclude_averaging->setVisible (b); - if(i==21) ui->actionInclude_correlation->setVisible (b); - if(i==22) { - if(!b && m_echoGraph->isVisible()) m_echoGraph->hide(); - } - if(i==23) ui->cbSWL->setVisible(b); - if(i==24) ui->actionEnable_AP_FT8->setVisible (b); - if(i==24) ui->actionHide_AP_info->setVisible (b); - if(i==25) ui->actionEnable_AP_JT65->setVisible (b); - if(i==26) ui->actionEnable_AP_DXcall->setVisible (b); - if(i==27) ui->respondComboBox->setVisible(b); - if(i==29) ui->measure_check_box->setVisible(b); - if(i==30) ui->labDXped->setVisible(b); - if(i==31) ui->cbRxAll->setVisible(b); - if(i==32) ui->cbCQonly->setVisible(b); - if(i==33) ui->sbTR_FST4W->setVisible(b); - if (34 == i) // adjust the stacked widget - { - ui->opt_controls_stack->setCurrentIndex (b ? 1 : 0); - ui->sbF_Low->setVisible(b); - } - if(i==35) ui->sbF_High->setVisible(b); - if(i==36) ui->actionAuto_Clear_Avg->setVisible (b); - if(i==37) ui->sbMaxDrift->setVisible(b); - j=j>>1; - } +void MainWindow::applyModeUiState(ModeUiState state) +{ + auto visible = [state] (ModeUiControl control) { + return std::find(state.begin(), state.end(), control) != state.end(); + }; + auto setLabeledControlVisible = [&visible] (ModeUiControl control, QWidget * widget, QLabel * label) { + auto const show = visible(control); + widget->setVisible(show); + label->setVisible(show); + }; + + ui->txFirstCheckBox->setVisible(visible(ModeUiControl::TxFirst)); + setLabeledControlVisible(ModeUiControl::TxFrequency, ui->TxFreqSpinBox, m_txFrequencyLabel); + setLabeledControlVisible(ModeUiControl::RxFrequency, ui->RxFreqSpinBox, m_rxFrequencyLabel); + setLabeledControlVisible(ModeUiControl::FrequencyTolerance, ui->sbFtol, m_frequencyToleranceLabel); + updateFrequencyToleranceRowAlignment (); + setLabeledControlVisible(ModeUiControl::Report, ui->rptSpinBox, m_reportLabel); + setTrPeriodVisible(visible(ModeUiControl::TrPeriod)); + + auto const showCqTxFrequency = visible(ModeUiControl::CqTxFrequency); + ui->sbCQTxFreq->setVisible(showCqTxFrequency); + ui->cbCQTx->setVisible(showCqTxFrequency); + auto const isCompoundCall = m_config.my_callsign() != m_baseCall; + ui->cbCQTx->setEnabled(showCqTxFrequency && (!isCompoundCall || shortList(m_config.my_callsign()))); + + ui->cbShMsgs->setVisible(visible(ModeUiControl::ShortMessages)); + ui->cbFast9->setVisible(visible(ModeUiControl::Fast9)); + ui->cbAutoSeq->setVisible(visible(ModeUiControl::AutoSequence)); + ui->cbTx6->setVisible(visible(ModeUiControl::Tx6)); + ui->pbR2T->setVisible(visible(ModeUiControl::CopyRxToTx)); + ui->pbT2R->setVisible(visible(ModeUiControl::CopyTxToRx)); + ui->cbHoldTxFreq->setVisible(visible(ModeUiControl::HoldTxFrequency)); + setLabeledControlVisible(ModeUiControl::Submode, ui->sbSubmode, m_submodeLabel); + ui->syncSpinBox->setVisible(visible(ModeUiControl::Sync)); + ui->WSPR_controls_widget->setVisible(visible(ModeUiControl::WsprControls)); + ui->ClrAvgButton->setVisible(visible(ModeUiControl::ClearAverage)); + + auto const decodeDepthEnabled = visible(ModeUiControl::DecodeDepth); + ui->actionQuickDecode->setEnabled(decodeDepthEnabled); + ui->actionMediumDecode->setEnabled(decodeDepthEnabled); + ui->actionDeepestDecode->setEnabled(decodeDepthEnabled); + ui->actionInclude_averaging->setVisible(visible(ModeUiControl::IncludeAveraging)); + ui->actionInclude_correlation->setVisible(visible(ModeUiControl::IncludeCorrelation)); + if (!visible(ModeUiControl::EchoGraph) && m_echoGraph->isVisible()) m_echoGraph->hide(); + ui->cbSWL->setVisible(visible(ModeUiControl::Swl)); + + auto const showFt8Ap = visible(ModeUiControl::ApFt8); + ui->actionEnable_AP_FT8->setVisible(showFt8Ap); + ui->actionHide_AP_info->setVisible(showFt8Ap); + ui->actionEnable_AP_JT65->setVisible(visible(ModeUiControl::ApJt65)); + ui->actionEnable_AP_DXcall->setVisible(visible(ModeUiControl::ApDxCall)); + ui->respondComboBox->setVisible(visible(ModeUiControl::Respond)); + ui->measure_check_box->setVisible(visible(ModeUiControl::Measure)); + ui->labDXped->setVisible(visible(ModeUiControl::DxpedLabel)); + ui->cbRxAll->setVisible(visible(ModeUiControl::RxAll)); + ui->cbCQonly->setVisible(visible(ModeUiControl::CqOnly)); + ui->sbTR_FST4W->setVisible(visible(ModeUiControl::Fst4wTrPeriod)); + + auto const showLowFrequency = visible(ModeUiControl::LowFrequency); + auto const showHighFrequency = visible(ModeUiControl::HighFrequency); + ui->opt_controls_stack->setCurrentIndex(showLowFrequency ? 1 : 0); + ui->sbF_Low->setVisible(showLowFrequency); + ui->sbF_High->setVisible(showHighFrequency); + ui->actionAuto_Clear_Avg->setVisible(visible(ModeUiControl::AutoClearAverage)); + setLabeledControlVisible(ModeUiControl::MaxDrift, ui->sbMaxDrift, m_maxDriftLabel); + if (visible(ModeUiControl::FoxQueueTab)) ui->tabWidget->setCurrentIndex(fox_queue_tab_index); + ui->pbBestSP->setVisible(m_mode=="FT4"); - b=false; + bool b=false; if(m_mode=="FT4" or m_mode=="FT8" || "Q65" == m_mode) { b=SpecOp::EU_VHF==m_specOp or ( SpecOp::RTTY==m_specOp and @@ -10773,17 +10253,440 @@ void MainWindow::displayWidgets(qint64 n) } if(m_mode=="MSK144") b=SpecOp::EU_VHF==m_specOp; ui->sbEchoAvg->setVisible(m_mode=="Echo"); + ui->sbSerialNumber->setMaximum(SpecOp::EU_VHF==m_specOp ? eu_vhf_type5_serial_max : default_serial_number_max); ui->sbSerialNumber->setVisible(b); + ui->opt_controls_stack->setVisible (b || showLowFrequency || showHighFrequency); m_lastCallsign.clear (); // ensures Tx5 is updated for new modes b=m_mode.startsWith("FST4"); ui->sbNB->setVisible(b); genStdMsgs (m_rpt, true); configActiveStations(); + updateDecodeAccessibility(); +} + +QString MainWindow::specOpLabel() const +{ + if (m_mode == "MSK144" && m_specOp != SpecOp::EU_VHF + && !(m_specOp == SpecOp::NA_VHF && !m_config.NCCC_Sprint ())) return {}; + return SpecOpLabel::label (m_specOp, m_config.NCCC_Sprint (), m_config.superFox ()); +} + +void MainWindow::initializeFFT(int nsps) +{ + m_nsps = nsps; + m_FFTSize = m_nsps / 2; + if (m_tci_audio) Q_EMIT m_config.transceiver_blocksize(m_FFTSize); + else Q_EMIT FFTSize(m_FFTSize); +} + +void MainWindow::initializeFFT(int nsps, int fftSize) +{ + m_nsps = nsps; + m_FFTSize = fftSize; + if (m_tci_audio) Q_EMIT m_config.transceiver_blocksize(m_FFTSize); + else Q_EMIT FFTSize(m_FFTSize); +} + +void MainWindow::setTxButtonsEnabled(bool enabled) +{ + ui->txrb2->setEnabled(enabled); + ui->txrb4->setEnabled(enabled); + ui->txrb5->setEnabled(enabled); + ui->txrb6->setEnabled(enabled); + ui->txb2->setEnabled(enabled); + ui->txb4->setEnabled(enabled); + ui->txb5->setEnabled(enabled); + ui->txb6->setEnabled(enabled); +} + +void MainWindow::setDXInfo(QString const& call, QString const& grid) +{ + ui->dxCallEntry->setText(call); + ui->dxGridEntry->setText(grid); +} + +void MainWindow::updateMainWindowAccessibility() +{ + auto const tooltipDescription = [] (QWidget *widget) + { + if (widget && widget->accessibleDescription ().isEmpty ()) widget->setAccessibleDescription (widget->toolTip ()); + }; + + ui->dxCallEntry->setAccessibleName (tr ("DX call")); + ui->dxCallEntry->setAccessibleDescription (tr ("Callsign of station to be worked.")); + ui->dxGridEntry->setAccessibleName (tr ("DX grid")); + ui->dxGridEntry->setAccessibleDescription (tr ("Locator of station to be worked.")); + ui->DX_Call_Button->setAccessibleName (tr ("Wait and Call")); + ui->DX_Call_Button->setAccessibleDescription (ui->DX_Call_Button->toolTip ()); + ui->lookupButton->setAccessibleName (tr ("Lookup DX call")); + ui->addButton->setAccessibleName (tr ("Add DX call")); + ui->ignoreButton->setAccessibleName (tr ("Ignore DX call")); + + ui->respondComboBox->setAccessibleName (tr ("CQ response mode")); + ui->respondComboBox->setAccessibleDescription (tr ("Selects a station automatically from replies to your pending CQ after Enable Tx is armed in the current receive period, or from CQ messages for Wait & Pounce.")); + ui->TxFreqSpinBox->setAccessibleName (tr ("Transmit audio frequency")); + ui->RxFreqSpinBox->setAccessibleName (tr ("Receive audio frequency")); + ui->sbFtol->setAccessibleName (tr ("Frequency tolerance")); + ui->rptSpinBox->setAccessibleName (tr ("Signal report")); + ui->sbTR->setAccessibleName (tr ("Transmit and receive period")); + ui->sbSubmode->setAccessibleName (tr ("Submode")); + ui->sbMaxDrift->setAccessibleName (tr ("Maximum drift")); + ui->bandComboBox->setAccessibleName (tr ("Operating band")); + if (ui->bandComboBox->lineEdit ()) ui->bandComboBox->lineEdit ()->setAccessibleName (tr ("Operating band text")); + ui->outAttenuation->setAccessibleName (tr ("Transmit power attenuation")); + ui->outAttenuation->setAccessibleDescription (tr ("Adjust transmit drive attenuation.")); + ui->cbMenus->setAccessibleName (tr ("Menus")); + ui->cbMenus->setAccessibleDescription (tr ("Show or hide the menu bar.")); + ui->readFreq->setAccessibleName (tr ("Rig control status")); + ui->labDialFreq->setAccessibleName (tr ("USB dial frequency")); + ui->houndButton->setAccessibleName (tr ("Hound mode")); + ui->houndButton->setAccessibleDescription (tr ("Toggle FT8 hound mode. Right-click to toggle SuperFox mode.")); + + auto const message_selector_name = tr ("Message panel selector"); + auto const message_selector_description = tr ("Switches between standard messages, Fox queue, and band hopping pages. Press 1, 2, or 3 while focused to select a page."); + ui->tabWidget->setAccessibleName (message_selector_name); + ui->tabWidget->setAccessibleDescription (message_selector_description); + if (ui->tabWidget->tabBar ()) + { + auto *tab_bar = ui->tabWidget->tabBar (); + tab_bar->setAccessibleName (message_selector_name); + tab_bar->setAccessibleDescription (message_selector_description); + tab_bar->setFocusPolicy (Qt::StrongFocus); + } + ui->tabWidget->setTabToolTip (0, tr ("Standard messages")); + ui->tabWidget->setTabToolTip (1, tr ("Fox queue")); + ui->tabWidget->setTabToolTip (2, tr ("Band hopping")); + ui->tabWidget->widget (0)->setAccessibleName (tr ("Standard messages page")); + ui->tabWidget->widget (1)->setAccessibleName (tr ("Fox queue page")); + ui->tabWidget->widget (2)->setAccessibleName (tr ("Band hopping page")); + ui->houndQueueTextBrowser->setAccessibleName (tr ("Hound queue")); + ui->houndQueueTextBrowser->setAccessibleDescription (tr ("Queued Hound callers available for Fox transmissions.")); + ui->foxTxListTextBrowser->setAccessibleName (tr ("Fox transmissions in progress")); + ui->foxTxListTextBrowser->setAccessibleDescription (tr ("Hound callers currently in progress for Fox transmissions.")); + ui->comboBoxHoundSort->setAccessibleName (tr ("Hound queue sort order")); + ui->sbNlist->setAccessibleName (tr ("Hound queue list size")); + ui->sbNslots->setAccessibleName (tr ("Fox transmission slots")); + ui->comboBoxCQ->setAccessibleName (tr ("Fox CQ message")); + ui->pbFoxReset->setAccessibleName (tr ("Reset Fox queues")); + ui->pbFreeText->setAccessibleName (tr ("Fox free text")); + ui->cbSendMsg->setAccessibleName (tr ("Send Fox free text")); + ui->pbBandHopping->setAccessibleName (tr ("Band hopping")); + ui->cbQRG1->setAccessibleName (tr ("Enable FT8 QRG 1")); + ui->cbQRG2->setAccessibleName (tr ("Enable FT8 QRG 2")); + ui->cbQRG3->setAccessibleName (tr ("Enable FT8 QRG 3")); + ui->cbQRG4->setAccessibleName (tr ("Enable FT8 QRG 4")); + ui->cbQRG5->setAccessibleName (tr ("Enable FT8 QRG 5")); + ui->cbQRG6->setAccessibleName (tr ("Enable FT8 QRG 6")); + ui->cbQRG7->setAccessibleName (tr ("Enable FT8 QRG 7")); + ui->cbQRG8->setAccessibleName (tr ("Enable FT8 QRG 8")); + ui->sbQRG1->setAccessibleName (tr ("FT8 QRG 1 frequency")); + ui->sbQRG2->setAccessibleName (tr ("FT8 QRG 2 frequency")); + ui->sbQRG3->setAccessibleName (tr ("FT8 QRG 3 frequency")); + ui->sbQRG4->setAccessibleName (tr ("FT8 QRG 4 frequency")); + ui->sbQRG5->setAccessibleName (tr ("FT8 QRG 5 frequency")); + ui->sbQRG6->setAccessibleName (tr ("FT8 QRG 6 frequency")); + ui->sbQRG7->setAccessibleName (tr ("FT8 QRG 7 frequency")); + ui->sbQRG8->setAccessibleName (tr ("FT8 QRG 8 frequency")); + + ui->tx1->setAccessibleName (tr ("Tx1 message")); + ui->tx2->setAccessibleName (tr ("Tx2 message")); + ui->tx3->setAccessibleName (tr ("Tx3 message")); + ui->tx4->setAccessibleName (tr ("Tx4 message")); + ui->tx5->setAccessibleName (tr ("Tx5 message macro")); + ui->tx6->setAccessibleName (tr ("Tx6 message")); + if (ui->tx5->lineEdit ()) ui->tx5->lineEdit ()->setAccessibleName (tr ("Tx5 message macro text")); + + ui->txrb1->setAccessibleName (tr ("Select Tx1 for next transmission")); + ui->txrb2->setAccessibleName (tr ("Select Tx2 for next transmission")); + ui->txrb3->setAccessibleName (tr ("Select Tx3 for next transmission")); + ui->txrb4->setAccessibleName (tr ("Select Tx4 for next transmission")); + ui->txrb5->setAccessibleName (tr ("Select Tx5 for next transmission")); + ui->txrb6->setAccessibleName (tr ("Select Tx6 for next transmission")); + ui->txb1->setAccessibleName (tr ("Transmit Tx1 now")); + ui->txb2->setAccessibleName (tr ("Transmit Tx2 now")); + ui->txb3->setAccessibleName (tr ("Transmit Tx3 now")); + ui->txb4->setAccessibleName (tr ("Transmit Tx4 now")); + ui->txb5->setAccessibleName (tr ("Transmit Tx5 now")); + ui->txb6->setAccessibleName (tr ("Transmit Tx6 now")); + + std::array<QWidget *, 26> const tooltip_widgets {{ + ui->tx1, ui->tx2, ui->tx3, ui->tx4, ui->tx5, ui->tx6, + ui->txrb1, ui->txrb2, ui->txrb3, ui->txrb4, ui->txrb5, ui->txrb6, + ui->txb1, ui->txb2, ui->txb3, ui->txb4, ui->txb5, ui->txb6, + ui->comboBoxHoundSort, ui->sbNlist, ui->sbNslots, ui->comboBoxCQ, + ui->pbFoxReset, ui->pbFreeText, ui->cbSendMsg, ui->pbBandHopping + }}; + for (auto *widget : tooltip_widgets) + { + tooltipDescription (widget); + } + +} + +void MainWindow::registerMainWindowFocusControls() +{ + ui->tabWidget->setFocusProxy (ui->tabWidget->tabBar ()); + QList<QWidget *> const tab_controls { + ui->decodedTextBrowser, ui->decodedTextBrowser2, ui->cbCQonly, ui->cbBypass, + ui->logQSOButton, ui->stopButton, ui->monitorButton, ui->EraseButton, + ui->ClrAvgButton, ui->DecodeButton, ui->autoButton, ui->stopTxButton, + ui->tuneButton, ui->cbMenus, ui->sbNB, ui->bandComboBox, + ui->pb160, ui->pb80, ui->pb60, ui->pb40, ui->pb30, ui->pb20, + ui->pb17, ui->pb15, ui->pb12, ui->pb10, ui->pb8, ui->pb6, + ui->pb4, ui->pb2, ui->pb70, ui->pb50, ui->pb144, ui->pb220, + ui->pb432, ui->pb902, ui->pb23, ui->pb13, ui->pb9, ui->pb5G, + ui->pb10G, ui->pb24G, ui->labDialFreq, ui->readFreq, + ui->houndButton, ui->ft8Button, ui->ft4Button, ui->msk144Button, + ui->q65Button, ui->jt65Button, ui->dxCallEntry, ui->dxGridEntry, + ui->DX_Call_Button, ui->lookupButton, ui->addButton, ui->ignoreButton, + ui->txFirstCheckBox, ui->cbHoldTxFreq, ui->TxFreqSpinBox, ui->sbSubmode, + ui->pbR2T, ui->sbFtol, ui->pbT2R, ui->sbMaxDrift, + ui->RxFreqSpinBox, ui->rptSpinBox, ui->sbSerialNumber, + ui->sbF_Low, ui->sbF_High, ui->sbTR, ui->syncSpinBox, + ui->sbCQTxFreq, ui->cbCQTx, ui->cbRxAll, + ui->cbShMsgs, ui->cbFast9, ui->cbAutoSeq, ui->respondComboBox, + ui->cbTx6, ui->cbSWL, ui->pbBestSP, ui->measure_check_box, + ui->tabWidget->tabBar (), + ui->genStdMsgsPushButton, + ui->txb1, ui->txb2, ui->txb3, ui->txb4, ui->txb5, ui->txb6, + ui->tx1, ui->tx2, ui->tx3, ui->tx4, ui->tx5, ui->tx6, + ui->houndQueueTextBrowser, ui->foxTxListTextBrowser, ui->comboBoxHoundSort, + ui->sbNlist, ui->sbNslots, ui->comboBoxCQ, ui->cbWorkDupes, ui->cbMoreCQs, + ui->pbFoxReset, ui->pbFreeText, ui->cbSendMsg, + ui->cb160m, ui->cb80m, ui->cb40m, ui->cb30m, ui->cb20m, ui->cb17m, + ui->cb15m, ui->cb12m, ui->cb10m, ui->cb6m, ui->cb4m, ui->cb2m, ui->cb70cm, + ui->cb80mFT4, ui->cb40mFT4, ui->cb30mFT4, ui->cb20mFT4, ui->cb17mFT4, + ui->cb15mFT4, ui->cb12mFT4, ui->cb10mFT4, ui->cb2mMSK, + ui->cbQRG1, ui->sbQRG1, ui->cbQRG2, ui->sbQRG2, ui->cbQRG3, ui->sbQRG3, + ui->cbQRG4, ui->sbQRG4, ui->cbQRG5, ui->sbQRG5, ui->cbQRG6, ui->sbQRG6, + ui->cbQRG7, ui->sbQRG7, ui->cbQRG8, ui->sbQRG8, ui->pbBandHopping, + ui->WSPRfreqSpinBox, ui->sbFST4W_RxFreq, ui->sbFST4W_FTol, + ui->RoundRobin, ui->sbTxPercent, ui->sbTR_FST4W, + ui->band_hopping_group_box, ui->band_hopping_schedule_push_button, + ui->cbUploadWSPR_Spots, ui->WSPR_prefer_type_1_check_box, ui->cbNoOwnCall, + ui->pbTxNext, ui->TxPowerComboBox, ui->outAttenuation + }; + + for (auto *widget : tab_controls) + { + if (!widget) continue; + widget->setFocusPolicy (Qt::StrongFocus); + } + + for (auto *widget : focusIndicatorWidgets ()) + { + widget->installEventFilter (this); + } + + // A disabled widget never gets its mouse-press event propagated to any + // ancestor's mousePressEvent() -- Qt swallows it at the widget itself, so + // this can only be caught by a filter installed directly on the checkbox. + ui->txFirstCheckBox->installEventFilter (this); + + for (auto *button : txNextButtons ()) + { + connect (button, &QRadioButton::toggled, this, [this] (bool checked) { + if (checked) updateTxNextFocusPolicies (); + }); + } + updateTxNextFocusPolicies (); +} + +bool MainWindow::switchMainWindowTab(QKeyEvent const *key_event) +{ + auto *focus_widget = QApplication::focusWidget (); + if (focus_widget != ui->tabWidget && focus_widget != ui->tabWidget->tabBar ()) + { + return false; + } + + auto const modifiers = key_event->modifiers () + & (Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier); + if (modifiers != Qt::NoModifier) return false; + + int next_index = ui->tabWidget->currentIndex (); + switch (key_event->key ()) + { + case Qt::Key_1: next_index = 0; break; + case Qt::Key_2: next_index = 1; break; + case Qt::Key_3: next_index = 2; break; + case Qt::Key_Left: + case Qt::Key_Up: + next_index = (next_index + ui->tabWidget->count () - 1) % ui->tabWidget->count (); + break; + case Qt::Key_Right: + case Qt::Key_Down: + next_index = (next_index + 1) % ui->tabWidget->count (); + break; + default: + return false; + } + + ui->tabWidget->setCurrentIndex (next_index); + auto *tab_bar = ui->tabWidget->tabBar (); + QTimer::singleShot (0, tab_bar, [tab_bar] { + tab_bar->setFocus (Qt::OtherFocusReason); + }); + return true; +} + +std::array<QRadioButton *, 6> MainWindow::txNextButtons() const +{ + return {{qobject_cast<QRadioButton *> (m_tx_message_button_group->button (1)), + qobject_cast<QRadioButton *> (m_tx_message_button_group->button (2)), + qobject_cast<QRadioButton *> (m_tx_message_button_group->button (3)), + qobject_cast<QRadioButton *> (m_tx_message_button_group->button (4)), + qobject_cast<QRadioButton *> (m_tx_message_button_group->button (5)), + qobject_cast<QRadioButton *> (m_tx_message_button_group->button (6))}}; +} + +std::array<QWidget *, 13> MainWindow::focusIndicatorWidgets() const +{ + auto const buttons = txNextButtons (); + return {{ui->tabWidget->tabBar (), + buttons[0], buttons[1], buttons[2], buttons[3], buttons[4], buttons[5], + ui->txb1, ui->txb2, ui->txb3, ui->txb4, ui->txb5, ui->txb6}}; +} + +void MainWindow::showMainWindowFocusIndicator(QWidget *widget) +{ + if (widget == ui->tabWidget->tabBar ()) + { + m_message_selector_focus_frame->setGeometry (widget->rect ()); + m_message_selector_focus_frame->raise (); + m_message_selector_focus_frame->show (); + return; + } + + m_main_window_focus_frame->setWidget (widget); + m_main_window_focus_frame->raise (); + m_main_window_focus_frame->show (); +} + +void MainWindow::hideMainWindowFocusIndicators() +{ + m_message_selector_focus_frame->hide (); + m_main_window_focus_frame->hide (); + m_main_window_focus_frame->setWidget (nullptr); +} + +void MainWindow::updateTxNextFocusPolicies() +{ + auto const buttons = txNextButtons (); + QRadioButton *tab_button = nullptr; + for (auto *button : buttons) + { + if (button->isChecked () && button->isEnabled () && !button->isHidden ()) + { + tab_button = button; + break; + } + } + if (!tab_button) + { + for (auto *button : buttons) + { + if (button->isEnabled () && !button->isHidden ()) + { + tab_button = button; + break; + } + } + } + + for (auto *button : buttons) + { + button->setFocusPolicy (button == tab_button ? Qt::StrongFocus : Qt::ClickFocus); + } +} + +void MainWindow::updateTxFirstEnabledState() +{ + ui->txFirstCheckBox->setEnabled (m_tx_first_user_enabled && m_tx_first_mode_enabled); +} + +void MainWindow::setTxFirstModeEnabled(bool enabled) +{ + m_tx_first_mode_enabled = enabled; + updateTxFirstEnabledState (); +} + +bool MainWindow::switchTxNextMessage(QKeyEvent const *key_event) +{ + auto const buttons = txNextButtons (); + auto *focus_button = qobject_cast<QRadioButton *> (QApplication::focusWidget ()); + auto const current = std::find (buttons.cbegin (), buttons.cend (), focus_button); + if (current == buttons.cend ()) return false; + auto const current_index = static_cast<int> (std::distance (buttons.cbegin (), current)); + + auto const modifiers = key_event->modifiers () + & (Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier); + if (modifiers != Qt::NoModifier) return false; + + int direction = 0; + switch (key_event->key ()) + { + case Qt::Key_Left: + case Qt::Key_Up: direction = -1; break; + case Qt::Key_Right: + case Qt::Key_Down: direction = 1; break; + default: return false; + } + + auto const button_count = static_cast<int> (buttons.size ()); + for (int offset = 1; offset < button_count; ++offset) + { + auto const next_index = (current_index + direction * offset + button_count) % button_count; + auto *button = buttons[next_index]; + if (button->isEnabledTo (this) && button->isVisibleTo (this)) + { + button->click (); + button->setFocus (direction < 0 ? Qt::BacktabFocusReason : Qt::TabFocusReason); + return true; + } + } + return false; +} + +void MainWindow::updateDecodeAccessibility() +{ + auto const updatePane = [] (QLabel *titleLabel, QLabel *headingsLabel, DisplayText *pane) + { + auto const title = titleLabel->text(); + auto const headings = decodeHeadingText(headingsLabel->text()); + + titleLabel->setAccessibleName(QString {"%1 decode pane title"}.arg (title)); + titleLabel->setAccessibleDescription(QString {"Title for the %1 decoded messages pane."}.arg (title)); + + headingsLabel->setAccessibleName(QString {"%1 decoded messages headings"}.arg (title)); + headingsLabel->setAccessibleDescription(decodeLineDescription(headings)); + + pane->setAccessibleName(QString {"%1 decoded messages"}.arg (title)); + pane->setAccessibleDescription(QString {"Decoded messages in the %1 pane. %2"} + .arg (title) + .arg (decodeLineDescription(headings))); + }; + + updatePane (ui->lh_decodes_title_label, ui->lh_decodes_headings_label, ui->decodedTextBrowser); + updatePane (ui->rh_decodes_title_label, ui->rh_decodes_headings_label, ui->decodedTextBrowser2); +} + +void MainWindow::setDecodeTitles(QString const& lh, QString const& rh) +{ + ui->lh_decodes_title_label->setText(lh); + ui->rh_decodes_title_label->setText(rh); +} + +void MainWindow::setDecodeHeadings(QString const& lh, QString const& rh) +{ + ui->lh_decodes_headings_label->setText(lh); + ui->rh_decodes_headings_label->setText(rh); } void MainWindow::on_actionFST4_triggered() { - QTimer::singleShot (50, [=] { + noteTxModeChange (QStringLiteral ("FST4")); + QTimer::singleShot (50, this, [=] { ui->TxFreqSpinBox->setValue(m_settings->value("TxFreq_old",1500).toInt()); ui->RxFreqSpinBox->setValue(m_settings->value("RxFreq_old",1500).toInt()); on_sbSubmode_valueChanged(ui->sbSubmode->value()); @@ -10801,19 +10704,25 @@ void MainWindow::on_actionFST4_triggered() m_wideGraph->show(); if (m_tci_audio && ui->bandComboBox->currentText()!="OOB") Q_EMIT m_config.transceiver_period(m_TRperiod); - m_nsps=6912; //For symspec only - m_FFTSize = m_nsps / 2; - if (m_tci_audio) Q_EMIT m_config.transceiver_blocksize (m_FFTSize); - else Q_EMIT FFTSize (m_FFTSize); - ui->lh_decodes_title_label->setText(tr ("Band Activity")); - ui->rh_decodes_title_label->setText(tr ("Rx Frequency")); + initializeFFT(6912); + setDecodeTitles(tr ("Band Activity"), tr ("Rx Frequency")); WSPR_config(false); if(m_config.single_decode()) { -// 01234567890123456789012345678901234567 - displayWidgets(nWidgets("11111100010011100001000000010000000000")); + applyModeUiState({ModeUiControl::TxFirst, ModeUiControl::TxFrequency, + ModeUiControl::RxFrequency, ModeUiControl::FrequencyTolerance, + ModeUiControl::Report, ModeUiControl::TrPeriod, + ModeUiControl::AutoSequence, ModeUiControl::CopyRxToTx, + ModeUiControl::CopyTxToRx, ModeUiControl::HoldTxFrequency, + ModeUiControl::DecodeDepth, ModeUiControl::Respond}); m_wideGraph->setSingleDecode(true); } else { - displayWidgets(nWidgets("11101100010011100001000000010000001100")); + applyModeUiState({ModeUiControl::TxFirst, ModeUiControl::TxFrequency, + ModeUiControl::RxFrequency, ModeUiControl::Report, + ModeUiControl::TrPeriod, ModeUiControl::AutoSequence, + ModeUiControl::CopyRxToTx, ModeUiControl::CopyTxToRx, + ModeUiControl::HoldTxFrequency, ModeUiControl::DecodeDepth, + ModeUiControl::Respond, ModeUiControl::LowFrequency, + ModeUiControl::HighFrequency}); m_wideGraph->setSingleDecode(false); ui->sbFtol->setValue(20); } @@ -10830,8 +10739,8 @@ void MainWindow::on_actionFST4_triggered() m_wideGraph->setMode(m_mode); ui->sbTR->values ({15, 30, 60, 120, 300, 900, 1800}); ui->sbTR->setValue (m_settings->value ("TRPeriod_FST4", 60).toInt()); // remember sbTR settings by mode - QTimer::singleShot (50, [=] {on_sbTR_valueChanged (ui->sbTR->value());}); - ui->txFirstCheckBox->setEnabled(true); + QTimer::singleShot (50, this, [=] {on_sbTR_valueChanged (ui->sbTR->value());}); + setTxFirstModeEnabled (true); statusChanged(); m_bOK_to_chk=true; chk_FST4_freq_range(); @@ -10839,6 +10748,7 @@ void MainWindow::on_actionFST4_triggered() void MainWindow::on_actionFST4W_triggered() { + noteTxModeChange (QStringLiteral ("FST4W")); m_mode="FST4W"; if(m_specOp==SpecOp::HOUND) { m_config.setSpecial_None(); @@ -10851,13 +10761,10 @@ void MainWindow::on_actionFST4W_triggered() m_wideGraph->show(); if (m_tci_audio && ui->bandComboBox->currentText()!="OOB") Q_EMIT m_config.transceiver_period(m_TRperiod); - m_nsps=6912; //For symspec only - m_FFTSize = m_nsps / 2; - if (m_tci_audio) Q_EMIT m_config.transceiver_blocksize (m_FFTSize); - else Q_EMIT FFTSize (m_FFTSize); + initializeFFT(6912); WSPR_config(true); -// 01234567890123456789012345678901234567 - displayWidgets(nWidgets("00000000000000000101000000000000010000")); + applyModeUiState({ModeUiControl::WsprControls, ModeUiControl::DecodeDepth, + ModeUiControl::Fst4wTrPeriod}); setup_status_bar(false); ui->band_hopping_group_box->setChecked(false); ui->band_hopping_group_box->setVisible(false); @@ -10876,8 +10783,9 @@ void MainWindow::on_actionFST4W_triggered() void MainWindow::on_actionFT4_triggered() { - if (m_mode=="MSK144") QTimer::singleShot (75, [=] {on_actionFT4_triggered();}); - QTimer::singleShot (50, [=] { + noteTxModeChange (QStringLiteral ("FT4")); + if (m_mode=="MSK144") QTimer::singleShot (75, this, [=] {on_actionFT4_triggered();}); + QTimer::singleShot (50, this, [=] { ui->TxFreqSpinBox->setValue(m_settings->value("TxFreq_old",1500).toInt()); ui->RxFreqSpinBox->setValue(m_settings->value("RxFreq_old",1500).toInt()); on_sbSubmode_valueChanged(ui->sbSubmode->value()); @@ -10894,10 +10802,7 @@ void MainWindow::on_actionFT4_triggered() m_bFastMode=false; WSPR_config(false); switch_mode (Modes::FT4); - m_nsps=6912; - m_FFTSize = m_nsps/2; - if (m_tci_audio) Q_EMIT m_config.transceiver_blocksize (m_FFTSize); - else Q_EMIT FFTSize (m_FFTSize); + initializeFFT(6912); m_hsymStop=21; setup_status_bar (bVHF); m_toneSpacing=12000.0/576.0; @@ -10908,36 +10813,32 @@ void MainWindow::on_actionFT4_triggered() ui->cbAutoSeq->setChecked(true); m_fastGraph->hide(); m_wideGraph->show(); - ui->rh_decodes_headings_label->setText(" UTC dB DT Freq " + tr ("Message")); m_wideGraph->setPeriod(m_TRperiod,m_nsps); if (m_tci_audio && ui->bandComboBox->currentText()!="OOB") Q_EMIT m_config.transceiver_period(m_TRperiod); if (!m_tci_audio) { m_modulator->setTRPeriod(m_TRperiod); // TODO - not thread safe - m_detector->setTRPeriod(m_TRperiod); // TODO - not thread safe - } - ui->rh_decodes_title_label->setText(tr ("Rx Frequency")); - ui->lh_decodes_title_label->setText(tr ("Band Activity")); - ui->lh_decodes_headings_label->setText( " UTC dB DT Freq " + tr ("Message")); -// 01234567890123456789012345678901234567 - displayWidgets(nWidgets("11101000010011100001000000011000100000")); - ui->txrb2->setEnabled(true); - ui->txrb4->setEnabled(true); - ui->txrb5->setEnabled(true); - ui->txrb6->setEnabled(true); - ui->txb2->setEnabled(true); - ui->txb4->setEnabled(true); - ui->txb5->setEnabled(true); - ui->txb6->setEnabled(true); - ui->txFirstCheckBox->setEnabled(true); + m_detector->setTRPeriod(m_TRperiod); // marshals to the audio thread + } + setDecodeTitles(tr ("Band Activity"), tr ("Rx Frequency")); + setDecodeHeadings(" UTC dB DT Freq " + tr ("Message"), " UTC dB DT Freq " + tr ("Message")); + applyModeUiState({ModeUiControl::TxFirst, ModeUiControl::TxFrequency, + ModeUiControl::RxFrequency, ModeUiControl::Report, + ModeUiControl::AutoSequence, ModeUiControl::CopyRxToTx, + ModeUiControl::CopyTxToRx, ModeUiControl::HoldTxFrequency, + ModeUiControl::DecodeDepth, ModeUiControl::Respond, + ModeUiControl::CqOnly}); + setTxButtonsEnabled(true); + setTxFirstModeEnabled (true); chkFT4(); statusChanged(); } void MainWindow::on_actionFT8_triggered() { - if (m_mode=="MSK144") QTimer::singleShot (75, [=] {on_actionFT8_triggered();}); - QTimer::singleShot (50, [=] { + noteTxModeChange (QStringLiteral ("FT8")); + if (m_mode=="MSK144") QTimer::singleShot (75, this, [=] {on_actionFT8_triggered();}); + QTimer::singleShot (50, this, [=] { if(m_specOp!=SpecOp::FOX) ui->TxFreqSpinBox->setValue(m_settings->value("TxFreq_old",1500).toInt()); if(m_specOp==SpecOp::FOX && !m_config.superFox()) ui->TxFreqSpinBox->setValue(m_TxFreqFox); if(SpecOp::HOUND == m_specOp && m_config.superFox()) { @@ -10958,10 +10859,7 @@ void MainWindow::on_actionFT8_triggered() m_bFast9=false; m_bFastMode=false; WSPR_config(false); - m_nsps=6912; - m_FFTSize = m_nsps / 2; - if (m_tci_audio) Q_EMIT m_config.transceiver_blocksize (m_FFTSize); - else Q_EMIT FFTSize (m_FFTSize); + initializeFFT(6912); if (m_multithreadFT8 && !(m_specOp==SpecOp::HOUND && m_config.superFox())) { if (m_ft8DecoderStart==0) m_hsymStop=49; else if (m_ft8DecoderStart==1) { @@ -10991,7 +10889,7 @@ void MainWindow::on_actionFT8_triggered() Q_EMIT m_config.transceiver_period(m_TRperiod); if (!m_tci_audio) { m_modulator->setTRPeriod(m_TRperiod); // TODO - not thread safe - m_detector->setTRPeriod(m_TRperiod); // TODO - not thread safe + m_detector->setTRPeriod(m_TRperiod); // marshals to the audio thread } ui->rh_decodes_title_label->setText(tr ("Rx Frequency")); if(SpecOp::FOX==m_specOp) { @@ -11001,25 +10899,21 @@ void MainWindow::on_actionFT8_triggered() ui->lh_decodes_title_label->setText(tr ("Band Activity")); ui->lh_decodes_headings_label->setText( " UTC dB DT Freq " + tr ("Message")); } - -// 01234567890123456789012345678901234567 - displayWidgets(nWidgets("11101000010011100001000010011000100000")); - ui->txrb2->setEnabled(true); - ui->txrb4->setEnabled(true); - ui->txrb5->setEnabled(true); - ui->txrb6->setEnabled(true); - ui->txb2->setEnabled(true); - ui->txb4->setEnabled(true); - ui->txb5->setEnabled(true); - ui->txb6->setEnabled(true); - ui->txFirstCheckBox->setEnabled(true); + + applyModeUiState({ModeUiControl::TxFirst, ModeUiControl::TxFrequency, + ModeUiControl::RxFrequency, ModeUiControl::Report, + ModeUiControl::AutoSequence, ModeUiControl::CopyRxToTx, + ModeUiControl::CopyTxToRx, ModeUiControl::HoldTxFrequency, + ModeUiControl::DecodeDepth, ModeUiControl::ApFt8, + ModeUiControl::Respond, ModeUiControl::CqOnly}); + setTxButtonsEnabled(true); + setTxFirstModeEnabled (true); ui->cbAutoSeq->setEnabled(true); if(SpecOp::FOX==m_specOp) { ui->txFirstCheckBox->setChecked(true); - ui->txFirstCheckBox->setEnabled(false); + setTxFirstModeEnabled (false); ui->cbHoldTxFreq->setChecked(true); ui->cbAutoSeq->setEnabled(false); - ui->tabWidget->setCurrentIndex(1); m_wideGraph->setSuperFox(false); if(m_config.superFox()) { ui->TxFreqSpinBox->setValue(750); //SuperFox transmits at 750 Hz @@ -11027,29 +10921,34 @@ void MainWindow::on_actionFT8_triggered() } else { ui->TxFreqSpinBox->setValue(500); } - // 01234567890123456789012345678901234567 - displayWidgets(nWidgets("11101000010011100001000000000011000000")); + applyModeUiState({ModeUiControl::TxFirst, ModeUiControl::TxFrequency, + ModeUiControl::RxFrequency, ModeUiControl::Report, + ModeUiControl::AutoSequence, ModeUiControl::CopyRxToTx, + ModeUiControl::CopyTxToRx, ModeUiControl::HoldTxFrequency, + ModeUiControl::DecodeDepth, ModeUiControl::DxpedLabel, + ModeUiControl::RxAll, ModeUiControl::FoxQueueTab}); ui->cbRxAll->setText(tr("Show Already Worked")); - if(m_config.superFox()) { - ui->labDXped->setText(tr ("Super Fox")); - } else { - ui->labDXped->setText(tr ("Fox")); - } + ui->labDXped->setText(specOpLabel()); on_fox_log_action_triggered(); if (m_ActiveStationsWidget) m_ActiveStationsWidget->setClickOK(true); // allow clicks } if(SpecOp::HOUND == m_specOp) { ui->houndButton->setChecked(true); ui->txFirstCheckBox->setChecked(false); - ui->txFirstCheckBox->setEnabled(false); + setTxFirstModeEnabled (false); ui->cbAutoSeq->setEnabled(false); - ui->tabWidget->setCurrentIndex(0); + if(ui->tabWidget->currentIndex() == fox_queue_tab_index) { + ui->tabWidget->setCurrentIndex(standard_messages_tab_index); + } ui->cbHoldTxFreq->setChecked(true); m_wideGraph->setSuperHound(false); if(m_config.superFox()) { - // 01234567890123456789012345678901234567 - displayWidgets(nWidgets("11111000010011000001000000000011000000")); - ui->labDXped->setText(tr ("Super Hound")); + applyModeUiState({ModeUiControl::TxFirst, ModeUiControl::TxFrequency, + ModeUiControl::RxFrequency, ModeUiControl::FrequencyTolerance, + ModeUiControl::Report, ModeUiControl::AutoSequence, + ModeUiControl::CopyRxToTx, ModeUiControl::CopyTxToRx, + ModeUiControl::DecodeDepth, ModeUiControl::DxpedLabel, + ModeUiControl::RxAll}); ui->cbRxAll->setEnabled(false); m_wideGraph->setRxFreq(ui->RxFreqSpinBox->value()); m_wideGraph->setTol(ui->sbFtol->value()); @@ -11058,22 +10957,18 @@ void MainWindow::on_actionFT8_triggered() if(ui->RxFreqSpinBox->value() < 700 or ui->RxFreqSpinBox->value() > 800) ui->RxFreqSpinBox->setValue(750); } else { - // 01234567890123456789012345678901234567 - displayWidgets(nWidgets("11101000010011000001000000000011000000")); - ui->labDXped->setText(tr ("Hound")); + applyModeUiState({ModeUiControl::TxFirst, ModeUiControl::TxFrequency, + ModeUiControl::RxFrequency, ModeUiControl::Report, + ModeUiControl::AutoSequence, ModeUiControl::CopyRxToTx, + ModeUiControl::CopyTxToRx, ModeUiControl::DecodeDepth, + ModeUiControl::DxpedLabel, ModeUiControl::RxAll}); ui->cbRxAll->setEnabled(true); m_wideGraph->setSuperHound(false); ui->RxFreqSpinBox->setValue(m_settings->value("RxFreq_old",1500).toInt()); } + ui->labDXped->setText(specOpLabel()); ui->txrb1->setChecked(true); - ui->txrb2->setEnabled(false); - ui->txrb4->setEnabled(false); - ui->txrb5->setEnabled(false); - ui->txrb6->setEnabled(false); - ui->txb2->setEnabled(false); - ui->txb4->setEnabled(false); - ui->txb5->setEnabled(false); - ui->txb6->setEnabled(false); + setTxButtonsEnabled(false); if (m_ActiveStationsWidget) m_ActiveStationsWidget->setClickOK(false); } else { switch_mode (Modes::FT8); @@ -11085,15 +10980,8 @@ void MainWindow::on_actionFT8_triggered() m_specOp=m_config.special_op_id(); if(m_specOp!=SpecOp::NONE and m_specOp!=SpecOp::FOX and m_specOp!=SpecOp::HOUND) { - QString t0=""; - if(SpecOp::NA_VHF==m_specOp) t0="NA VHF"; - if(SpecOp::EU_VHF==m_specOp) t0="EU VHF"; - if(SpecOp::FIELD_DAY==m_specOp) t0="Field Day"; - if(SpecOp::RTTY==m_specOp) t0="FT RU"; - if(SpecOp::WW_DIGI==m_specOp) t0="WW Digi"; - if(SpecOp::ARRL_DIGI==m_specOp) t0="ARRL Digi"; - if(SpecOp::Q65_PILEUP==m_specOp) t0="Q65 Pileup"; - if(t0=="") { + QString t0 = specOpLabel(); + if(t0.isEmpty()) { ui->labDXped->setVisible(false); } else { ui->labDXped->setVisible(true); @@ -11111,14 +10999,16 @@ void MainWindow::on_actionFT8_triggered() "the *Settings | Radio* tab.)", errorMsg); m_bWarnedSplit=true; } - if (ui->labDXped->isVisible()) ui->labDXped->setStyleSheet("QLabel {background-color: red; color: white;}"); + m_houndVerified = false; + updateHoundVerificationStyle (); statusChanged(); configActiveStations(); } void MainWindow::on_actionJT4_triggered() { - QTimer::singleShot (50, [=] { + noteTxModeChange (QStringLiteral ("JT4")); + QTimer::singleShot (50, this, [=] { ui->TxFreqSpinBox->setValue(m_settings->value("TxFreq_old",1500).toInt()); ui->RxFreqSpinBox->setValue(m_settings->value("RxFreq_old",1500).toInt()); }); @@ -11135,12 +11025,9 @@ void MainWindow::on_actionJT4_triggered() Q_EMIT m_config.transceiver_period(m_TRperiod); if (!m_tci_audio) { m_modulator->setTRPeriod(m_TRperiod); // TODO - not thread safe - m_detector->setTRPeriod(m_TRperiod); // TODO - not thread safe + m_detector->setTRPeriod(m_TRperiod); // marshals to the audio thread } - m_nsps=6912; //For symspec only - m_FFTSize = m_nsps / 2; - if (m_tci_audio) Q_EMIT m_config.transceiver_blocksize (m_FFTSize); - else Q_EMIT FFTSize (m_FFTSize); + initializeFFT(6912); m_hsymStop=176; if(m_config.decode_at_52s()) m_hsymStop=184; m_toneSpacing=0.0; @@ -11152,32 +11039,43 @@ void MainWindow::on_actionJT4_triggered() m_bFast9=false; setup_status_bar (bVHF); ui->sbSubmode->setMaximum(6); - ui->lh_decodes_headings_label->setText("UTC dB DT Freq " + tr ("Message")); - ui->rh_decodes_headings_label->setText("UTC dB DT Freq " + tr ("Message")); + setDecodeHeadings("UTC dB DT Freq " + tr ("Message"), "UTC dB DT Freq " + tr ("Message")); if(bVHF) { // restore last used parameters ui->sbFtol->setValue (m_settings->value ("Ftol_JT4", 50).toInt()); m_nSubMode=m_settings->value("SubMode_JT4",0).toInt(); ui->sbSubmode->setValue(m_settings->value("SubMode_JT4",0).toInt()); - QTimer::singleShot (50, [=] {on_sbSubmode_valueChanged(ui->sbSubmode->value());}); + QTimer::singleShot (50, this, [=] {on_sbSubmode_valueChanged(ui->sbSubmode->value());}); m_bShMsgs=m_settings->value("ShMsgs_JT4",false).toBool(); ui->cbShMsgs->setChecked(m_bShMsgs); } else { ui->sbSubmode->setValue(0); } if(bVHF) { - // 01234567890123456789012345678901234567 - displayWidgets(nWidgets("11111001011011011011110000010000000000")); + applyModeUiState({ModeUiControl::TxFirst, ModeUiControl::TxFrequency, + ModeUiControl::RxFrequency, ModeUiControl::FrequencyTolerance, + ModeUiControl::Report, ModeUiControl::ShortMessages, + ModeUiControl::AutoSequence, ModeUiControl::Tx6, + ModeUiControl::CopyRxToTx, ModeUiControl::CopyTxToRx, + ModeUiControl::Submode, ModeUiControl::Sync, + ModeUiControl::ClearAverage, ModeUiControl::DecodeDepth, + ModeUiControl::IncludeAveraging, + ModeUiControl::IncludeCorrelation, ModeUiControl::Respond}); } else { - displayWidgets(nWidgets("11101000010011000011000000010000000000")); + applyModeUiState({ModeUiControl::TxFirst, ModeUiControl::TxFrequency, + ModeUiControl::RxFrequency, ModeUiControl::Report, + ModeUiControl::AutoSequence, ModeUiControl::CopyRxToTx, + ModeUiControl::CopyTxToRx, ModeUiControl::ClearAverage, + ModeUiControl::DecodeDepth, ModeUiControl::Respond}); } fast_config(false); - ui->txFirstCheckBox->setEnabled(true); + setTxFirstModeEnabled (true); statusChanged(); } void MainWindow::on_actionJT9_triggered() { + noteTxModeChange (QStringLiteral ("JT9")); m_mode="JT9"; if(m_specOp==SpecOp::HOUND) { m_config.setSpecial_None(); @@ -11192,7 +11090,7 @@ void MainWindow::on_actionJT9_triggered() ui->sbFtol->setValue (m_settings->value ("Ftol_JT9", 50).toInt()); m_nSubMode=m_settings->value("SubMode",0).toInt(); ui->sbSubmode->setValue(m_nSubMode); - QTimer::singleShot (50, [=] { + QTimer::singleShot (50, this, [=] { on_sbTR_valueChanged (ui->sbTR->value()); on_sbSubmode_valueChanged(ui->sbSubmode->value()); }); @@ -11201,10 +11099,7 @@ void MainWindow::on_actionJT9_triggered() m_bFastMode=m_bFast9; WSPR_config(false); switch_mode (Modes::JT9); - m_nsps=6912; - m_FFTSize = m_nsps / 2; - if (m_tci_audio) Q_EMIT m_config.transceiver_blocksize (m_FFTSize); - else Q_EMIT FFTSize (m_FFTSize); + initializeFFT(6912); m_hsymStop=173; if(m_config.decode_at_52s()) m_hsymStop=179; setup_status_bar (bVHF); @@ -11227,15 +11122,13 @@ void MainWindow::on_actionJT9_triggered() m_fastGraph->showNormal(); ui->TxFreqSpinBox->setValue(700); ui->RxFreqSpinBox->setValue(700); - ui->lh_decodes_headings_label->setText(" UTC dB T Freq " + tr ("Message")); - ui->rh_decodes_headings_label->setText(" UTC dB T Freq " + tr ("Message")); + setDecodeHeadings(" UTC dB T Freq " + tr ("Message"), " UTC dB T Freq " + tr ("Message")); } else { // ui->cbAutoSeq->setChecked(false); if (m_mode != "FST4") { m_TRperiod=60.0; - ui->lh_decodes_headings_label->setText("UTC dB DT Freq " + tr ("Message")); - ui->rh_decodes_headings_label->setText("UTC dB DT Freq " + tr ("Message")); + setDecodeHeadings("UTC dB DT Freq " + tr ("Message"), "UTC dB DT Freq " + tr ("Message")); } } m_wideGraph->setPeriod(m_TRperiod,m_nsps); @@ -11243,26 +11136,37 @@ void MainWindow::on_actionJT9_triggered() Q_EMIT m_config.transceiver_period(m_TRperiod); if (!m_tci_audio) { m_modulator->setTRPeriod(m_TRperiod); // TODO - not thread safe - m_detector->setTRPeriod(m_TRperiod); // TODO - not thread safe + m_detector->setTRPeriod(m_TRperiod); // marshals to the audio thread } - ui->lh_decodes_title_label->setText(tr ("Band Activity")); - ui->rh_decodes_title_label->setText(tr ("Rx Frequency")); + setDecodeTitles(tr ("Band Activity"), tr ("Rx Frequency")); if(bVHF) { - // 01234567890123456789012345678901234567 - displayWidgets(nWidgets("11111010110011111001000000010000000000")); + applyModeUiState({ModeUiControl::TxFirst, ModeUiControl::TxFrequency, + ModeUiControl::RxFrequency, ModeUiControl::FrequencyTolerance, + ModeUiControl::Report, ModeUiControl::CqTxFrequency, + ModeUiControl::Fast9, ModeUiControl::AutoSequence, + ModeUiControl::CopyRxToTx, ModeUiControl::CopyTxToRx, + ModeUiControl::HoldTxFrequency, ModeUiControl::Submode, + ModeUiControl::Sync, ModeUiControl::DecodeDepth, + ModeUiControl::Respond}); } else { - displayWidgets(nWidgets("11101000010011100001000000010000100000")); + applyModeUiState({ModeUiControl::TxFirst, ModeUiControl::TxFrequency, + ModeUiControl::RxFrequency, ModeUiControl::Report, + ModeUiControl::AutoSequence, ModeUiControl::CopyRxToTx, + ModeUiControl::CopyTxToRx, ModeUiControl::HoldTxFrequency, + ModeUiControl::DecodeDepth, ModeUiControl::Respond, + ModeUiControl::CqOnly}); } fast_config(m_bFastMode); // ui->cbAutoSeq->setVisible(m_bFast9); - ui->txFirstCheckBox->setEnabled(true); + setTxFirstModeEnabled (true); statusChanged(); } void MainWindow::on_actionJT65_triggered() { - if (m_mode=="MSK144") QTimer::singleShot (75, [=] {on_actionJT65_triggered();}); - QTimer::singleShot (50, [=] { + noteTxModeChange (QStringLiteral ("JT65")); + if (m_mode=="MSK144") QTimer::singleShot (75, this, [=] {on_actionJT65_triggered();}); + QTimer::singleShot (50, this, [=] { ui->TxFreqSpinBox->setValue(m_settings->value("TxFreq_old",1500).toInt()); ui->RxFreqSpinBox->setValue(m_settings->value("RxFreq_old",1500).toInt()); }); @@ -11280,12 +11184,9 @@ void MainWindow::on_actionJT65_triggered() Q_EMIT m_config.transceiver_period(m_TRperiod); if (!m_tci_audio) { m_modulator->setTRPeriod(m_TRperiod); // TODO - not thread safe - m_detector->setTRPeriod(m_TRperiod); // TODO - not thread safe + m_detector->setTRPeriod(m_TRperiod); // marshals to the audio thread } - m_nsps=6912; //For symspec only - m_FFTSize = m_nsps / 2; - if (m_tci_audio) Q_EMIT m_config.transceiver_blocksize (m_FFTSize); - else Q_EMIT FFTSize (m_FFTSize); + initializeFFT(6912); m_hsymStop=174; if(m_config.decode_at_52s()) m_hsymStop=183; m_toneSpacing=0.0; @@ -11305,19 +11206,30 @@ void MainWindow::on_actionJT65_triggered() ui->sbFtol->setValue (m_settings->value ("Ftol_JT65", 50).toInt()); m_nSubMode=m_settings->value("SubMode_JT65",0).toInt(); ui->sbSubmode->setValue(m_settings->value("SubMode_JT65",0).toInt()); - QTimer::singleShot (50, [=] {on_sbSubmode_valueChanged(ui->sbSubmode->value());}); + QTimer::singleShot (50, this, [=] {on_sbSubmode_valueChanged(ui->sbSubmode->value());}); m_bShMsgs=m_settings->value("ShMsgs_JT65",false).toBool(); ui->cbShMsgs->setChecked(m_bShMsgs); } else { ui->sbSubmode->setValue(0); - ui->lh_decodes_title_label->setText(tr ("Band Activity")); - ui->rh_decodes_title_label->setText(tr ("Rx Frequency")); + setDecodeTitles(tr ("Band Activity"), tr ("Rx Frequency")); } if(bVHF) { - // 01234567890123456789012345678901234567 - displayWidgets(nWidgets("11111001010011011010110001010000000000")); + applyModeUiState({ModeUiControl::TxFirst, ModeUiControl::TxFrequency, + ModeUiControl::RxFrequency, ModeUiControl::FrequencyTolerance, + ModeUiControl::Report, ModeUiControl::ShortMessages, + ModeUiControl::AutoSequence, ModeUiControl::CopyRxToTx, + ModeUiControl::CopyTxToRx, ModeUiControl::Submode, + ModeUiControl::Sync, ModeUiControl::ClearAverage, + ModeUiControl::IncludeAveraging, + ModeUiControl::IncludeCorrelation, ModeUiControl::ApJt65, + ModeUiControl::Respond}); } else { - displayWidgets(nWidgets("11101000010011100001000000010000100000")); + applyModeUiState({ModeUiControl::TxFirst, ModeUiControl::TxFrequency, + ModeUiControl::RxFrequency, ModeUiControl::Report, + ModeUiControl::AutoSequence, ModeUiControl::CopyRxToTx, + ModeUiControl::CopyTxToRx, ModeUiControl::HoldTxFrequency, + ModeUiControl::DecodeDepth, ModeUiControl::Respond, + ModeUiControl::CqOnly}); } fast_config(false); // if(ui->cbShMsgs->isChecked()) { @@ -11326,14 +11238,15 @@ void MainWindow::on_actionJT65_triggered() // } if (m_config.decode_at_52s() && m_config.auto_astro() && !ui->actionAstronomical_data->isChecked()) ui->actionAstronomical_data->setChecked (true); - ui->txFirstCheckBox->setEnabled(true); + setTxFirstModeEnabled (true); statusChanged(); } void MainWindow::on_actionQ65_triggered() { - if (m_mode=="MSK144") QTimer::singleShot (75, [=] {on_actionQ65_triggered();}); - QTimer::singleShot (50, [=] { + noteTxModeChange (QStringLiteral ("Q65")); + if (m_mode=="MSK144") QTimer::singleShot (75, this, [=] {on_actionQ65_triggered();}); + QTimer::singleShot (50, this, [=] { ui->TxFreqSpinBox->setValue(m_settings->value("TxFreq_old",1500).toInt()); ui->RxFreqSpinBox->setValue(m_settings->value("RxFreq_old",1500).toInt()); }); @@ -11350,10 +11263,7 @@ void MainWindow::on_actionQ65_triggered() setup_status_bar(true); m_bFastMode=false; m_bFast9=false; - m_nsps=6912; //For symspec only - m_FFTSize = m_nsps / 2; - if (m_tci_audio) Q_EMIT m_config.transceiver_blocksize (m_FFTSize); - else Q_EMIT FFTSize (m_FFTSize); + initializeFFT(6912); m_hsymStop=49; ui->sbTR->values ({15, 30, 60, 120, 300}); // restore last used parameters @@ -11361,7 +11271,7 @@ void MainWindow::on_actionQ65_triggered() ui->sbFtol->setValue (m_settings->value ("Ftol_Q65", 50).toInt()); m_nSubMode=m_settings->value("SubMode_Q65",0).toInt(); ui->sbSubmode->setValue(m_settings->value("SubMode_Q65",0).toInt()); - QTimer::singleShot (50, [=] { + QTimer::singleShot (50, this, [=] { on_sbTR_valueChanged (ui->sbTR->value()); on_sbSubmode_valueChanged(ui->sbSubmode->value()); }); @@ -11375,24 +11285,24 @@ void MainWindow::on_actionQ65_triggered() m_wideGraph->setRxFreq(ui->RxFreqSpinBox->value()); m_wideGraph->setTxFreq(ui->TxFreqSpinBox->value()); switch_mode (Modes::Q65); -// 01234567890123456789012345678901234567 - displayWidgets(nWidgets("11111101011011010011100000010000000011")); - ui->lh_decodes_headings_label->setText("UTC dB DT Freq " + tr ("Message")); - ui->rh_decodes_headings_label->setText("UTC dB DT Freq " + tr ("Message")); + applyModeUiState({ModeUiControl::TxFirst, ModeUiControl::TxFrequency, + ModeUiControl::RxFrequency, ModeUiControl::FrequencyTolerance, + ModeUiControl::Report, ModeUiControl::TrPeriod, + ModeUiControl::ShortMessages, ModeUiControl::AutoSequence, + ModeUiControl::Tx6, ModeUiControl::CopyRxToTx, + ModeUiControl::CopyTxToRx, ModeUiControl::Submode, + ModeUiControl::ClearAverage, ModeUiControl::DecodeDepth, + ModeUiControl::IncludeAveraging, + ModeUiControl::Respond, ModeUiControl::AutoClearAverage, + ModeUiControl::MaxDrift}); + setDecodeHeadings("UTC dB DT Freq " + tr ("Message"), "UTC dB DT Freq " + tr ("Message")); if (m_tci_audio && ui->bandComboBox->currentText()!="OOB") Q_EMIT m_config.transceiver_period(m_TRperiod); m_specOp=m_config.special_op_id(); if(m_specOp!=SpecOp::NONE and m_specOp!=SpecOp::FOX and m_specOp!=SpecOp::HOUND) { - QString t0=""; - if(SpecOp::NA_VHF==m_specOp) t0="NA VHF"; - if(SpecOp::EU_VHF==m_specOp) t0="EU VHF"; - if(SpecOp::FIELD_DAY==m_specOp) t0="Field Day"; - if(SpecOp::RTTY==m_specOp) t0="FT RU"; - if(SpecOp::WW_DIGI==m_specOp) t0="WW Digi"; - if(SpecOp::ARRL_DIGI==m_specOp) t0="ARRL Digi"; - if(SpecOp::Q65_PILEUP==m_specOp) t0="Q65 Pileup"; - if(t0=="") { + QString t0 = specOpLabel(); + if(t0.isEmpty()) { ui->labDXped->setVisible(false); } else { ui->labDXped->setVisible(true); @@ -11408,10 +11318,60 @@ void MainWindow::on_actionQ65_triggered() } if (m_config.decode_at_52s() && m_config.auto_astro() && !ui->actionAstronomical_data->isChecked()) ui->actionAstronomical_data->setChecked (true); - ui->txFirstCheckBox->setEnabled(true); + setTxFirstModeEnabled (true); statusChanged(); } +void MainWindow::on_actionJTTY_triggered() +{ + noteTxModeChange (QStringLiteral ("JTTY")); + on_stopButton_clicked(); + m_mode = "JTTY"; + ui->actionJTTY->setChecked(true); + switch_mode (Modes::JTTY); + WSPR_config(false); + VHF_features_enabled(false); + m_wideGraph->setMode(m_mode); + ui->cbAutoSeq->setChecked(false); + m_bFastMode=false; + m_bFast9=false; + m_nsps=6912; + initializeFFT(m_nsps); + m_FFTSize = m_nsps / 2; + if (m_tci_audio) Q_EMIT m_config.transceiver_blocksize (m_FFTSize); + else Q_EMIT FFTSize (m_FFTSize); + m_TRperiod=180; //We need a nonzero setting for WideGraph plotter to work. + m_hsymStop=620; + m_wideGraph->setPeriod(m_TRperiod,m_nsps); + m_detector->setTRPeriod(m_TRperiod); // marshals to the audio thread + ui->TxFreqSpinBox_2->setValue(1500); + ui->RxFreqSpinBox_2->setValue(1500); +// ui->RxFreqSpinBox_2->setSingleStep(200); + ui->sbFtol_2->values ({2, 5, 10, 20, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500}); + // setValue() above is a no-op (no valueChanged signal) if the spinbox + // already held this value from a prior JTTY session, so set the plotter + // state directly rather than relying on that signal to reach it. + m_wideGraph->setRxFreq(ui->RxFreqSpinBox_2->value()); + m_wideGraph->setTol(ui->sbFtol_2->value()); + setDecodeHeadings("", ""); + updateJttyDecodeHeadings(); + setDecodeTitles(tr ("All Decodes"), tr ("QSO Frequency")); + applyModeUiState({ModeUiControl::TxFirst, ModeUiControl::TxFrequency, + ModeUiControl::RxFrequency, ModeUiControl::FrequencyTolerance, + ModeUiControl::Report, ModeUiControl::TrPeriod, + ModeUiControl::AutoSequence, ModeUiControl::CopyRxToTx, + ModeUiControl::CopyTxToRx, ModeUiControl::HoldTxFrequency, + ModeUiControl::DecodeDepth, ModeUiControl::Respond}); + // JTTY's decoder has no Fast/Deep behavior to select -- force Normal and + // disable the other two rather than offer a choice that does nothing. + ui->actionMediumDecode->setChecked(true); + ui->actionQuickDecode->setEnabled(false); + ui->actionDeepestDecode->setEnabled(false); + setup_status_bar (false); + monitor(true); +} + + void MainWindow::on_actionMSK144_triggered() { m_hsymStop=105; @@ -11434,6 +11394,7 @@ void MainWindow::on_actionMSK144_triggered() "MSK144 not available if Fox, Hound, Field Day, FT Roundup, WW Digi. or ARRL Digi contest is selected."); return; } + noteTxModeChange (QStringLiteral ("MSK144")); m_mode="MSK144"; if(m_specOp==SpecOp::HOUND) { m_config.setSpecial_None(); @@ -11441,10 +11402,7 @@ void MainWindow::on_actionMSK144_triggered() } ui->actionMSK144->setChecked(true); switch_mode (Modes::MSK144); - m_nsps=6; - m_FFTSize = 7 * 512; - if (m_tci_audio) Q_EMIT m_config.transceiver_blocksize (m_FFTSize); - else Q_EMIT FFTSize (m_FFTSize); + initializeFFT(6, 7 * 512); setup_status_bar (true); m_toneSpacing=0.0; WSPR_config(false); @@ -11459,8 +11417,8 @@ void MainWindow::on_actionMSK144_triggered() else if (m_currentBand=="6m" or m_currentBand=="4m") ui->sbTR->setValue (m_msk144_tr6); else ui->sbTR->setValue (m_msk144_tr); } - ui->txFirstCheckBox->setEnabled(true); - QTimer::singleShot (50, [=] {on_sbTR_valueChanged (ui->sbTR->value());}); + setTxFirstModeEnabled (true); + QTimer::singleShot (50, this, [=] {on_sbTR_valueChanged (ui->sbTR->value());}); ui->sbFtol->setValue (m_settings->value ("Ftol_MSK144", 50).toInt()); // restore last used parameter m_bShMsgs=m_settings->value("ShMsgs_MSK144",false).toBool(); ui->cbShMsgs->setChecked(m_bShMsgs); @@ -11471,43 +11429,44 @@ void MainWindow::on_actionMSK144_triggered() ui->RxFreqSpinBox->setMinimum(1400); ui->RxFreqSpinBox->setMaximum(1600); ui->RxFreqSpinBox->setSingleStep(10); - ui->lh_decodes_headings_label->setText(" UTC dB T Freq " + tr ("Message")); - ui->rh_decodes_headings_label->setText(" UTC dB T Freq " + tr ("Message")); + setDecodeHeadings(" UTC dB T Freq " + tr ("Message"), " UTC dB T Freq " + tr ("Message")); if (m_tci_audio && ui->bandComboBox->currentText()!="OOB") Q_EMIT m_config.transceiver_period(m_TRperiod); if (!m_tci_audio) { m_modulator->setTRPeriod(m_TRperiod); // TODO - not thread safe - m_detector->setTRPeriod(m_TRperiod); // TODO - not thread safe + m_detector->setTRPeriod(m_TRperiod); // marshals to the audio thread } m_fastGraph->setTRPeriod(m_TRperiod); - ui->lh_decodes_title_label->setText(tr ("Band Activity")); - ui->rh_decodes_title_label->setText(tr ("Tx Messages")); + setDecodeTitles(tr ("Band Activity"), tr ("Tx Messages")); ui->actionMSK144->setChecked(true); ui->rptSpinBox->setMinimum(-8); ui->rptSpinBox->setMaximum(24); ui->rptSpinBox->setValue(0); ui->rptSpinBox->setSingleStep(1); ui->sbFtol->values ({20, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500}); - // 01234567890123456789012345678901234567 - displayWidgets(nWidgets("10111111010000000001000100011000000000")); + applyModeUiState({ModeUiControl::TxFirst, ModeUiControl::RxFrequency, + ModeUiControl::FrequencyTolerance, ModeUiControl::Report, + ModeUiControl::TrPeriod, ModeUiControl::CqTxFrequency, + ModeUiControl::ShortMessages, ModeUiControl::AutoSequence, + ModeUiControl::DecodeDepth, ModeUiControl::Swl, + ModeUiControl::Respond}); fast_config(m_bFastMode); statusChanged(); - QString t0=""; - if(SpecOp::NA_VHF==m_specOp) t0="NA VHF"; - if(SpecOp::EU_VHF==m_specOp) t0="EU VHF"; - if(t0=="") { + QString t0 = specOpLabel(); + if(t0.isEmpty()) { ui->labDXped->setVisible(false); } else { ui->labDXped->setVisible(true); ui->labDXped->setText(t0); on_contest_log_action_triggered(); } - if(!(programStart or m_freqNominal == 0)) m_msk144basefreq = m_freqNominal; // MSK144 QSY + if(!(programStart or m_operatingFrequency.rx () == 0)) m_msk144basefreq = m_operatingFrequency.rx (); // MSK144 QSY } void MainWindow::on_actionWSPR_triggered() { + noteTxModeChange (QStringLiteral ("WSPR")); m_mode="WSPR"; if(m_specOp==SpecOp::HOUND) { m_config.setSpecial_None(); @@ -11520,12 +11479,9 @@ void MainWindow::on_actionWSPR_triggered() Q_EMIT m_config.transceiver_period(m_TRperiod); if (!m_tci_audio) { m_modulator->setTRPeriod(m_TRperiod); // TODO - not thread safe - m_detector->setTRPeriod(m_TRperiod); // TODO - not thread safe + m_detector->setTRPeriod(m_TRperiod); // marshals to the audio thread } - m_nsps=6912; //For symspec only - m_FFTSize = m_nsps / 2; - if (m_tci_audio) Q_EMIT m_config.transceiver_blocksize (m_FFTSize); - else Q_EMIT FFTSize (m_FFTSize); + initializeFFT(6912); m_hsymStop=396; m_toneSpacing=12000.0/8192.0; setup_status_bar (false); @@ -11538,14 +11494,15 @@ void MainWindow::on_actionWSPR_triggered() m_bFastMode=false; m_bFast9=false; ui->TxFreqSpinBox->setValue(ui->WSPRfreqSpinBox->value()); - // 01234567890123456789012345678901234567 - displayWidgets(nWidgets("00000000000000000101000000000000000000")); + applyModeUiState({ModeUiControl::WsprControls, ModeUiControl::DecodeDepth}); fast_config(false); + enterBeaconMode (); statusChanged(); } void MainWindow::on_actionEcho_triggered() { + noteTxModeChange (QStringLiteral ("Echo")); int nd=int(m_ndepth&3); on_actionJT4_triggered(); // Don't allow decoding depth to be changed just because Echo mode was entered: @@ -11564,12 +11521,9 @@ void MainWindow::on_actionEcho_triggered() Q_EMIT m_config.transceiver_period(m_TRperiod); if (!m_tci_audio) { m_modulator->setTRPeriod(m_TRperiod); // TODO - not thread safe - m_detector->setTRPeriod(m_TRperiod); // TODO - not thread safe + m_detector->setTRPeriod(m_TRperiod); // marshals to the audio thread } - m_nsps=6912; //For symspec only - m_FFTSize = m_nsps / 2; - if (m_tci_audio) Q_EMIT m_config.transceiver_blocksize (m_FFTSize); - else Q_EMIT FFTSize (m_FFTSize); + initializeFFT(6912); m_hsymStop=9; m_toneSpacing=1.0; switch_mode(Modes::Echo); @@ -11584,25 +11538,30 @@ void MainWindow::on_actionEcho_triggered() m_bFastMode=false; m_bFast9=false; WSPR_config(true); - ui->lh_decodes_headings_label->setText(" UTC Hour Level Doppler Width N Q DF SNR dBerr TS EchoMsg"); - // 01234567890123456789012345678901234567 - displayWidgets(nWidgets("00000000000000000010001000000000000000")); + ui->lh_decodes_headings_label->setText(" UTC Hour Level Doppler Width Dgrd N Q DF SNR dBerr TS EchoMsg"); + applyModeUiState({ModeUiControl::ClearAverage, ModeUiControl::EchoGraph}); fast_config(false); ui->sbEchoAvg->values ({1, 2, 5, 10, 20, 50, 100}); statusChanged(); monitor(false); //Don't auto-start Monitor in Echo mode. // Ensure that the correct frequency is set and displayed - QTimer::singleShot (500, [=] { - auto const& row = m_config.frequencies ()->best_working_frequency (m_freqNominal); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); + QTimer::singleShot (500, this, [=] { + auto const& row = m_config.frequencies ()->best_working_frequency (m_operatingFrequency.rx ()); + Frequency frequency; + if (workingFrequencyAt (row, frequency) + && nominalFrequencyChangeAllowed (FrequencyRequestOrigin::Automatic)) + { + ui->bandComboBox->setCurrentIndex (row); + requestBandChange (frequency, FrequencyRequestOrigin::Automatic); + } if (m_monitoring) ui->monitorButton->click(); }); } void MainWindow::on_actionFreqCal_triggered() { + noteTxModeChange (QStringLiteral ("FreqCal")); on_actionJT9_triggered(); m_mode="FreqCal"; if(m_specOp==SpecOp::HOUND) { @@ -11618,12 +11577,9 @@ void MainWindow::on_actionFreqCal_triggered() Q_EMIT m_config.transceiver_period(m_TRperiod); if (!m_tci_audio) { m_modulator->setTRPeriod(m_TRperiod); // TODO - not thread safe - m_detector->setTRPeriod(m_TRperiod); // TODO - not thread safe + m_detector->setTRPeriod(m_TRperiod); // marshals to the audio thread } - m_nsps=6912; //For symspec only - m_FFTSize = m_nsps / 2; - if (m_tci_audio) Q_EMIT m_config.transceiver_blocksize (m_FFTSize); - else Q_EMIT FFTSize (m_FFTSize); + initializeFFT(6912); m_hsymStop=((int(m_TRperiod/0.288))/8)*8; m_frequency_list_fcal_iter = m_config.frequencies ()->begin (); ui->RxFreqSpinBox->setValue(1500); @@ -11631,16 +11587,27 @@ void MainWindow::on_actionFreqCal_triggered() // 18:15:47 0 1 1500 1550.349 0.100 3.5 10.2 ui->lh_decodes_headings_label->setText(" UTC Freq CAL Offset fMeas DF Level S/N"); ui->measure_check_box->setChecked (false); - // 01234567890123456789012345678901234567 - displayWidgets(nWidgets("00110100000000000000000000000100000000")); + applyModeUiState({ModeUiControl::RxFrequency, ModeUiControl::FrequencyTolerance, + ModeUiControl::TrPeriod, ModeUiControl::Measure}); statusChanged(); } void MainWindow::switch_mode (Mode mode) { + clear_generated_message_error (); + if (m_mode != "Q65" || mode != Modes::Q65) { + m_q65PileupCopiedLastRxCall.clear(); + m_q65PileupCopiedCallers.clear(); + } + // Sit just under the decoded-text panes, outside the per-mode + // displayWidgets()/ModeUiControl mechanism -- only meaningful for JTTY. + bool const jtty = m_mode=="JTTY"; + ui->cbLowerCase->setVisible(jtty); + ui->cbIncludeTime->setVisible(jtty); + if (mode != Modes::MSK144) m_msk144basefreq = 0; no_a7_decodes = true; // Don't allow a7 decodes during the first period because they can be leftovers from the previous mode msk144qsy = false; // MSK144 QSY - QTimer::singleShot ((int(1500.0*m_TRperiod)), [=] {no_a7_decodes = false;}); + QTimer::singleShot ((int(1500.0*m_TRperiod)), this, [=] {no_a7_decodes = false;}); if (m_mode != "Q65" && m_specOp==SpecOp::Q65_PILEUP) { m_config.setSpecial_None(); m_specOp=m_config.special_op_id(); @@ -11649,12 +11616,12 @@ void MainWindow::switch_mode (Mode mode) } m_fastGraph->setMode(m_mode); m_config.frequencies ()->filter (m_config.region (), mode, true); // filter on current time - auto const& row = m_config.frequencies ()->best_working_frequency (m_freqNominal); - if (!keep_frequency) { + auto const& row = m_config.frequencies ()->best_working_frequency (m_operatingFrequency.rx ()); + Frequency frequency; + if (!keep_frequency && workingFrequencyAt (row, frequency) + && nominalFrequencyChangeAllowed (FrequencyRequestOrigin::Automatic)) { ui->bandComboBox->setCurrentIndex (row); - if (row >= 0 ) { - on_bandComboBox_activated (row); - } + requestBandChange (frequency, FrequencyRequestOrigin::Automatic); } ui->rptSpinBox->setSingleStep(1); ui->rptSpinBox->setMinimum(-50); @@ -11677,26 +11644,30 @@ void MainWindow::switch_mode (Mode mode) ui->rh_decodes_widget->setVisible (false); // UR disable for AL + widescreen versions ui->lh_decodes_title_label->setVisible(false); } - QTimer::singleShot (500, [=] { + QTimer::singleShot (500, this, [=] { if (!(m_mode=="Echo" or ((m_mode=="Q65" or m_mode=="JT65") && m_config.decode_at_52s())) && ui->actionAstronomical_data->isChecked () && m_config.auto_astro()) ui->actionAstronomical_data->setChecked (false); }); check_button_color(); + ui->autoButton->setEnabled(m_mode != "JTTY"); + ui->autoButton->setVisible(m_mode != "JTTY"); + updateDecodeControls (); } void MainWindow::WSPR_config(bool b) { ui->rh_decodes_widget->setVisible(!b); // UR disable for AL + widescreen version - ui->controls_stack_widget->setCurrentIndex (b && m_mode != "Echo" ? 1 : 0); - if(m_mode=="Echo") ui->controls_stack_widget->setCurrentIndex(2); + ui->controls_stack_widget->setCurrentIndex (b && m_mode != "Echo" ? 2 : 0); + if(m_mode=="Echo") ui->controls_stack_widget->setCurrentIndex(3); + if(m_mode=="JTTY") ui->controls_stack_widget->setCurrentIndex(1); ui->QSO_controls_widget->setVisible (!b); ui->DX_controls_widget->setVisible (!b or (m_mode=="Echo")); - ui->WSPR_controls_widget->setVisible (b); ui->lh_decodes_title_label->setVisible(!b and ui->cbMenus->isChecked()); ui->logQSOButton->setVisible(!b); ui->DecodeButton->setEnabled(!b); bool bFST4W=(m_mode=="FST4W"); - ui->sbTxPercent->setEnabled(!bFST4W or (tr("Random") == ui->RoundRobin->currentText())); + ui->sbTxPercent->setEnabled(!bFST4W + or configuredRoundRobinPolicy ().kind == BeaconTx::RoundRobinPolicy::Kind::Random); ui->band_hopping_group_box->setVisible(true); ui->RoundRobin->setVisible(bFST4W); ui->sbFST4W_RxFreq->setVisible(bFST4W); @@ -11708,7 +11679,8 @@ void MainWindow::WSPR_config(bool b) if(!m_config.miles()) t += " km"; ui->lh_decodes_headings_label->setText(t); if (m_config.is_transceiver_online ()) { - m_config.transceiver_tx_frequency (0); // turn off split + m_config.transceiver_tx_frequency ( + 0, RigFrequencyChangePolicy::ChangeKind::TxPathCorrection); // turn off split } m_bSimplex = true; } else @@ -11722,7 +11694,7 @@ void MainWindow::fast_config(bool b) { m_bFastMode=b; ui->TxFreqSpinBox->setEnabled(!b); - ui->sbTR->setVisible(b); + setTrPeriodVisible(b); if(b and (m_bFast9 or m_mode=="MSK144")) { m_wideGraph->hide(); m_fastGraph->showNormal(); @@ -11732,8 +11704,15 @@ void MainWindow::fast_config(bool b) } } +void MainWindow::setTrPeriodVisible(bool visible) +{ + ui->sbTR->setVisible(visible); + m_trPeriodLabel->setVisible(visible); +} + void MainWindow::on_TxFreqSpinBox_valueChanged(int n) { + ui->TxFreqSpinBox_2->setValue(n); if (m_config.superFox() && m_specOp==SpecOp::FOX && n!=750) { ui->TxFreqSpinBox->setValue(750); m_wideGraph->setTxFreq(750); @@ -11743,8 +11722,7 @@ void MainWindow::on_TxFreqSpinBox_valueChanged(int n) m_wideGraph->setTxFreq(n); // if (ui->cbHoldTxFreq->isChecked ()) ui->RxFreqSpinBox->setValue(n); if(m_mode!="MSK144") { - if (m_tci_audio) Q_EMIT m_config.transceiver_trfrequency(n - m_XIT); - else Q_EMIT transmitFrequency (n - m_XIT); + setXIT (n); } if(m_mode=="Q65") { @@ -11757,27 +11735,16 @@ void MainWindow::on_TxFreqSpinBox_valueChanged(int n) } if (m_mode != "MSK144" && m_mode != "FST4W" && m_mode != "WSPR" && m_mode != "Echo" && m_mode != "FreqCal" && m_specOp!=SpecOp::FOX) { - QTimer::singleShot (200, [=] {m_settings->setValue("TxFreq_old",ui->TxFreqSpinBox->value());}); - } - if(m_specOp==SpecOp::FOX && !m_config.superFox()) QTimer::singleShot (50, [=] {m_TxFreqFox=n;}); - - // UK stations must transmit below 5358 kHz on 60m - if((m_config.my_callsign().startsWith("G") or m_config.my_callsign().startsWith("M") - or m_config.my_callsign().startsWith("2")) && (m_freqNominal + ui->TxFreqSpinBox->value()) > 5357950) { - QString band=m_config.bands()->find(m_freqNominal); - if(band=="60m") { - ui->TxFreqSpinBox->setValue(5357950 - m_freqNominal); - m_wideGraph->setTxFreq(5357950 - m_freqNominal); - QTimer::singleShot (0, [=] { // don't block guiUpdate - MessageBox::information_message (this, tr ("UK stations must transmit below 5358 kHz on 60m.")); - }); - } + QTimer::singleShot (200, this, [=] {m_settings->setValue("TxFreq_old",ui->TxFreqSpinBox->value());}); } + if(m_specOp==SpecOp::FOX && !m_config.superFox()) QTimer::singleShot (50, this, [=] {m_TxFreqFox=n;}); + statusUpdate (); } void MainWindow::on_RxFreqSpinBox_valueChanged(int n) { + ui->RxFreqSpinBox_2->setValue(n); if (m_config.superFox() && m_specOp==SpecOp::HOUND) { if (ui->RxFreqSpinBox->value() < 200) { ui->RxFreqSpinBox->setValue(200); @@ -11790,11 +11757,25 @@ void MainWindow::on_RxFreqSpinBox_valueChanged(int n) } m_wideGraph->setRxFreq(n); if (m_mode == "FreqCal") { - setRig (); + if (m_frequency_list_fcal_iter != m_config.frequencies ()->end ()) + { + if (!requestNominalFrequencyChange ( + m_frequency_list_fcal_iter->frequency_ - n, + FrequencyRequestOrigin::User)) + { + auto const accepted_rx_frequency = static_cast<int> ( + m_frequency_list_fcal_iter->frequency_ - m_operatingFrequency.rx ()); + QSignalBlocker const rx_blocker {ui->RxFreqSpinBox}; + QSignalBlocker const rx_copy_blocker {ui->RxFreqSpinBox_2}; + ui->RxFreqSpinBox->setValue (accepted_rx_frequency); + ui->RxFreqSpinBox_2->setValue (accepted_rx_frequency); + m_wideGraph->setRxFreq (accepted_rx_frequency); + } + } } if (m_mode != "MSK144" && m_mode != "FST4W" && m_mode != "WSPR" && m_mode != "Echo" && m_mode != "FreqCal" && !(SpecOp::HOUND == m_specOp && m_config.superFox())) { - QTimer::singleShot (200, [=] {m_settings->setValue("RxFreq_old",ui->RxFreqSpinBox->value());}); + QTimer::singleShot (200, this, [=] {m_settings->setValue("RxFreq_old",ui->RxFreqSpinBox->value());}); } statusUpdate (); } @@ -11870,8 +11851,8 @@ void MainWindow::on_actionUse_multithreaded_FT8_decoder_triggered(bool checked) { m_multithreadFT8 = checked; dec_data.params.lmultift8 = m_multithreadFT8; - qDebug() << "m_multithreadFT8 is" << m_multithreadFT8; - qDebug() << "dec_data.params.lmultift8 is" << dec_data.params.lmultift8; +// qDebug() << "m_multithreadFT8 is" << m_multithreadFT8; +// qDebug() << "dec_data.params.lmultift8 is" << dec_data.params.lmultift8; if (checked && !(m_specOp==SpecOp::HOUND && m_config.superFox())) { if (m_ft8DecoderStart==0) m_hsymStop=49; else if (m_ft8DecoderStart==1) { @@ -12002,9 +11983,15 @@ void MainWindow::on_actionOpen_log_directory_triggered () void MainWindow::on_bandComboBox_currentIndexChanged (int index) { + if (keep_frequency) + { + restoreNominalFrequencySelection (); + return; + } + auto const& frequencies = m_config.frequencies (); auto const& source_index = frequencies->mapToSource (frequencies->index (index, FrequencyList_v2_101::frequency_column)); - Frequency frequency {m_freqNominal}; + Frequency frequency {m_operatingFrequency.rx ()}; if (source_index.isValid ()) { frequency = frequencies->frequency_list ()[source_index.row ()].frequency_; @@ -12013,7 +12000,6 @@ void MainWindow::on_bandComboBox_currentIndexChanged (int index) // Lookup band auto const& band = m_config.bands ()->find (frequency); ui->bandComboBox->setCurrentText (band.size () ? band : m_config.bands ()->oob ()); - setXIT (ui->TxFreqSpinBox->value ()); displayDialFrequency (); } @@ -12033,28 +12019,138 @@ void MainWindow::on_bandComboBox_activated (int index) { auto const& frequencies = m_config.frequencies (); auto const& source_index = frequencies->mapToSource (frequencies->index (index, FrequencyList_v2_101::frequency_column)); - Frequency frequency {m_freqNominal}; + Frequency frequency {m_operatingFrequency.rx ()}; if (source_index.isValid ()) { frequency = frequencies->frequency_list ()[source_index.row ()].frequency_; } - m_bandEdited = true; - band_changed (frequency); - m_wideGraph->setRxBand (m_config.bands ()->find (frequency)); + if (requestBandChange (frequency, FrequencyRequestOrigin::User)) + { + setXIT (ui->TxFreqSpinBox->value ()); + m_wideGraph->setRxBand (m_config.bands ()->find (frequency)); + } // m_specOp=m_config.special_op_id(); // if (m_specOp==SpecOp::HOUND) auto_tx_mode(false); // only required if RETURN intiates TXing } -void MainWindow::band_changed (Frequency f) +bool MainWindow::requestBandChange (Frequency frequency, FrequencyRequestOrigin origin) +{ + if (!nominalFrequencyChangeAllowed (origin)) + { + restoreNominalFrequencySelection (); + return false; + } + auto const previous_frequency = m_operatingFrequency.rx (); + if (!RigFrequencyChangePolicy::requestWhileMonitoring ( + m_monitoring, + [this] (bool state) {monitor (state);}, + [this, frequency, origin] { + return requestNominalFrequencyChange (frequency, origin); + })) + { + restoreNominalFrequencySelection (); + return false; + } + + m_bandEdited = true; + applyBandChange (frequency, previous_frequency); + return true; +} + +bool MainWindow::workingFrequencyAt (int row, Frequency& frequency) const { + if (row < 0) return false; + + auto const& frequencies = m_config.frequencies (); + auto const source_index = frequencies->mapToSource ( + frequencies->index (row, FrequencyList_v2_101::frequency_column)); + if (!source_index.isValid ()) return false; + + frequency = frequencies->frequency_list ()[source_index.row ()].frequency_; + return true; +} + +bool MainWindow::requestBandButtonFrequency (Frequency lookup_frequency, + Frequency fallback_frequency, + double msk144_tr_period) +{ + if (!nominalFrequencyChangeAllowed (FrequencyRequestOrigin::User)) return false; + + if (m_mode == "MSK144") + { + ui->sbTR->setValue (msk144_tr_period); + programStart = true; + QTimer::singleShot (250, [=] {programStart = false;}); + } + + auto const row = m_config.frequencies ()->best_working_frequency (lookup_frequency); + if (row >= 0) + { + Frequency frequency; + if (!workingFrequencyAt (row, frequency)) return false; + ui->bandComboBox->setCurrentIndex (row); + if (!requestBandChange (frequency, FrequencyRequestOrigin::User)) return false; + setXIT (ui->TxFreqSpinBox->value ()); + m_wideGraph->setRxBand (m_config.bands ()->find (frequency)); + } + else + { + keep_frequency = true; + if (!requestNominalFrequencyChange (fallback_frequency, FrequencyRequestOrigin::User)) + { + keep_frequency = false; + restoreNominalFrequencySelection (); + return false; + } + QTimer::singleShot (250, [=] {keep_frequency = false;}); + setXIT (ui->TxFreqSpinBox->value ()); + } + return true; +} + +bool MainWindow::requestAlternateBandFrequency (Frequency frequency) +{ + if (!nominalFrequencyChangeAllowed (FrequencyRequestOrigin::User)) return false; + + keep_frequency = true; + if (!requestNominalFrequencyChange (frequency, FrequencyRequestOrigin::User)) + { + keep_frequency = false; + restoreNominalFrequencySelection (); + return false; + } + QTimer::singleShot (250, this, [=] {keep_frequency = false;}); + setXIT (ui->TxFreqSpinBox->value ()); + return true; +} + +void MainWindow::restoreNominalFrequencySelection () +{ + m_bandEdited = false; + QSignalBlocker const blocker {ui->bandComboBox}; + auto const band = m_config.bands ()->find (m_operatingFrequency.rx ()); + ui->bandComboBox->setCurrentText (band.size () ? band : m_config.bands ()->oob ()); + displayDialFrequency (); +} + +void MainWindow::band_changed (Frequency frequency) +{ + applyBandChange (frequency, m_operatingFrequency.rx ()); +} + +void MainWindow::applyBandChange (Frequency f, Frequency previous_frequency) +{ + if (f != previous_frequency) cancelPendingFt8Decode ("dial frequency changed"); + m_autoRespondPeriodState.disarm(); msk144qsy = false; // MSK144 QSY // Don't allow a7 decodes during the first period because they can be leftovers from the previous band no_a7_decodes = true; - QTimer::singleShot ((int(1500.0*m_TRperiod)), [=] {no_a7_decodes = false;}); + QTimer::singleShot ((int(1500.0*m_TRperiod)), this, [=] {no_a7_decodes = false;}); // Set the attenuation value if options are checked if (m_config.pwrBandTxMemory() && !m_tune) { - auto const&curBand = ui->bandComboBox->currentText(); + auto curBand = m_config.bands()->find(f); + if (curBand.isEmpty()) curBand = m_config.bands()->oob(); if (m_pwrBandTxMemory.contains(curBand)) { ui->outAttenuation->setValue(m_pwrBandTxMemory[curBand].toInt()); } @@ -12065,9 +12161,9 @@ void MainWindow::band_changed (Frequency f) if (m_bandEdited && !keep_frequency) { if (m_mode!="WSPR" && !ui->pbBandHopping->isChecked() && !ui->DX_Call_Button->isChecked()) { // preserves auto Tx - if (f + m_wideGraph->nStartFreq () > m_freqNominal + ui->TxFreqSpinBox->value () + if (f + m_wideGraph->nStartFreq () > previous_frequency + ui->TxFreqSpinBox->value () || f + m_wideGraph->nStartFreq () + m_wideGraph->fSpan () <= - m_freqNominal + ui->TxFreqSpinBox->value ()) { + previous_frequency + ui->TxFreqSpinBox->value ()) { // qDebug () << "start f:" << m_wideGraph->nStartFreq () << "span:" << m_wideGraph->fSpan () << "DF:" << ui->TxFreqSpinBox->value (); // disable auto Tx if "blind" QSY outside of waterfall ui->stopTxButton->click (); // halt any transmission @@ -12087,16 +12183,11 @@ void MainWindow::band_changed (Frequency f) { m_frequency_list_fcal_iter = m_config.frequencies ()->find (f); } - if(m_tci) { - m_freqNominal = f; - m_freqTxNominal = m_freqNominal; - } - setRig (f); setXIT (ui->TxFreqSpinBox->value ()); m_specOp=m_config.special_op_id(); if (m_specOp==SpecOp::FOX) FoxReset("BandChange"); // when changing bands, don't preserve the Fox queues m_lastloggedcall.clear(); //ft8md - if (m_mode=="MSK144" && !(programStart or m_freqNominal == 0)) m_msk144basefreq = m_freqNominal; // MSK144 QSY + if (m_mode=="MSK144" && !(programStart or m_operatingFrequency.rx () == 0)) m_msk144basefreq = m_operatingFrequency.rx (); // MSK144 QSY } // Erase the decodedTextBrowsers only if the band really changed @@ -12109,26 +12200,13 @@ void MainWindow::band_changed (Frequency f) m_skedFreq=0.000001*f; } if (m_mode=="MSK144" && !programStart) { // restore MSK144 TRperiods by band - QTimer::singleShot (750, [=] { + QTimer::singleShot (750, this, [=] { if (m_currentBand=="2m" && m_msk144_tr2!=ui->sbTR->value()) ui->sbTR->setValue (m_msk144_tr2); else if ((m_currentBand=="6m" or m_currentBand=="4m") && m_msk144_tr6!=ui->sbTR->value()) ui->sbTR->setValue (m_msk144_tr6); else ui->sbTR->setValue (m_msk144_tr); }); } - // UK stations must transmit below 5358 kHz on 60m - if((m_config.my_callsign().startsWith("G") or m_config.my_callsign().startsWith("M") - or m_config.my_callsign().startsWith("2")) && (m_freqNominal + ui->TxFreqSpinBox->value()) > 5357950) { - QString band=m_config.bands()->find(m_freqNominal); - if(band=="60m") { - ui->TxFreqSpinBox->setValue(5357950 - m_freqNominal); - m_wideGraph->setTxFreq(5357950 - m_freqNominal); - QTimer::singleShot (0, [=] { // don't block guiUpdate - MessageBox::information_message (this, tr ("UK stations must transmit below 5358 kHz on 60m.")); - }); - } - } - /* //ft8md qint64 ms = QDateTime::currentMSecsSinceEpoch() % 86400000; @@ -12182,62 +12260,20 @@ void MainWindow::on_rptSpinBox_valueChanged(int n) statusChanged(); } -void MainWindow::on_tuneButton_clicked (bool checked) -{ - ui->pbBandHopping->setChecked(false); // disable band hopping - // prevent tuning on top of a SuperFox message - if (SpecOp::HOUND==m_specOp && m_config.superFox() && !m_tune) { - QDateTime now = QDateTime::currentDateTimeUtc(); - int s = now.time().toString("ss").toInt(); - if ((s >= 0 && s < 15) || (s >= 30 && s < 45)) { - ui->tuneButton->setChecked (false); - m_config.transceiver_tune (false); // reset rig tuning - return; - } - } - m_config.transceiver_tune (false); // reset rig tuning - if (blocked) return; - if (m_auto && !(m_mode=="WSPR" || m_mode=="FST4W")) ui->autoButton->click(); // stop any other transmission - stopWRTimer.stop(); // stop any Wait & Reply timeout - stopWCTimer.stop(); // stop any Wait & Call timeout - if (checked && m_config.tune_watchdog() && !(m_mode=="WSPR" || m_mode=="FST4W")) { - tuneATU_Timer.start (m_config.tune_watchdog_time()*1000); // tune watchdog - } - if (!checked) { - tuneATU_Timer.stop (); // stop tune watchdog when stopping Tune manually - ui->tuneButton->setText("Tune"); - } - static bool lastChecked = false; - if (lastChecked == checked) return; - lastChecked = checked; - if (checked && m_tune==false) { // we're starting tuning so remember Tx and change pwr to Tune value - if (m_config.pwrBandTuneMemory ()) { - auto const& curBand = ui->bandComboBox->currentText(); - m_pwrBandTxMemory[curBand] = ui->outAttenuation->value(); // remember our Tx pwr - m_PwrBandSetOK = false; - if (m_pwrBandTuneMemory.contains(curBand)) { - ui->outAttenuation->setValue(m_pwrBandTuneMemory[curBand].toInt()); // set to Tune pwr - } - m_PwrBandSetOK = true; - } - } - if (m_tune) { - tuneButtonTimer.start(250); - } else { - m_sentFirst73=false; - itone[0]=0; - on_monitorButton_clicked (true); - m_tune=true; - } - if (m_tci_audio) Q_EMIT m_config.transceiver_tune(checked); - else Q_EMIT tune (checked); -} void MainWindow::end_tuning () { tuneATU_Timer.stop (); // stop tune watchdog when stopping Tune manually - on_stopTxButton_clicked (); + if (m_mode == "WSPR" || m_mode == "FST4W") + { + if (m_tune) stop_tuning (); + reset_transmit_controls_after_stop (); + } + else + { + on_stopTxButton_clicked (); + } // we're turning off so remember our Tune pwr setting and reset to Tx pwr if (m_config.pwrBandTuneMemory() || m_config.pwrBandTxMemory()) { auto const& curBand = ui->bandComboBox->currentText(); @@ -12259,42 +12295,13 @@ void MainWindow::stop_tuning () void MainWindow::stopTuneATU() { + noteTxStopReason (TxEvidence::TxStopReason::Watchdog); tuneATU_Timer.stop (); // stop tune watchdog when stopping Tune manually on_tuneButton_clicked(false); m_bTxTime=false; ui->tuneButton->setText("Tune"); } -void MainWindow::on_stopTxButton_clicked() // Stop Tx -{ - ui->pbBandHopping->setChecked(false); // disable band hopping - if (m_tune) stop_tuning (); - if (m_auto and !m_tuneup) auto_tx_mode (false); - m_btxok=false; - m_bCallingCQ = false; - m_bAutoReply = false; // ready for next - m_maxPoints=-1; - if (ui->DX_Call_Button->isChecked()) ui->DX_Call_Button->click (); - stopWRTimer.stop(); // Stop any Wait & Reply timeout - stopWCTimer.stop(); // Stop any Wait & Call timeout - tuneATU_Timer.stop (); // stop tune watchdog when stopping Tune manually - no_wait_and_call = false; - m_specOp=m_config.special_op_id(); - if (ui->respondComboBox->isVisible() && ui->respondComboBox->currentText() != "CQ: None") { - Dpoints=0; // reset points - maxDPoints=0; // reset points - dBpoints=-28; // reset points - dBpoints2=99; // reset points - maxdBPoints=-28; // reset points - mindBPoints=99; // reset points - } - pounce = false; - ui->autoButton->setChecked(false); // ensure auoButton is unchecked - filtered = false; - ignored = false; - m_muted = false; - check_button_color(); -} void MainWindow::rigOpen () { @@ -12305,33 +12312,14 @@ void MainWindow::rigOpen () m_config.sync_transceiver (true, true); } -void MainWindow::on_pbR2T_clicked() -{ - ui->TxFreqSpinBox->setValue(ui->RxFreqSpinBox->value ()); -} - -void MainWindow::on_pbT2R_clicked() -{ - if (ui->RxFreqSpinBox->isEnabled ()) - { - ui->RxFreqSpinBox->setValue (ui->TxFreqSpinBox->value ()); - } -} -void MainWindow::on_readFreq_clicked() -{ - if (m_transmitting) return; - if (m_config.transceiver_online ()) - { - m_config.sync_transceiver (true, true); - } -} void MainWindow::setXIT(int n, Frequency base) { - if (m_transmitting && !m_config.tx_QSY_allowed ()) return; + auto const kind = RigFrequencyChangePolicy::ChangeKind::TxPathCorrection; + if (!rigFrequencyChangeDecision (kind).allowed) return; // If "CQ nnn ..." feature is active, set the proper Tx frequency if(m_config.split_mode () && ui->cbCQTx->isEnabled () && ui->cbCQTx->isVisible () && ui->cbCQTx->isChecked()) @@ -12339,17 +12327,19 @@ void MainWindow::setXIT(int n, Frequency base) if (6 == m_ntx || (7 == m_ntx && m_gen_message_is_cq)) { // All conditions are met, use calling frequency - base = m_freqNominal / 1000000 * 1000000 + 1000 * ui->sbCQTxFreq->value () + m_XIT; + base = m_operatingFrequency.rx () / 1000000 * 1000000 + 1000 * ui->sbCQTxFreq->value () + m_XIT; } - } - if (!base) base = m_freqNominal; - m_XIT = 0; + } + if (!base) base = m_operatingFrequency.rx (); + FrequencyDelta requested_xit = 0; + Frequency requested_tx_nominal = base; + bool update_tx_nominal = false; if (!(m_bSimplex || (SpecOp::FOX==m_specOp && m_config.superFox()))) { // m_bSimplex is false, so we can use split mode if requested if (m_config.split_mode () && (!m_config.enable_VHF_features () || m_mode=="FT4" || m_mode == "FT8" || m_mode=="FST4")) { // Don't use XIT for VHF & up - m_XIT=(n/500)*500 - 1500; + requested_xit=(n/500)*500 - 1500; } if ((m_monitoring || m_transmitting) @@ -12358,9 +12348,10 @@ void MainWindow::setXIT(int n, Frequency base) { // All conditions are met, reset the transceiver Tx dial // frequency - m_freqTxNominal = base + m_XIT; - if (m_astroWidget) m_astroWidget->nominal_frequency (m_freqNominal, m_freqTxNominal); - m_config.transceiver_tx_frequency (m_freqTxNominal + m_astroCorrection.tx); + requested_tx_nominal = base + requested_xit; + if (!m_config.transceiver_tx_frequency ( + requested_tx_nominal + m_astroCorrection.tx, kind)) return; + update_tx_nominal = true; } } if (SpecOp::FOX==m_specOp && m_config.superFox() @@ -12369,11 +12360,22 @@ void MainWindow::setXIT(int n, Frequency base) { // the transceiver Tx dial frequency must be consistent with // zero m_XIT for SuperFox - m_freqTxNominal = base; - if (m_astroWidget) m_astroWidget->nominal_frequency (m_freqNominal, m_freqTxNominal); - m_config.transceiver_tx_frequency (m_freqTxNominal + m_astroCorrection.tx); + requested_tx_nominal = base; + if (!m_config.transceiver_tx_frequency ( + requested_tx_nominal + m_astroCorrection.tx, kind)) return; + update_tx_nominal = true; } + m_XIT = requested_xit; + if (update_tx_nominal) + { + m_operatingFrequency.commitAcceptedTx (requested_tx_nominal); + if (m_astroWidget) + { + m_astroWidget->nominal_frequency (m_operatingFrequency.rx (), m_operatingFrequency.tx ()); + } + } + //Now set the audio Tx freq if (m_tci_audio) Q_EMIT m_config.transceiver_trfrequency(ui->TxFreqSpinBox->value () - m_XIT); else Q_EMIT transmitFrequency (ui->TxFreqSpinBox->value () - m_XIT); @@ -12383,8 +12385,12 @@ void MainWindow::setFreq4(int rxFreq, int txFreq) { if (m_mode=="Q65" && ui->actionDisable_clicks_on_waterfall->isVisible() && ui->actionDisable_clicks_on_waterfall->isChecked() && !(Qt::AltModifier & QApplication::keyboardModifiers ())) return; - if (m_mode=="ECHO") return; // we do not adjust rx/tx for echo mode -- always 1500Hz - if (ui->RxFreqSpinBox->isEnabled () && !(SpecOp::HOUND==m_specOp && m_config.superFox() && + if (m_mode == Modes::name(Modes::Echo)) return; // Echo uses a fixed 1500 Hz audio frequency. + bool const vhf_dial_adjustment = !ui->TxFreqSpinBox->isEnabled () + && m_config.enable_VHF_features () + && (Qt::ControlModifier & QApplication::keyboardModifiers ()); + if (!vhf_dial_adjustment && ui->RxFreqSpinBox->isEnabled () + && !(SpecOp::HOUND==m_specOp && m_config.superFox() && (rxFreq < 700 or rxFreq > 800))) ui->RxFreqSpinBox->setValue(rxFreq); if(m_mode=="WSPR" or m_mode=="FST4W") { ui->WSPRfreqSpinBox->setValue(txFreq); @@ -12398,31 +12404,61 @@ void MainWindow::setFreq4(int rxFreq, int txFreq) if (m_transmitting) m_restart = true; } } - else if (m_config.enable_VHF_features () - && (Qt::ControlModifier & QApplication::keyboardModifiers ())) { + else if (vhf_dial_adjustment) { // for VHF & up we adjust Tx dial frequency to equalize Tx to Rx // when user CTRL+clicks on waterfall auto temp = ui->TxFreqSpinBox->value (); - ui->RxFreqSpinBox->setValue (temp); - setRig (m_freqNominal + txFreq - temp); - setXIT (ui->TxFreqSpinBox->value ()); + if (requestNominalFrequencyChange ( + m_operatingFrequency.rx () + txFreq - temp, FrequencyRequestOrigin::User)) + { + ui->RxFreqSpinBox->setValue (temp); + setXIT (ui->TxFreqSpinBox->value ()); + } } } } +void MainWindow::applyOperatingFrequencyTransition (OperatingFrequency::Transition const& transition) +{ + if (transition.before.rx != transition.after.rx) + { + cancelPendingFt8Decode ("dial frequency changed"); + genCQMsg (); + } + if (m_lastDialFreq != transition.after.rx && transition.after.rx + && (m_mode != "MSK144" + || !(ui->cbCQTx->isEnabled () && ui->cbCQTx->isVisible () && ui->cbCQTx->isChecked ()))) + { + if (m_ActiveStationsWidget) + { + m_recentCall.clear (); + if (m_mode != "Q65") m_ActiveStationsWidget->erase (); + } + m_lastDialFreq = transition.after.rx; + m_secBandChanged = QDateTime::currentMSecsSinceEpoch () / 1000; + statusChanged (); + m_wideGraph->setDialFreq (transition.after.rx / 1.e6); + } + if (m_astroWidget) + m_astroWidget->nominal_frequency (transition.after.rx, transition.after.tx); + displayDialFrequency (); +} + void MainWindow::handle_transceiver_update (Transceiver::TransceiverState const& s) { + if (!m_startup_rig_reported) + { + m_startup_rig_reported = true; + PerformanceTrace::milestone ( + m_startup_trace_run, "rig.first_update", + QString {"online=%1"}.arg (s.online () ? "true" : "false")); + } Transceiver::TransceiverState old_state {m_rigState}; //transmitDisplay (s.ptt ()); if (s.ptt () // && !m_rigState.ptt () ) { // safe to start audio // (caveat - DX Lab Suite Commander) - if (m_tx_when_ready && g_iptt) { // waiting to Tx and still needed - int ms_delay=1000*m_config.txDelay(); - if(m_mode=="FT4") ms_delay=20; - ptt1Timer.start(ms_delay); //Start-of-transmission sequencer delay - m_tx_when_ready = false; - } + startTxAudioAfterPttDelay (); } // Display PWR and SWR @@ -12441,7 +12477,7 @@ void MainWindow::handle_transceiver_update (Transceiver::TransceiverState const& ui->outAttenuation->setMinimumWidth (2.8*pointSize + 16); } } else { - ui->label->setText("Pwr"); + ui->label->setText(tr ("Pwr")); } if (m_rigState.swr() != s.swr()) { static bool s_alreadyShowingSWRAlert = false; @@ -12473,69 +12509,78 @@ void MainWindow::handle_transceiver_update (Transceiver::TransceiverState const& } m_rigState = s; - auto old_freqNominal = m_freqNominal; - if (!old_freqNominal) + auto const transition = m_operatingFrequency.reconcile ( + {old_state.online (), old_state.ptt (), m_splitMode, old_state.frequency (), old_state.tx_frequency ()}, + {s.online (), s.ptt (), s.split (), s.frequency (), s.tx_frequency ()}, + operatingFrequencyContext (), [this] (Frequency corrected) { + return dispatchNominalFrequency (corrected, FrequencyRequestOrigin::User, true); + }); + m_splitMode = s.split (); + applyOperatingFrequencyTransition (transition); + if (transition.monitor) { - // always take initial rig frequency to avoid start up problems - // with bogus Tx frequencies - m_freqNominal = s.frequency (); + applyMonitorEffects (*transition.monitor, transition.restorationAccepted); } - if (old_state.online () == false && s.online () == true) + else if (!old_state.online () && s.online ()) { - // initializing - on_monitorButton_clicked (!(m_config.monitor_off_at_startup() or m_mode=="Echo")); + ui->monitorButton->setChecked (false); } - if (s.frequency () != old_state.frequency () || s.split () != m_splitMode) + if (s.online () && s.frequency () && !s.ptt () + && s.frequency () != old_state.frequency () && !transition.restorationAccepted) { - m_splitMode = s.split (); - if (!s.ptt ()) - { - m_freqNominal = s.frequency () - m_astroCorrection.rx; - if (old_freqNominal != m_freqNominal) - { - m_freqTxNominal = m_freqNominal; - genCQMsg (); - } - - if (m_monitoring) - { - m_lastMonitoredFrequency = m_freqNominal; - } - if (m_lastDialFreq != m_freqNominal && - (m_mode != "MSK144" - || !(ui->cbCQTx->isEnabled () && ui->cbCQTx->isVisible () && ui->cbCQTx->isChecked()))) { - - if (m_lastDialFreq != m_freqNominal and m_ActiveStationsWidget != NULL) { - m_recentCall.clear(); - if(m_mode!="Q65") m_ActiveStationsWidget->erase(); - } - - m_lastDialFreq = m_freqNominal; - m_secBandChanged=QDateTime::currentMSecsSinceEpoch()/1000; -// pskSetLocal (); // better be done after a band change - statusChanged(); - m_wideGraph->setDialFreq(m_freqNominal / 1.e6); - } - } else { - m_freqTxNominal = s.split () ? s.tx_frequency () - m_astroCorrection.tx : s.frequency (); - } - if (m_astroWidget) m_astroWidget->nominal_frequency (m_freqNominal, m_freqTxNominal); - } + setXIT (ui->TxFreqSpinBox->value ()); + } // ensure frequency display is correct - if (m_astroWidget && old_state.ptt () != s.ptt ()) setRig (); + if (m_astroWidget && old_state.ptt () != s.ptt ()) + { + reapplyCurrentRigFrequencyCorrection (); + } - displayDialFrequency (); update_dynamic_property (ui->readFreq, "state", "ok"); ui->readFreq->setEnabled (false); ui->readFreq->setText (s.split () ? "S" : ""); } +void MainWindow::handle_transceiver_closing (bool failed) +{ + if (m_tci_audio) + { + m_receiveConsumer.invalidate (); + m_receiveQueue.clear (); + } + if (m_closing || m_mode != "JTTY" || !m_jttyTxActive + || !m_jttyTxUsesTciAudio) + { + return; + } + + noteTxStopReason (failed ? TxEvidence::TxStopReason::Error + : TxEvidence::TxStopReason::UserHalt); + stopTx (); +} + void MainWindow::handle_transceiver_failure (QString const& reason) { + noteTxStopReason (TxEvidence::TxStopReason::Error); + m_beaconTxController.setAutoEnabled (false); + if (m_beaconTxController.txLifecycle () == BeaconTx::TxLifecycle::Decided + || m_beaconTxController.txLifecycle () == BeaconTx::TxLifecycle::StartRequested) + { + m_tx_when_ready = false; + ptt1Timer.stop (); + processBeaconActions (m_beaconTxController.transmitWindowEnded ()); + } + if (m_beaconTxController.tuneKind () != BeaconTx::TuneKind::None) + { + processBeaconActions (m_beaconTxController.tuneCompleted ( + m_beaconTxController.tunePlanId ())); + } update_dynamic_property (ui->readFreq, "state", "error"); ui->readFreq->setEnabled (true); - on_stopTxButton_clicked (); - qDebug() << "MainWindow::handle_transceiver_failure fired"; + // tune carrier isn't gated by m_btxok, so stop it explicitly; messages self-stop via guiUpdate + if (m_tune) Q_EMIT tune (false); + m_auto = false; + reset_transmit_controls_after_stop (); rigFailure (reason); rigFailed = true; } @@ -12590,28 +12635,77 @@ void MainWindow::rigFailure (QString const& reason) } } +void MainWindow::dispatchTxRequest (TxEvidence::TxRequest const& request) +{ + bool const useTciAudio = request.mode == QStringLiteral ("JTTY") + ? m_jttyTxUsesTciAudio : m_tci_audio; + if (useTciAudio) + { + if (!request.tuning && rigTuneTimer.isActive ()) + { + rigTuneTimer.stop (); + m_config.transceiver_tune (false); + ui->tuneButton->setChecked (false); + ui->tuneButton->setText ("Tune"); + } + Q_EMIT m_config.transceiver_modulator_start (request); + } + else if (request.mode == QStringLiteral ("JTTY") && !request.tuning) + { + Q_EMIT startJttyStream (request, m_soundOutput); + } + else + { + auto localRequest = request; + // The local modulator historically receives an integer period; TCI retains the full value. + localRequest.tr_period_s = static_cast<int> (localRequest.tr_period_s); + Q_EMIT sendMessage (localRequest, m_soundOutput); + } +} + void MainWindow::transmit (double snr) { + qint64 const jttyCommittedSamples = jttyTxCommittedSamples (); + beginTxEvidenceGeneration (m_mode == "JTTY" && jttyCommittedSamples > 0 + ? jttyCommittedSamples - 1 : -1, + false); + auto const txSessionId = m_txEvidenceSourceSession; + auto const txGeneration = m_txEvidenceGeneration; + TxEvidence::TxRequest request; + request.mode = m_mode; + request.channel = m_config.audio_output_channel (); + request.snr_db = snr; + request.tr_period_s = m_TRperiod; + request.session_id = txSessionId; + request.generation = txGeneration; + request.queue_epoch = m_jttyTxQueueEpoch; + request.tuning = m_tune; + int const cwSymbols = qBound (0, int (icw[0]), NUM_CW_SYMBOLS - 1); + request.cw_id.reserve (cwSymbols); + for (int i = 1; i <= cwSymbols; ++i) request.cw_id.append (int (icw[i])); +#if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) + request.start_window_open_ms = m_liveAudioTestFt8StartWindowOpenMs; + request.start_window_close_ms = m_liveAudioTestFt8StartWindowCloseMs; + if (request.start_window_open_ms >= 0) + { + m_liveAudioTestFt8StartSessionId = txSessionId.value (); + m_liveAudioTestFt8StartGeneration = txGeneration.value (); + } +#endif double toneSpacing=0.0; if (m_mode == "JT65") { if(m_nSubMode==0) toneSpacing=11025.0/4096.0; if(m_nSubMode==1) toneSpacing=2*11025.0/4096.0; if(m_nSubMode==2) toneSpacing=4*11025.0/4096.0; - if (m_tci_audio) { - Q_EMIT m_config.transceiver_modulator_start(m_mode, NUM_JT65_SYMBOLS, - 4096.0*12000.0/11025.0, ui->TxFreqSpinBox->value () - m_XIT, - toneSpacing,true,false,snr,m_TRperiod); - } else { - Q_EMIT sendMessage (m_mode, NUM_JT65_SYMBOLS, - 4096.0*12000.0/11025.0, ui->TxFreqSpinBox->value () - m_XIT, - toneSpacing, m_soundOutput, m_config.audio_output_channel (), - true, false, snr, m_TRperiod); - } + request.symbols_length = NUM_JT65_SYMBOLS; + request.frames_per_symbol = 4096.0*12000.0/11025.0; + request.frequency_hz = ui->TxFreqSpinBox->value () - m_XIT; + request.tone_spacing = toneSpacing; + dispatchTxRequest (request); } if((m_mode=="FT4" or m_mode=="FT8") and m_maxPoints>0 and SpecOp::ARRL_DIGI==m_specOp) { - ui->dxCallEntry->setText(m_deCall); - ui->dxGridEntry->setText(m_deGrid); + setDXInfo(m_deCall, m_deGrid); genStdMsgs("-10"); } @@ -12622,43 +12716,38 @@ void MainWindow::transmit (double snr) if(m_config.x4ToneSpacing()) toneSpacing=4*12000.0/1920.0; if(SpecOp::FOX==m_specOp and !m_tune) toneSpacing=-1; if(SpecOp::FOX==m_specOp and m_config.superFox()) { - if (m_tci_audio) { - Q_EMIT m_config.transceiver_modulator_start(m_mode, NUM_SUPERFOX_SYMBOLS, - 1024.0,ui->TxFreqSpinBox->value()-m_XIT, - toneSpacing,true,false,snr,m_TRperiod); - } else { - Q_EMIT sendMessage (m_mode, NUM_SUPERFOX_SYMBOLS, - 1024.0, ui->TxFreqSpinBox->value () - m_XIT, - toneSpacing, m_soundOutput, m_config.audio_output_channel (), - true, false, snr, m_TRperiod); - } + request.symbols_length = NUM_SUPERFOX_SYMBOLS; + request.frames_per_symbol = 1024.0; } else { - if (m_tci_audio) { - Q_EMIT m_config.transceiver_modulator_start(m_mode, NUM_FT8_SYMBOLS, - 1920.0,ui->TxFreqSpinBox->value()-m_XIT, - toneSpacing,true,false,snr,m_TRperiod); - } else { - Q_EMIT sendMessage (m_mode, NUM_FT8_SYMBOLS, - 1920.0, ui->TxFreqSpinBox->value () - m_XIT, - toneSpacing, m_soundOutput, m_config.audio_output_channel (), - true, false, snr, m_TRperiod); - } + request.symbols_length = NUM_FT8_SYMBOLS; + request.frames_per_symbol = 1920.0; } + request.frequency_hz = ui->TxFreqSpinBox->value () - m_XIT; + request.tone_spacing = toneSpacing; + dispatchTxRequest (request); } if (m_mode == "FT4") { m_dateTimeSentTx3=QDateTime::currentDateTimeUtc(); toneSpacing=-2.0; //Transmit a pre-computed, filtered waveform. - if (m_tci_audio) { - Q_EMIT m_config.transceiver_modulator_start(m_mode, NUM_FT4_SYMBOLS, - 576.0,ui->TxFreqSpinBox->value()-m_XIT, - toneSpacing,true,false,snr,m_TRperiod); - } else { - Q_EMIT sendMessage (m_mode, NUM_FT4_SYMBOLS, - 576.0, ui->TxFreqSpinBox->value() - m_XIT, - toneSpacing, m_soundOutput, m_config.audio_output_channel(), - true, false, snr, m_TRperiod); - } + request.symbols_length = NUM_FT4_SYMBOLS; + request.frames_per_symbol = 576.0; + request.frequency_hz = ui->TxFreqSpinBox->value() - m_XIT; + request.tone_spacing = toneSpacing; + dispatchTxRequest (request); + } + + if (m_mode == "JTTY") { + m_dateTimeSentTx3=QDateTime::currentDateTimeUtc(); + toneSpacing=-2.0; //Transmit a pre-computed, filtered waveform. + double txt=m_nsym_jtty*384.0/12000.0; + request.symbols_length = m_nsym_jtty; + request.frames_per_symbol = 384.0; + request.frequency_hz = 1500.0; + request.tone_spacing = toneSpacing; + request.synchronize = false; + request.tr_period_s = txt; + dispatchTxRequest (request); } if (m_mode == "FST4" or m_mode == "FST4W") { @@ -12678,14 +12767,11 @@ void MainWindow::transmit (double snr) double f0=ui->WSPRfreqSpinBox->value() - m_XIT; if(m_mode=="FST4") f0=ui->TxFreqSpinBox->value() - m_XIT; if(!m_tune) f0 += 1.5*dfreq; - if (m_tci_audio) { - Q_EMIT m_config.transceiver_modulator_start(m_mode, NUM_FST4_SYMBOLS,double(nsps),f0,toneSpacing, - true,false,snr,m_TRperiod); - } else { - Q_EMIT sendMessage (m_mode, NUM_FST4_SYMBOLS,double(nsps),f0,toneSpacing, - m_soundOutput,m_config.audio_output_channel(), - true, false, snr, m_TRperiod); - } + request.symbols_length = NUM_FST4_SYMBOLS; + request.frames_per_symbol = double(nsps); + request.frequency_hz = f0; + request.tone_spacing = toneSpacing; + dispatchTxRequest (request); } if (m_mode == "Q65") { @@ -12697,16 +12783,11 @@ void MainWindow::transmit (double snr) int mode65=pow(2.0,double(m_nSubMode)); toneSpacing=mode65*12000.0/nsps; // toneSpacing=-4.0; - if (m_tci_audio) { - Q_EMIT m_config.transceiver_modulator_start(m_mode, NUM_Q65_SYMBOLS, - double(nsps),ui->TxFreqSpinBox->value()-m_XIT, - toneSpacing,true,false,snr,m_TRperiod); - } else { - Q_EMIT sendMessage (m_mode, NUM_Q65_SYMBOLS, - double(nsps), ui->TxFreqSpinBox->value () - m_XIT, - toneSpacing, m_soundOutput, m_config.audio_output_channel (), - true, false, snr, m_TRperiod); - } + request.symbols_length = NUM_Q65_SYMBOLS; + request.frames_per_symbol = double(nsps); + request.frequency_hz = ui->TxFreqSpinBox->value () - m_XIT; + request.tone_spacing = toneSpacing; + dispatchTxRequest (request); } if (m_mode == "JT9") { @@ -12722,16 +12803,12 @@ void MainWindow::transmit (double snr) sps=nsps[m_nSubMode-4]; m_toneSpacing=12000.0/sps; } - if (m_tci_audio) { - Q_EMIT m_config.transceiver_modulator_start(m_mode, NUM_JT9_SYMBOLS,sps, - ui->TxFreqSpinBox->value()-m_XIT, - m_toneSpacing,true,fastmode,snr,m_TRperiod); - } else { - Q_EMIT sendMessage (m_mode, NUM_JT9_SYMBOLS, sps, - ui->TxFreqSpinBox->value() - m_XIT, m_toneSpacing, - m_soundOutput, m_config.audio_output_channel (), - true, fastmode, snr, m_TRperiod); - } + request.symbols_length = NUM_JT9_SYMBOLS; + request.frames_per_symbol = sps; + request.frequency_hz = ui->TxFreqSpinBox->value() - m_XIT; + request.tone_spacing = m_toneSpacing; + request.fast_mode = fastmode; + dispatchTxRequest (request); } if (m_mode == "MSK144") { @@ -12748,14 +12825,12 @@ void MainWindow::transmit (double snr) int nsym; nsym=NUM_MSK144_SYMBOLS; if(itone[40] < 0) nsym=40; - if (m_tci_audio) { - Q_EMIT m_config.transceiver_modulator_start(m_mode, nsym,double(m_nsps),f0, m_toneSpacing, - true,true,snr,m_TRperiod); - } else { - Q_EMIT sendMessage (m_mode, nsym, double(m_nsps), f0, m_toneSpacing, - m_soundOutput, m_config.audio_output_channel (), - true, true, snr, m_TRperiod); - } + request.symbols_length = nsym; + request.frames_per_symbol = double(m_nsps); + request.frequency_hz = f0; + request.tone_spacing = m_toneSpacing; + request.fast_mode = true; + dispatchTxRequest (request); } if (m_mode == "JT4") { @@ -12766,34 +12841,22 @@ void MainWindow::transmit (double snr) if(m_nSubMode==4) toneSpacing=18*4.375; if(m_nSubMode==5) toneSpacing=36*4.375; if(m_nSubMode==6) toneSpacing=72*4.375; - if (m_tci_audio) { - Q_EMIT m_config.transceiver_modulator_start(m_mode, NUM_JT4_SYMBOLS, - 2520.0*12000.0/11025.0,ui->TxFreqSpinBox->value()-m_XIT, - toneSpacing,true,false,snr,m_TRperiod); - } else { - Q_EMIT sendMessage (m_mode, NUM_JT4_SYMBOLS, - 2520.0*12000.0/11025.0, ui->TxFreqSpinBox->value () - m_XIT, - toneSpacing, m_soundOutput, m_config.audio_output_channel (), - true, false, snr, m_TRperiod); - } + request.symbols_length = NUM_JT4_SYMBOLS; + request.frames_per_symbol = 2520.0*12000.0/11025.0; + request.frequency_hz = ui->TxFreqSpinBox->value () - m_XIT; + request.tone_spacing = toneSpacing; + dispatchTxRequest (request); } if (m_mode=="WSPR") { int nToneSpacing=1; if(m_config.x2ToneSpacing()) nToneSpacing=2; if(m_config.x4ToneSpacing()) nToneSpacing=4; - if (m_tci_audio) { - Q_EMIT m_config.transceiver_modulator_start(m_mode, NUM_WSPR_SYMBOLS,8192.0, - ui->TxFreqSpinBox->value() - 1.5 * 12000 / 8192, - m_toneSpacing*nToneSpacing,true,false,snr, - m_TRperiod); - } else { - Q_EMIT sendMessage (m_mode, NUM_WSPR_SYMBOLS, 8192.0, - ui->TxFreqSpinBox->value() - 1.5 * 12000 / 8192, - m_toneSpacing*nToneSpacing, m_soundOutput, - m_config.audio_output_channel(),true, false, snr, - m_TRperiod); - } + request.symbols_length = NUM_WSPR_SYMBOLS; + request.frames_per_symbol = 8192.0; + request.frequency_hz = ui->TxFreqSpinBox->value() - 1.5 * 12000 / 8192; + request.tone_spacing = m_toneSpacing*nToneSpacing; + dispatchTxRequest (request); } if(m_mode=="Echo") { @@ -12814,9 +12877,8 @@ void MainWindow::transmit (double snr) if(ui->rbEchoCW->isChecked()) { freq=1500.0; int ifreq=freq; - int n=ui->leEchoMessage->text().length(); - gen_cw_wave_(const_cast<char *> (ui->leEchoMessage->text().toLatin1().constData()), &ifreq, - foxcom_.wave, (FCL)n); + auto const message = ui->leEchoMessage->text().toLatin1(); + gen_cw_wave_(message.constData(), &ifreq, foxcom_.wave, (FCL)message.size()); } else { toneSpacing=ui->sbToneSpacing->value(); int nsps4=4*framesPerSymbol; //48000 Hz sampling @@ -12832,13 +12894,12 @@ void MainWindow::transmit (double snr) } m_msEchoTxStart=QDateTime::currentMSecsSinceEpoch(); - if (m_tci_audio) { - Q_EMIT m_config.transceiver_modulator_start(m_mode,numEchoSymbols,framesPerSymbol,freq,toneSpacing, - false,false,snr,m_TRperiod); - } else { - Q_EMIT sendMessage (m_mode,numEchoSymbols,framesPerSymbol,freq,toneSpacing,m_soundOutput, - m_config.audio_output_channel(), false, false, snr, m_TRperiod); - } + request.symbols_length = numEchoSymbols; + request.frames_per_symbol = framesPerSymbol; + request.frequency_hz = freq; + request.tone_spacing = toneSpacing; + request.synchronize = false; + dispatchTxRequest (request); } // In auto-sequencing mode, stop after 5 transmissions of "73" message. @@ -12856,13 +12917,13 @@ void MainWindow::transmit (double snr) void MainWindow::on_outAttenuation_valueChanged (int a) { QString tt_str; - qreal dBAttn {a / 10.}; // slider interpreted as dB / 100 + qreal dBAttn {a / 10.}; if (m_tune && m_config.pwrBandTuneMemory()) { - tt_str = tr ("Tune digital gain "); + tt_str = tr ("Tune drive "); } else { - tt_str = tr ("Transmit digital gain "); + tt_str = tr ("Transmit drive "); } - tt_str += (a ? QString::number (-dBAttn, 'f', 1) : "0") + "dB"; + tt_str += (a ? QString::number (-dBAttn, 'f', 1) : "0.0") + " dB"; if (ui->outAttenuation->hasFocus() && !m_block_pwr_tooltip) { QToolTip::showText (QCursor::pos (), tt_str, ui->outAttenuation); } @@ -12875,43 +12936,24 @@ void MainWindow::on_outAttenuation_valueChanged (int a) } // Updating attenuation for tuning is done in stop_tuning if (m_tci_audio) { - Q_EMIT m_config.transceiver_txvolume(dBAttn); + sync_tci_tx_volume (); } else { Q_EMIT outAttenuationChanged (dBAttn); } } +void MainWindow::sync_tci_tx_volume (bool force) +{ + if (m_tci_audio) { + Q_EMIT m_config.transceiver_txvolume (ui->outAttenuation->value () / 10., force); + } +} + void MainWindow::on_actionShort_list_of_add_on_prefixes_and_suffixes_triggered() { if (!m_prefixes) { m_prefixes.reset (new HelpTextWindow {tr ("Prefixes") - , R"(Type 1 Prefixes: - - 1A 1S 3A 3B6 3B8 3B9 3C 3C0 3D2 3D2C 3D2R 3DA 3V 3W 3X - 3Y 3YB 3YP 4J 4L 4S 4U1I 4U1U 4W 4X 5A 5B 5H 5N 5R - 5T 5U 5V 5W 5X 5Z 6W 6Y 7O 7P 7Q 7X 8P 8Q 8R - 9A 9G 9H 9J 9K 9L 9M2 9M6 9N 9Q 9U 9V 9X 9Y A2 - A3 A4 A5 A6 A7 A9 AP BS7 BV BV9 BY C2 C3 C5 C6 - C9 CE CE0X CE0Y CE0Z CE9 CM CN CP CT CT3 CU CX CY0 CY9 - D2 D4 D6 DL DU E3 E4 EA EA6 EA8 EA9 EI EK EL EP - ER ES ET EU EX EY EZ F FG FH FJ FK FKC FM FO - FOA FOC FOM FP FR FRG FRJ FRT FT5W FT5X FT5Z FW FY M MD - MI MJ MM MU MW H4 H40 HA HB HB0 HC HC8 HH HI HK - HK0A HK0M HL HM HP HR HS HV HZ I IS IS0 J2 J3 J5 - J6 J7 J8 JA JDM JDO JT JW JX JY K KG4 KH0 KH1 KH2 - KH3 KH4 KH5 KH5K KH6 KH7 KH8 KH9 KL KP1 KP2 KP4 KP5 LA LU - LX LY LZ OA OD OE OH OH0 OJ0 OK OM ON OX OY OZ - P2 P4 PA PJ2 PJ7 PY PY0F PT0S PY0T PZ R1F R1M S0 S2 S5 - S7 S9 SM SP ST SU SV SVA SV5 SV9 T2 T30 T31 T32 T33 - T5 T7 T8 T9 TA TF TG TI TI9 TJ TK TL TN TR TT - TU TY TZ UA UA2 UA9 UK UN UR V2 V3 V4 V5 V6 V7 - V8 VE VK VK0H VK0M VK9C VK9L VK9M VK9N VK9W VK9X VP2E VP2M VP2V VP5 - VP6 VP6D VP8 VP8G VP8H VP8O VP8S VP9 VQ9 VR VU VU4 VU7 XE XF4 - XT XU XW XX9 XZ YA YB YI YJ YK YL YN YO YS YU - YV YV0 Z2 Z3 ZA ZB ZC4 ZD7 ZD8 ZD9 ZF ZK1N ZK1S ZK2 ZK3 - ZL ZL7 ZL8 ZL9 ZP ZS ZS8 KC4 E5 - -Type 1 Suffixes: /0 /1 /2 /3 /4 /5 /6 /7 /8 /9 /A /P)", {"Courier", 10}}); + , Radio::HelpText::prefixes(), {"Courier", 10}}); } m_prefixes->showNormal(); m_prefixes->raise (); @@ -12962,11 +13004,11 @@ void MainWindow::transmitDisplay (bool transmitting) ui->signal_meter_widget->setValue(0,0); if (m_monitoring && !ui->actionFull_Duplex_Mode->isChecked()) monitor (false); m_txing=true; - QTimer::singleShot ((int(1000.0*m_TRperiod)), [=] {m_txing=false;}); + QTimer::singleShot ((int(1000.0*m_TRperiod)), this, [=] {m_txing=false;}); m_btxok=true; } - auto QSY_allowed = !transmitting or m_config.tx_QSY_allowed () or + auto QSY_allowed = !transmitting or m_config.tx_frequency_corrections_allowed () or !m_config.split_mode (); if (ui->cbHoldTxFreq->isChecked ()) { ui->TxFreqSpinBox->setEnabled (QSY_allowed); @@ -12984,7 +13026,7 @@ void MainWindow::transmitDisplay (bool transmitting) } // the following are always disallowed in transmit - ui->menuMode->setEnabled (!transmitting); + ui->menuMode->setEnabled (!transmitting && !m_modeLocked); } } @@ -12997,7 +13039,7 @@ void MainWindow::on_sbFtol_valueChanged(int value) m_wideGraph->setTol (value); statusUpdate (); // save last used parameters - QTimer::singleShot (200, [=] { + QTimer::singleShot (200, this, [=] { if (m_mode=="FT8") m_settings->setValue ("Ftol_SF", ui->sbFtol->value()); if (m_mode=="Q65") m_settings->setValue ("Ftol_Q65", ui->sbFtol->value()); if (m_mode=="MSK144") m_settings->setValue ("Ftol_MSK144", ui->sbFtol->value()); @@ -13066,7 +13108,7 @@ void MainWindow::on_sbTR_valueChanged(int value) Q_EMIT m_config.transceiver_period(m_TRperiod); if (!m_tci_audio) { m_modulator->setTRPeriod(m_TRperiod); // TODO - not thread safe - m_detector->setTRPeriod(m_TRperiod); // TODO - not thread safe + m_detector->setTRPeriod(m_TRperiod); // marshals to the audio thread } m_wideGraph->setPeriod (value, m_nsps); progressBar.setMaximum (value); @@ -13076,7 +13118,7 @@ void MainWindow::on_sbTR_valueChanged(int value) on_sbSubmode_valueChanged(ui->sbSubmode->value()); statusUpdate (); check_button_color(); - if (!programStart) QTimer::singleShot (1000, [=] { + if (!programStart) QTimer::singleShot (1000, this, [=] { if (m_mode=="Q65") m_settings->setValue ("TRPeriod_Q65", ui->sbTR->value ()); if (m_mode=="MSK144") { if (m_currentBand=="2m") { @@ -13098,6 +13140,18 @@ void MainWindow::on_sbTR_valueChanged(int value) void MainWindow::on_sbTR_FST4W_valueChanged(int value) { on_sbTR_valueChanged(value); + if (m_mode == "FST4W") + { + if (m_beaconTxController.active ()) + { + processBeaconActions (m_beaconTxController.setPeriod ( + qRound64 (1000.0 * m_TRperiod))); + } + else + { + enterBeaconMode (); + } + } } QChar MainWindow::current_submode () const @@ -13136,12 +13190,12 @@ void MainWindow::on_sbSubmode_valueChanged(int n) ui->cbFast9->setChecked(false); on_cbFast9_clicked(false); ui->cbFast9->setEnabled(false); - ui->sbTR->setVisible(false); + setTrPeriodVisible(false); m_TRperiod=60.0; } else { if(!blocked) ui->cbFast9->setEnabled(true); } - ui->sbTR->setVisible(m_bFast9); + setTrPeriodVisible(m_bFast9); if(m_bFast9) ui->TxFreqSpinBox->setValue(700); } if(m_transmitting and m_bFast9 and m_nSubMode>=4) transmit (99.0); @@ -13149,7 +13203,7 @@ void MainWindow::on_sbSubmode_valueChanged(int n) statusUpdate (); check_button_color(); // save last used parameters - QTimer::singleShot (200, [=] { + QTimer::singleShot (200, this, [=] { if (m_mode=="Q65") m_settings->setValue("SubMode_Q65",ui->sbSubmode->value()); if (m_mode=="JT65") m_settings->setValue("SubMode_JT65",ui->sbSubmode->value()); if (m_mode=="JT4") m_settings->setValue("SubMode_JT4",ui->sbSubmode->value()); @@ -13157,29 +13211,6 @@ void MainWindow::on_sbSubmode_valueChanged(int n) }); } -void MainWindow::on_cbFast9_clicked(bool b) -{ - if(m_mode=="JT9") { - m_bFast9=b; -// ui->cbAutoSeq->setVisible(b); - blocked=true; // needed to prevent a loop - on_actionJT9_triggered(); - QTimer::singleShot (50, [=] {blocked = false;}); // needed to prevent a loop - QTimer::singleShot (200, [=] { - if(m_mode=="JT9") m_settings->setValue("JT9_Fast",m_bFast9); - }); - } - - if(b) { - m_TRperiod = ui->sbTR->value (); - } else { - m_TRperiod=60.0; - } - progressBar.setMaximum(int(m_TRperiod)); - m_wideGraph->setPeriod(m_TRperiod,m_nsps); - fast_config(b); - statusChanged (); -} void MainWindow::on_cbSendMsg_toggled(bool b) { @@ -13211,7 +13242,7 @@ void MainWindow::on_cbShMsgs_toggled(bool b) if(ntx==4) ui->txrb4->setChecked(true); if(ntx==5) ui->txrb5->setChecked(true); if(ntx==6) ui->txrb6->setChecked(true); - QTimer::singleShot (200, [=] { + QTimer::singleShot (200, this, [=] { if(m_mode=="MSK144") m_settings->setValue("ShMsgs_MSK144",m_bShMsgs); if(m_mode=="Q65") m_settings->setValue("ShMsgs_Q65",m_bShMsgs); if(m_mode=="JT65") m_settings->setValue("ShMsgs_JT65",m_bShMsgs); @@ -13257,67 +13288,37 @@ void MainWindow::replyToCQ (QTime time, qint32 snr, float delta_time, quint32 de , QString const& mode, QString const& message_text , bool /*low_confidence*/, quint8 modifiers) { - QString format_string {"%1 %2 %3 %4 %5 %6"}; auto const& time_string = time.toString ("~" == mode || "&" == mode || "+" == mode || (m_TRperiod < 60. && ("`" == mode || ":" == mode)) ? "hhmmss" : "hhmm"); - auto text = message_text; - auto ap_pos = text.lastIndexOf (QRegularExpression {R"((?:\?\s)?(?:a[0-9]|q[0-9][0-9]?)$)"}); - if (ap_pos >= 0) - { - // beware of decodes ending on shorter version of wanted call so - // add a space - text = text.left (ap_pos).trimmed () + ' '; - } - auto message_line = format_string + auto message_line = QString {"%1 %2 %3 %4 %5 %6"} .arg (time_string) .arg (snr, 3) .arg (delta_time, 4, 'f', 1) .arg (delta_frequency, 4) .arg (mode, -2) - .arg (text); - QTextCursor start {ui->decodedTextBrowser->document ()}; - start.movePosition (QTextCursor::End); - auto cursor = ui->decodedTextBrowser->document ()->find (message_line, start, QTextDocument::FindBackward); - if (cursor.isNull ()) - { - // try again with with -0.0 delta time - cursor = ui->decodedTextBrowser->document ()->find (format_string - .arg (time_string) - .arg (snr, 3) - .arg ('-' + QString::number (delta_time, 'f', 1), 4) - .arg (delta_frequency, 4) - .arg (mode, -2) - .arg (text), start, QTextDocument::FindBackward); - } - if (!cursor.isNull ()) + .arg (message_text); + if (m_config.udpWindowToFront ()) { - if (m_config.udpWindowToFront ()) - { - show (); - raise (); - activateWindow (); - } - if (m_config.udpWindowRestore () && isMinimized ()) - { - showNormal (); - raise (); - } - if ((text.contains (QRegularExpression {R"(^(CQ |CQDX |QRZ ))"})) - || text.contains("73 ") || (ui->cbHoldTxFreq->isChecked ())) { - // a message we are willing to accept and auto reply to - m_bDoubleClicked = true; - } - DecodedText message {message_line}; - Qt::KeyboardModifiers kbmod {modifiers << 24}; - processMessage (message, kbmod); - tx_watchdog (false); - QApplication::alert (this); + show (); + raise (); + activateWindow (); } - else + if (m_config.udpWindowRestore () && isMinimized ()) { - qDebug () << "process reply message ignored, decode not found:" << message_line; + showNormal (); + raise (); } + if ((message_text.contains (reply_cq_or_qrz_regexp)) + || message_text.contains("73 ") || (ui->cbHoldTxFreq->isChecked ())) { + // a message we are willing to accept and auto reply to + m_bDoubleClicked = true; + } + DecodedText message {message_line}; + Qt::KeyboardModifiers kbmod {modifiers << 24}; + processMessage (message, kbmod, DecodedMessageReaction::SelectionOrigin::Udp); + tx_watchdog (false); + QApplication::alert (this); } void MainWindow::locationChange (QString const& location) @@ -13336,7 +13337,7 @@ void MainWindow::locationChange (QString const& location) } } if (MaidenheadLocatorValidator::Acceptable == MaidenheadLocatorValidator ().validate (grid, len)) { - qDebug() << "locationChange: Grid supplied is " << grid; +// qDebug() << "locationChange: Grid supplied is " << grid; if (m_config.my_grid () != grid) { m_config.set_location (grid); genStdMsgs (m_rpt, false); @@ -13353,6 +13354,11 @@ void MainWindow::replayDecodes () // we accept this request even if the setting to accept UDP requests // is not checked + if (!m_messageClient->begin_replay ()) + { + return; + } + // attempt to parse the decoded text for (QTextBlock block = ui->decodedTextBrowser->document ()->firstBlock (); block.isValid (); block = block.next ()) { @@ -13371,6 +13377,7 @@ void MainWindow::replayDecodes () } } statusChanged (); + m_messageClient->end_replay (); } void MainWindow::postDecode (bool is_new, QString const& message) @@ -13463,8 +13470,7 @@ void MainWindow::p1ReadFromStdout() //p1readFromStdout } m_RxLog=0; m_startAnother=m_loopall; - m_decoderBusy = false; - statusUpdate (); + endDecode (DecodeOwner::Wsprd); } else { int n=t.length(); t=t.mid(0,n-2) + " "; @@ -13600,18 +13606,13 @@ void MainWindow::uploadWSPRSpots (bool direct_post, QString const& decode_text) { // do not spot if disabled, replays, or if rig control not working if(!m_uploadWSPRSpots || m_diskData || !m_config.is_transceiver_online ()) return; - if(m_uploading && !decode_text.size ()) { - qDebug() << "Previous upload has not completed, spots were lost"; - wsprNet->abortOutstandingRequests (); - m_uploading = false; - } QString rfreq = QString("%1").arg((m_dialFreqRxWSPR + 1500) / 1e6, 0, 'f', 6); QString tfreq = QString("%1").arg((m_dialFreqRxWSPR + ui->TxFreqSpinBox->value()) / 1e6, 0, 'f', 6); auto pct = QString::number (ui->autoButton->isChecked () ? ui->sbTxPercent->value () : 0); if (direct_post) { - // queues one FST4W spot + // Queue an FST4W spot, or flush queued FST4W spots after the decode cycle. wsprNet->post (m_config.my_callsign (), m_config.my_grid (), rfreq, tfreq, m_mode, m_TRperiod, pct, QString::number (m_dBm), version (), decode_text); @@ -13624,21 +13625,11 @@ void MainWindow::uploadWSPRSpots (bool direct_post, QString const& decode_text) QString::number (m_dBm), version (), m_config.writeable_data_dir ().absoluteFilePath ("wspr_spots.txt")); } - // trigger upload of any queued spots - if (!decode_text.size ()) - { - m_uploading = true; - } } void MainWindow::uploadResponse(QString const& response) { - if (response == "done") { - m_uploading=false; - } else { - if (response.startsWith ("Upload Failed")) { - m_uploading=false; - } + if (response != "done") { qDebug () << "WSPRnet.org status:" << response; } } @@ -13671,89 +13662,125 @@ void MainWindow::on_sbFST4W_FTol_valueChanged(int n) statusUpdate (); } -void MainWindow::on_pbTxNext_clicked(bool b) + +BeaconTx::RoundRobinPolicy MainWindow::beaconRoundRobinPolicy () const { - if (b && !ui->autoButton->isChecked ()) - { - ui->autoButton->click (); // make sure Tx is possible - } + if (m_mode != "FST4W") return BeaconTx::RoundRobinPolicy::random (); + return configuredRoundRobinPolicy (); } -void MainWindow::WSPR_scheduling () +BeaconTx::RoundRobinPolicy MainWindow::configuredRoundRobinPolicy () const { - if (ui->pbTxNext->isEnabled () && ui->pbTxNext->isChecked ()) - { - // Tx Next button overrides all scheduling - m_WSPR_tx_next = true; - return; - } - QString t=ui->RoundRobin->currentText(); - if(m_mode=="FST4W" and t != tr ("Random")) { - bool ok; - int i=t.left (1).toInt (&ok) - 1; - if (!ok) return; - int n=t.right (1).toInt (&ok); - if (!ok || 0 == n) return; - - qint64 ms = QDateTime::currentMSecsSinceEpoch() % 86400000; - int nsec=ms/1000; - int ntr=m_TRperiod; - int j=((nsec+ntr-1) % (n*ntr))/ntr; - m_WSPR_tx_next = i == j; - return; - } - m_WSPR_tx_next = false; - if (!ui->sbTxPercent->isEnabled ()) + return RoundRobinSelection::policy (*ui->RoundRobin); +} + +void MainWindow::enterBeaconMode () +{ + processBeaconActions (m_beaconTxController.enterMode ( + qRound64 (1000.0 * m_TRperiod), beaconRoundRobinPolicy ())); + m_beaconTxController.setAutoEnabled (m_auto, false); + processBeaconActions (m_beaconTxController.setTxNext ( + ui->pbTxNext->isEnabled () && ui->pbTxNext->isChecked ())); +} + +BeaconTx::ScheduleProposal MainWindow::beaconScheduleProposal () +{ + auto const bandHopping = m_config.is_transceiver_online () + && !m_config.is_dummy_rig () && ui->band_hopping_group_box->isChecked (); + if (bandHopping) { - return; // don't schedule if %age disabled - } - if (m_config.is_transceiver_online () // need working rig control for hopping - && !m_config.is_dummy_rig () - && ui->band_hopping_group_box->isChecked ()) { - auto hop_data = m_WSPR_band_hopping.next_hop (m_auto); - qDebug () << "hop data: period:" << hop_data.period_name_ - << "frequencies index:" << hop_data.frequencies_index_ - << "tune:" << hop_data.tune_required_ - << "tx:" << hop_data.tx_next_; - m_WSPR_tx_next = hop_data.tx_next_; - if (hop_data.frequencies_index_ >= 0) { // new band - ui->bandComboBox->setCurrentIndex (hop_data.frequencies_index_); - on_bandComboBox_activated (hop_data.frequencies_index_); - // Execute user's hardware controller - auto band = m_config.bands ()->find (m_freqNominal).remove ('m'); + BeaconTx::ScheduleProposal proposal; + auto const hop = m_WSPR_band_hopping.next_hop (m_auto); + proposal.disposition = hop.tx_next_ + ? BeaconTx::Disposition::Transmit : BeaconTx::Disposition::Receive; + proposal.source = BeaconTx::PlanSource::BandHop; + proposal.hasHoppingProposal = true; + proposal.hopping.frequenciesIndex = hop.frequencies_index_; + proposal.hopping.tuneRequired = hop.tune_required_; + proposal.hopping.periodName = hop.period_name_.toStdString (); + return proposal; + } + BeaconTx::ScheduleProposal proposal; + proposal.disposition = m_WSPR_band_hopping.next_is_tx (m_mode=="FST4W") + ? BeaconTx::Disposition::Transmit : BeaconTx::Disposition::Receive; + proposal.source = BeaconTx::PlanSource::Percentage; + return proposal; +} + +bool MainWindow::applyBeaconBandChange (BeaconTx::HoppingProposal const& proposal) +{ + band_hopping_label.setText (QString::fromStdString (proposal.periodName)); + if (proposal.frequenciesIndex < 0) return true; + if (!nominalFrequencyChangeAllowed (FrequencyRequestOrigin::Automatic)) return false; + + Frequency frequency; + if (!workingFrequencyAt (proposal.frequenciesIndex, frequency)) return false; + ui->bandComboBox->setCurrentIndex (proposal.frequenciesIndex); + if (!requestBandChange (frequency, FrequencyRequestOrigin::Automatic)) return false; + + setXIT (ui->TxFreqSpinBox->value ()); + m_wideGraph->setRxBand (m_config.bands ()->find (frequency)); + auto band = m_config.bands ()->find (m_operatingFrequency.rx ()).remove ('m'); #if defined(Q_OS_WIN) - // On windows we use CMD.EXE to find and execute the - // user_hardware executable. This means that the first matching - // file extension on the PATHEXT environment variable found on - // the PATH environment variable path list. This give maximum - // flexibility for users to write user_hardware in their - // language of choice, and place the file anywhere on the PATH - // environment variable. Equivalent to typing user_hardware - // without any path or extension at the CMD.EXE prompt. - p3.start("CMD", QStringList {"/C", "user_hardware", band}); + p3.start("CMD", QStringList {"/C", "user_hardware", band}); #else - // On non-Windows systems we expect the user_hardware executable - // to be anywhere in the paths specified in the PATH environment - // variable path list, and executable. Equivalent to typing - // user_hardware without any path at the shell prompt. - p3.start("/bin/sh", QStringList {"-c", "user_hardware " + band}); + p3.start("/bin/sh", QStringList {"-c", "user_hardware \"$1\"", "sh", band}); #endif + return true; +} - // Produce a short tuneup signal - m_tuneup = false; - if (hop_data.tune_required_) { - m_tuneup = true; - on_tuneButton_clicked (true); - tuneATU_Timer.start (2500); - } +// Applies controller intents at the UI/rig boundary. Follow-up actions are +// appended so each external result re-enters the controller before another +// effect is applied. +void MainWindow::processBeaconActions (BeaconTx::Controller::Actions actions) +{ + for (std::size_t index = 0; index < actions.size (); ++index) + { + auto const action = actions[index]; + BeaconTx::Controller::Actions followup; + switch (action.kind) + { + case BeaconTx::ActionKind::SetTransmitWindow: + m_bTxTime = action.enabled; + break; + case BeaconTx::ActionKind::RequestScheduleProposal: + followup = m_beaconTxController.proposalDelivered ( + action.planId, beaconScheduleProposal ()); + break; + case BeaconTx::ActionKind::ApplyBandChange: + followup = m_beaconTxController.bandChangeOutcome ( + action.planId, applyBeaconBandChange (action.hopping)); + break; + case BeaconTx::ActionKind::StartAutomaticTune: + followup = m_beaconTxController.tuneStarted ( + BeaconTx::TuneKind::Automatic, action.planId); + if (m_beaconTxController.tuneKind () == BeaconTx::TuneKind::Automatic + && m_beaconTxController.tunePlanId () == action.planId) + { + on_tuneButton_clicked (true); + tuneATU_Timer.start (2500); + } + break; + case BeaconTx::ActionKind::RestoreAuto: + { + QSignalBlocker const blocker {ui->autoButton}; + ui->autoButton->setChecked (true); + m_auto = true; + } + break; + case BeaconTx::ActionKind::ClearTxNextUi: + { + QSignalBlocker const blocker {ui->pbTxNext}; + ui->pbTxNext->setChecked (false); + } + break; + case BeaconTx::ActionKind::RecordBeaconTransmission: + WSPR_history (m_operatingFrequency.rx (), -1); + m_wideGraph->setWSPRtransmitted (); + break; + } + actions.insert (actions.end (), followup.begin (), followup.end ()); } - - // Display grayline status - band_hopping_label.setText (hop_data.period_name_); - } - else { - m_WSPR_tx_next = m_WSPR_band_hopping.next_is_tx(m_mode=="FST4W"); - } } void MainWindow::astroUpdate () @@ -13762,18 +13789,18 @@ void MainWindow::astroUpdate () // no Doppler correction while CTRL pressed allows manual tuning if (Qt::ControlModifier & QApplication::queryKeyboardModifiers ()) return; if (m_tci && (ui->bandComboBox->currentText()=="OOB")) { - qDebug() << "TCI Mode and OOB so MainWindow::setRig returning at top\n"; + qDebug() << "TCI Mode and OOB so rig-frequency correction is skipped\n"; return; } auto correction = m_astroWidget->astroUpdate(QDateTime::currentDateTimeUtc (), - m_config.my_grid(), m_hisGrid,m_freqNominal,"Echo" == m_mode, - m_transmitting,m_auto,!m_config.tx_QSY_allowed (),m_TRperiod); + m_config.my_grid(), m_hisGrid,m_operatingFrequency.rx (),"Echo" == m_mode, + m_transmitting,m_auto,!m_config.tx_frequency_corrections_allowed (),m_TRperiod); m_fDop=correction.dop; m_fSpread=correction.width; m_tEcho=correction.techo; - if (m_transmitting && !m_config.tx_QSY_allowed ()) return; // No Tx Doppler correction if rig can't do it + if (m_transmitting && !m_config.tx_frequency_corrections_allowed ()) return; // No Tx Doppler correction if rig can't do it if (!m_astroWidget->doppler_tracking() or m_astroWidget->DopplerMethod()==0) { // We are not using RF Doppler correction m_fAudioShift=m_fDop; @@ -13784,7 +13811,7 @@ void MainWindow::astroUpdate () } if ((m_monitoring || m_transmitting) - && m_freqNominal >= 21000000 // No Doppler correction below 15m + && m_operatingFrequency.rx () >= 21000000 // No Doppler correction below 15m && m_config.split_mode ()) // Doppler correcion needs split mode { // adjust for rig resolution @@ -13823,30 +13850,96 @@ void MainWindow::astroUpdate () } else { m_astroCorrection = {}; } - if(!(m_tci && inSettings)) setRig (); + if(!(m_tci && inSettings)) reapplyCurrentRigFrequencyCorrection (); m_fAudioShift=m_fDop - correction.rx; } } -void MainWindow::setRig (Frequency f) +RigFrequencyChangePolicy::Activity MainWindow::rigFrequencyActivity () const { - if (f) { - m_freqNominal = f; - genCQMsg (); - m_freqTxNominal = m_freqNominal; - if (m_astroWidget) m_astroWidget->nominal_frequency (m_freqNominal, m_freqTxNominal); - } - if (m_mode == "FreqCal" && m_frequency_list_fcal_iter != m_config.frequencies ()->end ()) { - m_freqNominal = m_frequency_list_fcal_iter->frequency_ - ui->RxFreqSpinBox->value (); - } - if (m_transmitting && !m_config.tx_QSY_allowed ()) return; + return { + g_iptt == 1, + m_tx_when_ready, + m_transmitting, + m_tune, + m_jttyTxActive, + ptt1Timer.isActive (), + ptt0Timer.isActive (), + m_rigState.ptt (), + m_rigState.tune () + }; +} + +RigFrequencyChangePolicy::Decision MainWindow::rigFrequencyChangeDecision ( + RigFrequencyChangePolicy::ChangeKind kind) const +{ + return RigFrequencyChangePolicy::evaluate ( + kind, rigFrequencyActivity (), m_config.tx_frequency_corrections_allowed ()); +} + +bool MainWindow::nominalFrequencyChangeAllowed (FrequencyRequestOrigin origin) +{ + auto const decision = rigFrequencyChangeDecision ( + RigFrequencyChangePolicy::ChangeKind::NominalQsy); + if (!decision.allowed && origin == FrequencyRequestOrigin::User) + { + statusBar ()->showMessage ( + tr ("Stop transmitting or tuning before changing the dial frequency."), 5000); + } + return decision.allowed; +} + +OperatingFrequency::Context MainWindow::operatingFrequencyContext () const +{ + return {m_monitoring, !m_transmitting && !m_wav_load_coordinator.isLoading (), + !m_config.monitor_off_at_startup (), m_config.monitor_last_used (), m_mode == "Echo", + m_astroCorrection.rx, m_astroCorrection.tx}; +} + +bool MainWindow::dispatchNominalFrequency (Frequency corrected, + FrequencyRequestOrigin origin, + bool monitoring) +{ + if (!nominalFrequencyChangeAllowed (origin)) return false; + auto const accepted = !((monitoring || m_transmitting) && m_config.transceiver_online ()) + || m_config.transceiver_frequency ( + corrected, RigFrequencyChangePolicy::ChangeKind::NominalQsy); + if (!accepted && origin == FrequencyRequestOrigin::User) + { + statusBar ()->showMessage ( + tr ("Stop transmitting or tuning before changing the dial frequency."), 5000); + } + return accepted; +} + +bool MainWindow::requestNominalFrequencyChange (Frequency frequency, + FrequencyRequestOrigin origin) +{ + if (!m_operatingFrequency.requestNominal (frequency, m_astroCorrection.rx, + [this, origin] (Frequency corrected) { + return dispatchNominalFrequency (corrected, origin, m_monitoring); + })) return false; + + genCQMsg (); + if (m_astroWidget) + { + m_astroWidget->nominal_frequency (m_operatingFrequency.rx (), m_operatingFrequency.tx ()); + } + return true; +} + +bool MainWindow::reapplyCurrentRigFrequencyCorrection () +{ + auto const kind = RigFrequencyChangePolicy::ChangeKind::TxPathCorrection; + if (!rigFrequencyChangeDecision (kind).allowed) return false; if ((m_monitoring || m_transmitting) && m_config.transceiver_online ()) { if (m_transmitting && m_config.split_mode () && !(m_config.superFox() && m_specOp==SpecOp::FOX)) { - m_config.transceiver_tx_frequency (m_freqTxNominal + m_astroCorrection.tx); + return m_config.transceiver_tx_frequency (m_operatingFrequency.correctedTx (m_astroCorrection.tx), kind); } else { - m_config.transceiver_frequency (m_freqNominal + m_astroCorrection.rx); + return m_config.transceiver_frequency (m_operatingFrequency.correctedRx (m_astroCorrection.rx), kind); } } + return true; } void MainWindow::fastPick(int x0, int x1, int y) @@ -13854,7 +13947,7 @@ void MainWindow::fastPick(int x0, int x1, int y) float pixPerSecond=12000.0/512.0; if(m_TRperiod<30.0) pixPerSecond=12000.0/256.0; if(m_mode!="MSK144") return; - if(!m_decoderBusy) { + if(!decoderBusy ()) { dec_data.params.newdat=0; dec_data.params.nagain=1; m_nPick=1; @@ -13870,6 +13963,52 @@ void MainWindow::on_actionMeasure_reference_spectrum_triggered() { if(!m_monitoring) on_monitorButton_clicked (true); m_bRefSpec=true; + m_refSpecSecondsRemaining=ReferenceSpectrumMeasureSeconds; + statusBar()->showMessage(tr("Measuring reference spectrum: %1 s remaining") + .arg(m_refSpecSecondsRemaining)); + m_refSpecTimer.start(); +} + +void MainWindow::finishReferenceSpectrumMeasurement(bool notify) +{ + if(!m_bRefSpec) return; + + m_refSpecTimer.stop(); + m_refSpecSecondsRemaining=0; + bool const refspec_available { + QFile::exists(m_config.writeable_data_dir ().absoluteFilePath ("refspec.dat"))}; + m_wideGraph->setReferenceSpectrumAvailable(refspec_available); + m_bRefSpec=false; + + QString const message { + refspec_available + ? (notify + ? tr("Reference spectrum measurement stopped; Ref Spec is available") + : tr("Reference spectrum saved; Ref Spec is available")) + : tr("Reference spectrum measurement stopped; no reference spectrum is available")}; + statusBar()->showMessage(message, 5000); + + if(notify) { + MessageBox::information_message (this, message); + } +} + +void MainWindow::updateReferenceSpectrumCountdown() +{ + if(!m_bRefSpec) { + m_refSpecTimer.stop(); + m_refSpecSecondsRemaining=0; + return; + } + + --m_refSpecSecondsRemaining; + if(m_refSpecSecondsRemaining <= 0) { + finishReferenceSpectrumMeasurement(false); + return; + } + + statusBar()->showMessage(tr("Measuring reference spectrum: %1 s remaining") + .arg(m_refSpecSecondsRemaining)); } void MainWindow::on_actionMeasure_phase_response_triggered() @@ -13885,19 +14024,32 @@ void MainWindow::on_actionMeasure_phase_response_triggered() void MainWindow::on_actionErase_reference_spectrum_triggered() { + QFile refspec_file {m_config.writeable_data_dir ().absoluteFilePath ("refspec.dat")}; + bool refspec_available {false}; + if (refspec_file.exists () and !refspec_file.remove ()) { + refspec_available = refspec_file.exists (); + MessageBox::warning_message (this, tr ("File Error"), + tr ("Cannot remove \"%1\": %2") + .arg (refspec_file.fileName (), refspec_file.errorString ())); + } + if (m_wideGraph) m_wideGraph->clearReferenceSpectrum (refspec_available); + m_bUseRef=false; m_bClearRefSpec=true; } void MainWindow::freqCalStep() { - if (m_frequency_list_fcal_iter == m_config.frequencies ()->end () - || ++m_frequency_list_fcal_iter == m_config.frequencies ()->end ()) { - m_frequency_list_fcal_iter = m_config.frequencies ()->begin (); + auto next = m_frequency_list_fcal_iter; + if (next == m_config.frequencies ()->end () + || ++next == m_config.frequencies ()->end ()) { + next = m_config.frequencies ()->begin (); } // allow for empty list - if (m_frequency_list_fcal_iter != m_config.frequencies ()->end ()) { - setRig (m_frequency_list_fcal_iter->frequency_ - ui->RxFreqSpinBox->value ()); + if (next != m_config.frequencies ()->end () + && requestNominalFrequencyChange ( + next->frequency_ - ui->RxFreqSpinBox->value (), FrequencyRequestOrigin::Automatic)) { + m_frequency_list_fcal_iter = next; } } @@ -13915,7 +14067,7 @@ void MainWindow::on_cbCQTx_toggled(bool b) m_ntx=6; m_QSOProgress = CALLING; } - setRig (); + reapplyCurrentRigFrequencyCorrection (); setXIT (ui->TxFreqSpinBox->value ()); } @@ -13943,10 +14095,10 @@ void MainWindow::statusUpdate () const { tr_period = quint32_max; } - m_messageClient->status_update (m_freqNominal, m_mode, m_hisCall, + m_messageClient->status_update (m_operatingFrequency.rx (), m_mode, m_hisCall, QString::number (ui->rptSpinBox->value ()), m_mode, ui->autoButton->isChecked (), - m_transmitting, m_decoderBusy, + m_transmitting, decoderBusy (), rx_frequency, ui->TxFreqSpinBox->value (), m_config.my_callsign (), m_config.my_grid (), m_hisGrid, m_tx_watchdog, @@ -14005,6 +14157,7 @@ void MainWindow::tx_watchdog (bool triggered) m_tx_watchdog = triggered; if (triggered) { + noteTxStopReason (TxEvidence::TxStopReason::Watchdog); m_bTxTime=false; if (m_tune) stop_tuning (); if (m_auto) auto_tx_mode (false); @@ -14034,7 +14187,7 @@ void MainWindow::update_watchdog_label () watchdog_label.setText (tr (" WD:%1m ").arg (m_config.watchdog () - m_idleMinutes)); watchdog_label.setVisible (true); // Highlight watchdog label yellow when there is less than one minute left - if ((m_config.watchdog() - m_idleMinutes == 1) && (m_auto or m_tune)) + if (normalWatchdogWarningActive ()) watchdog_label.setStyleSheet ("QLabel{color: #000000; background-color: #ffff00}"); if (m_config.watchdog() - m_idleMinutes > 1) watchdog_label.setStyleSheet (""); } @@ -14045,19 +14198,42 @@ void MainWindow::update_watchdog_label () } } -void MainWindow::on_cbMenus_toggled(bool b) +bool MainWindow::normalWatchdogWarningActive () const { - select_geometry (!b ? 2 : ui->actionSWL_Mode->isChecked () ? 1 : 0); + return m_config.watchdog () && m_mode != "WSPR" && m_mode != "FST4W" + && m_config.watchdog () - m_idleMinutes == 1 && (m_auto || m_tune); +} + +bool MainWindow::isHoundOperation () const +{ + return SpecOp::HOUND == m_specOp; +} + +bool MainWindow::isSuperHoundOperation () const +{ + return isHoundOperation () && m_config.superFox (); +} + +void MainWindow::updateHoundVerificationStyle () +{ + if (isHoundOperation () && m_houndVerified) + { + ui->labDXped->setStyleSheet ("QLabel {background-color: #00ff00; color: black;}"); + } + else + { + ui->labDXped->setStyleSheet ("QLabel {background-color: red; color: white;}"); + } } -void MainWindow::on_cbCQonly_toggled(bool) -{ //Fix this -- no decode here? - to_jt9(m_ihsym,1,-1); //Send m_ihsym to jt9[.exe] and start decoding - decodeBusy(true); +void MainWindow::on_cbMenus_toggled(bool b) +{ + select_geometry (!b ? 2 : ui->actionSWL_Mode->isChecked () ? 1 : 0); } void MainWindow::on_cbAutoSeq_toggled(bool b) { + if (!b) m_autoRespondPeriodState.disarm(); ui->respondComboBox->setVisible((m_mode=="FT8" or m_mode=="FT4" or m_mode=="FST4" or m_mode=="Q65" or m_mode=="MSK144" or m_mode=="JT65" or m_mode=="JT9") and b); check_button_color(); @@ -14065,6 +14241,13 @@ void MainWindow::on_cbAutoSeq_toggled(bool b) void MainWindow::on_measure_check_box_stateChanged (int state) { + if (!nominalFrequencyChangeAllowed (FrequencyRequestOrigin::User)) + { + QSignalBlocker const blocker {ui->measure_check_box}; + ui->measure_check_box->setCheckState ( + Qt::Checked == state ? Qt::Unchecked : Qt::Checked); + return; + } m_config.enable_calibration (Qt::Checked != state); } @@ -14077,7 +14260,7 @@ void MainWindow::write_transmit_entry (QString const& file_name) auto time = QDateTime::currentDateTimeUtc (); time = time.addSecs (-fmod(double(time.time().second()),m_TRperiod)); out << time.toString("yyMMdd_hhmmss") - << " Transmitting " << qSetRealNumberPrecision (12) << (m_freqNominal / 1.e6) + << " Transmitting " << qSetRealNumberPrecision (12) << (m_operatingFrequency.rx () / 1.e6) << " MHz " << m_mode << ": " << m_currentMessage #if QT_VERSION >= QT_VERSION_CHECK (5, 15, 0) @@ -14092,7 +14275,7 @@ void MainWindow::write_transmit_entry (QString const& file_name) { auto const& message = tr ("Cannot open \"%1\" for append: %2") .arg (f.fileName ()).arg (f.errorString ()); - QTimer::singleShot (0, [=] { // don't block guiUpdate + QTimer::singleShot (0, this, [=] { // don't block guiUpdate MessageBox::warning_message (this, tr ("Log File Error"), message); }); } @@ -14100,52 +14283,49 @@ void MainWindow::write_transmit_entry (QString const& file_name) void MainWindow::readWidebandDecodes() { - if(m_ActiveStationsWidget==NULL) return; int nhr=0; int nmin=0; int nsec=0; int nsnr=0; - while(m_fetched < qmapcom.ndecodes) { + int const max_qmap_decodes = sizeof qmapcom.result / sizeof qmapcom.result[0]; + int const qmap_decodes = qBound(0, qmapcom.ndecodes, max_qmap_decodes); + while(m_fetched < qmap_decodes) { // Recover and parse each decoded line. - QString line=QString::fromLatin1(qmapcom.result[m_fetched]); + auto const& row=qmapcom.result[m_fetched]; + QString line=QString::fromLatin1(row, + static_cast<int>(qmap_decode_ipc::text_length(row))); m_fetched++; - nhr=line.mid(0,2).toInt(); - nmin=line.mid(2,2).toInt(); - nsec=line.mid(4,2).toInt(); - int sTimeString = line.mid(0,6).toInt(); - QTime time2(nhr, nmin, nsec); - QDateTime qSpotTime; - if (sTimeString + m_TRperiod < 236000) { - qSpotTime = QDateTime(QDateTime::currentDateTimeUtc().date(), time2, Qt::UTC); - } - else { - qSpotTime = QDateTime((QDateTime::currentDateTimeUtc().addDays(-1)).date(), time2, Qt::UTC); - } - double frx=line.mid(6,9).toDouble(); - double fsked=line.mid(16,7).toDouble(); - QString submode=line.mid(36,3); - QString msg=line.mid(41,-1); - int i1=msg.indexOf(" "); - int i2=i1 +1 + msg.mid(i1+1,-1).indexOf(" "); - QString dxcall=msg.mid(i1+1,i2-i1-1); - if(stdCall(dxcall)) { - QString w3=msg.mid(i2+1,-1); - nsnr=line.mid(31,3).toInt(); + auto const record = parseQMapDecodeRecord ( + QByteArray {row, static_cast<int> (QMapDecodeRowSize)}); + if (!record) continue; + nhr=record->secondsSinceMidnight/3600; + nmin=(record->secondsSinceMidnight/60)%60; + nsec=record->secondsSinceMidnight%60; + auto const qSpotTime = DecodedTime::spotTime( + line.left(6), QDateTime::currentDateTimeUtc(), m_TRperiod); + if (!qSpotTime.isValid()) continue; + double frx=record->receiveFrequencyKHz; + double fsked=record->scheduledFrequencyKHz; + QString const& submode=record->submode; + QString const& dxcall=record->callsign; + if(stdCall (dxcall)) { + nsnr=record->snr; m_EMECall[dxcall].frx=frx; m_EMECall[dxcall].fsked=fsked; m_EMECall[dxcall].nsnr=nsnr; m_EMECall[dxcall].t=3600*nhr + 60*nmin + nsec; m_EMECall[dxcall].submode=submode; - if(w3.contains(grid_regexp)) m_EMECall[dxcall].grid4=w3; - bool bCQ=line.contains(" CQ "); + if(!record->grid.isEmpty ()) m_EMECall[dxcall].grid4=record->grid; + bool bCQ=record->cq; // m_EMECall[dxcall].ready2call=(bCQ or line.contains(" 73") or line.contains(" RR73")); m_EMECall[dxcall].ready2call=(bCQ); - Frequency frequency = (m_freqNominal/1000000) * 1000000 + int(fsked*1000.0); + Frequency frequency = (m_operatingFrequency.rx ()/1000000) * 1000000 + int(fsked*1000.0); bool bFromDisk=qmapcom.nQDecoderDone==2; - if(!bFromDisk and (m_EMECall[dxcall].grid4.contains(grid_regexp) or bCQ)) { + if(!bFromDisk && m_config.spot_to_psk_reporter () + && (m_EMECall[dxcall].grid4.contains(MainWindow::grid_regexp) or bCQ)) { qDebug() << "To PSKreporter:" << dxcall << m_EMECall[dxcall].grid4 << frequency << m_mode << nsnr; if (!m_psk_Reporter.addRemoteStation (dxcall, m_EMECall[dxcall].grid4, frequency, m_mode, nsnr, qSpotTime)) { - showStatusMessage (tr ("Spotting to PSK Reporter unavailable")); + showStatusMessage (tr ("PSK Reporter spot queue full; oldest spot dropped")); } } } @@ -14155,19 +14335,19 @@ void MainWindow::readWidebandDecodes() m_psk_Reporter.sendReport(); // Upload any queued spots } -// Update "m_wEMECall" by reading qmap_decodes.txt + if(m_ActiveStationsWidget==NULL) return; + +// Displayed row numbers index m_ready2call, so the rendered QMAP list must +// stay within the same capacity as its click-target storage. QMap<QString,EMECall>::iterator i; QString t=""; QString t1; QString dxcall; QString dxgrid4; - QStringList list; - float f[100]; - int indx[100]; + QVector<ActiveStationListItem> rows; int maxAge=m_ActiveStationsWidget->maxAge(); m_ActiveStationsWidget->setClickOK(false); - int k=0; for(i=m_EMECall.begin(); i!=m_EMECall.end(); i++) { bool bSkip=false; @@ -14190,52 +14370,63 @@ void MainWindow::readWidebandDecodes() t1=t1.asprintf("%7.3f %5.1f %+03d %3s %8s %4s %3d %3d %2s\n",i->frx,i->fsked,snr, submode.toLatin1().constData(),dxcall.toLatin1().constData(), dxgrid4.toLatin1().constData(),odd,age,c2); - f[k]=i->fsked; - list.append(t1); - k++; + rows.append({float(i->fsked), t1}); } m_ActiveStationsWidget->setClickOK(true); } } - if(k>0) { + std::fill(m_ready2call.begin(), m_ready2call.end(), QString {}); + rows=sorted_limited_active_station_items(rows, MaxActiveStationRows, false); + if(!rows.isEmpty()) { t1=""; - int kz=k; - indexx_(f,&kz,indx); - for(int k=0; k<kz; k++) { - int j=indx[k]-1; + for(int k=0; k<rows.size(); k++) { t1=t1.asprintf("%2d. ",k+1); - t1+=list[j]; - m_ready2call[k]=list[j]; + t1+=rows[k].text; + m_ready2call[k]=rows[k].text; t+=t1; } } if(m_ActiveStationsWidget != NULL) { m_ActiveStationsWidget->erase(); - m_ActiveStationsWidget->displayRecentStations(m_mode,t); + m_ActiveStationsWidget->displayRecentStations(ActiveStations::DisplayMode::Q65,t); m_ActiveStationsWidget->setClickOK(true); } - if(ipc_qmap[2]!=0) { - m_fetched=0; - ipc_qmap[0]=0; - ipc_qmap[2]=0; - } } // -------------------------- Code for FT8 DXpedition Mode --------------------------- -void MainWindow::hound_reply () -{ - if (!m_tune) { - // Select Tx3, set TxFreq to FoxFreq, and Force Auto ON. - ui->txrb3->setChecked (true); - m_nSentFoxRrpt = 1; - ui->rptSpinBox->setValue(m_rptSent.toInt()); - if (!m_auto) auto_tx_mode(true); - if (!m_config.superFox()) ui->TxFreqSpinBox->setValue (m_nFoxFreq); - stopWRTimer.start(int(11000.0*m_TRperiod)); // Tx3 timeout when in Hound mode - } +void MainWindow::hound_reply (int foxFrequency) +{ + HoundTransmissionPolicy::ReplyInput input; + input.protocol = m_config.superFox () ? HoundTransmissionPolicy::Protocol::SuperFox + : HoundTransmissionPolicy::Protocol::Classic; + input.tune = m_tune; + input.autoEnabled = m_auto; + input.sentReport = m_rptSent.toInt (); + input.decodedFoxFrequency = foxFrequency; + input.trPeriod = m_TRperiod; + auto const plan = HoundTransmissionPolicy::planFoxReportReply ( + m_houndTransmissionState, input); + if (!plan.applyReply) + { + m_houndTransmissionState = plan.nextState; + return; + } + + if (HoundTransmissionPolicy::TxMessage::Tx3 == plan.txMessage) + { + ui->txrb3->setChecked (true); + } + m_houndTransmissionState = plan.nextState; + ui->rptSpinBox->setValue (plan.report); + if (plan.enableAuto) auto_tx_mode (true); + if (HoundTransmissionPolicy::FrequencyAction::Set == plan.frequencyDecision.action) + { + ui->TxFreqSpinBox->setValue (plan.frequencyDecision.frequency); + } + stopWRTimer.start (plan.timeoutMilliseconds); } void MainWindow::on_sbNlist_valueChanged(int n) @@ -14259,9 +14450,9 @@ void MainWindow::FoxReset(QString reason="") { QFile f(m_config.temp_dir().absoluteFilePath("houndcallers.txt")); f.remove(); - ui->decodedTextBrowser->setText(""); - ui->houndQueueTextBrowser->setText(""); - ui->foxTxListTextBrowser->setText(""); + ui->decodedTextBrowser->clear(); + ui->houndQueueTextBrowser->clear(); + ui->foxTxListTextBrowser->clear(); m_houndQueue.clear(); m_foxQSO.clear(); @@ -14271,31 +14462,7 @@ void MainWindow::FoxReset(QString reason="") writeFoxQSO(" Reset"); } -void MainWindow::on_pbFoxReset_clicked() -{ - if(m_specOp!=SpecOp::FOX) return; - auto button = MessageBox::query_message (this, tr ("Confirm Reset"), - tr ("Are you sure you want to clear the QSO queues?")); - if(button == MessageBox::Yes) { - FoxReset(); - } -} -void MainWindow::on_pbFreeText_clicked() -{ - bool ok; - if(m_config.superFox()) { - m_freeTextMsg = QInputDialog::getText (this, tr("Free Text Message"), - tr("Message:"), QLineEdit::Normal, m_freeTextMsg0, &ok).left(26); - } else { - m_freeTextMsg = QInputDialog::getText (this, tr("Free Text Message"), - tr("Message:"), QLineEdit::Normal, m_freeTextMsg0, &ok).left(13); - } - if(ok) { - m_freeTextMsg=m_freeTextMsg.toUpper(); - m_freeTextMsg0=m_freeTextMsg; - } -} void MainWindow::on_comboBoxHoundSort_activated(int index) { @@ -14306,7 +14473,7 @@ void MainWindow::on_comboBoxCQ_activated() { if(m_config.superFox()) { ui->comboBoxCQ->setCurrentIndex(0); // No directional calls supported yet for SuperFox mode - QTimer::singleShot (0, [=] { // don't block guiUpdate + QTimer::singleShot (0, this, [=] { // don't block guiUpdate MessageBox::information_message(this, tr ("Directional calls not yet supported in SuperFox mode")); }); } @@ -14456,7 +14623,7 @@ QString MainWindow::sortHoundCalls(QString t, int isort, int max_dB) int nn=lines2.length(); if(isort==0) { // shuffle Hound calls to random order - int a[nn]; + int *a = new int[nn]; for(i=0; i<nn; i++) { a[i]=i; } @@ -14469,6 +14636,8 @@ QString MainWindow::sortHoundCalls(QString t, int isort, int max_dB) std::swap (a[j], a[i]); t += lines2.at(a[i]) + "\n"; } + delete [] a; + a = NULL; } int i0=t.indexOf("\n") + 1; @@ -14502,22 +14671,42 @@ void MainWindow::selectHound(QString line, bool bTopQueue) */ if(line.simplified().isEmpty()) return; if(line.length() < 6) return; - QString houndCall=line.split(" ",SkipEmptyParts).at(0); + QStringList houndFields = line.split(" ",SkipEmptyParts); + if(houndFields.size() < 3) return; + QString houndCall=houndFields.at(0); // Don't add a call already enqueued or in QSO if(ui->houndQueueTextBrowser->toPlainText().indexOf(houndCall) >= 0) return; - QString houndGrid=line.split(" ",SkipEmptyParts).at(1); // Hound caller's grid - QString rpt=line.split(" ",SkipEmptyParts).at(2); // Hound SNR + QString houndGrid=houndFields.at(1); // Hound caller's grid + QString rpt=houndFields.at(2); // Hound SNR + QString t1=houndCall + " "; + QString t2=m_config.superFox() ? superFoxTxReport(rpt) : rpt; + QString t1_with_grid; + if(!m_config.superFox()) { + bool ok=false; + int snr=rpt.toInt(&ok); + if(ok) { + snr=qBound(-30,snr,32); + snr=2*((snr+30)/2)-30; + t2=QString::asprintf("%+03d",snr); + } else { + if(t2.mid(0,1) != "-" and t2.mid(0,1) != "+") t2="+" + t2; + if(t2.length()==2) t2=t2.mid(0,1) + "0" + t2.mid(1,1); + } + } + if(m_config.superFox() && !superFoxQueueableHound(m_baseCall,houndCall,t2)) + { + removeHoundFromCallingList(houndCall); + showStatusMessage(tr("SuperFox cannot queue %1: unsupported callsign.") + .arg(houndCall)); + writeFoxQSO(" Reject: " + houndCall + " unsupported SuperFox callsign"); + return; + } m_houndCallers=m_houndCallers.remove(line+"\n"); // Remove t from sorted Hound list m_nSortedHounds--; ui->decodedTextBrowser->setHighlightedHoundText(m_houndCallers); // Populate left window with Hound callers - QString t1=houndCall + " "; - QString t2=rpt; - QString t1_with_grid; - if(rpt.mid(0,1) != "-" and rpt.mid(0,1) != "+") t2="+" + rpt; - if(t2.length()==2) t2=t2.mid(0,1) + "0" + t2.mid(1,1); t1=t1.mid(0,12) + t2; // display the callers, highlighting calls if necessary ui->houndQueueTextBrowser->insertText(bTopQueue ? t1 + "\n" : t1, QColor{}, QColor{}, houndCall, "", bTopQueue ? QTextCursor::Start : QTextCursor::End); @@ -14539,7 +14728,7 @@ void MainWindow::selectHound(QString line, bool bTopQueue) //------------------------------------------------------------------------------ void MainWindow::houndCallers() { -/* Called from decodeDone(), in DXpedition Fox mode. Reads decodes from file +/* Called from finishDecodeUi(), in DXpedition Fox mode. Reads decodes from file * "houndcallers.txt", ignoring any that are not addressed to MyCall, are already * in the stack, or with whom a QSO has been started. Others are considered to * be Hounds eager for a QSO. We add caller information (Call, Grid, SNR, Freq, @@ -14668,7 +14857,22 @@ void MainWindow::updateFoxQSOsInProgressDisplay() } } -void MainWindow::foxTxSequencer() +void MainWindow::clearSuperFoxPreparedTx() +{ + clearFoxTxMessages(); + std::memset(foxcom_.wave, 0, sizeof foxcom_.wave); +} + +void MainWindow::abortSuperFoxTxStart() +{ + clearSuperFoxPreparedTx(); + m_btxok = false; + m_tx_when_ready = false; + if (g_iptt == 1 || m_transmitting) stopTx(); + auto_tx_mode(false); +} + +bool MainWindow::foxTxSequencer() { /* Called from guiUpdate at the point where an FT8 Fox-mode transmission * is to be started. @@ -14691,6 +14895,192 @@ void MainWindow::foxTxSequencer() m_tFoxTxSinceOTP++; m_tFoxTx++; //Increment Fox Tx cycle counter + clearFoxTxMessages(); + + if (m_config.superFox()) { + qint32 const previousFoxTx0 = m_tFoxTx0; + qint32 const previousFoxTxSinceCQ = m_tFoxTxSinceCQ; + qint64 const previousFullFoxCallTime = m_fullFoxCallTime; + QString const previousFirstMessage = m_fm1; + bool const sendFreeText = ui->cbSendMsg->isChecked(); + QVector<SuperFoxTxPlanner::QsoState> qsos; + qsos.reserve(m_foxQSO.size()); + for (auto it = m_foxQSO.constBegin(); it != m_foxQSO.constEnd(); ++it) { + auto const& call = it.key(); + auto const& foxQSO = it.value(); + SuperFoxTxPlanner::QsoState qso; + qso.call = call; + qso.grid = foxQSO.grid; + qso.sent = foxQSO.sent; + qso.rcvd = foxQSO.rcvd; + qso.ncall = foxQSO.ncall; + qso.nRR73 = foxQSO.nRR73; + qso.tFoxRrpt = foxQSO.tFoxRrpt; + qso.tFoxTxRR73 = foxQSO.tFoxTxRR73; + qsos.push_back(qso); + } + + QVector<SuperFoxTxPlanner::QueuedHound> queuedHounds; + queuedHounds.reserve(m_houndQueue.size()); + for (auto const& line : m_houndQueue) { + queuedHounds.push_back(SuperFoxTxPlanner::parseQueuedHound(line)); + } + + auto const plan = SuperFoxTxPlanner::plan(qsos, m_foxQSOinProgress, + queuedHounds, m_maxStrikes, + sendFreeText); + QVector<SuperFoxTxPlanner::Record> rr73Records; + QVector<SuperFoxTxPlanner::Record> reportRecords; + for (auto const& record : plan.records) { + if (record.kind == SuperFoxTxPlanner::RecordKind::RR73) { + rr73Records.push_back(record); + } else { + reportRecords.push_back(record); + } + } + + auto logCompletedQSO = [this] (QString const& houndCall) { + auto alreadyLogged = m_loggedByFox[houndCall].contains(m_lastBand + " "); + auto const& qso = m_foxQSO[houndCall]; + if (!alreadyLogged) { + auto QSO_time = QDateTime::currentDateTimeUtc(); + m_hisCall = houndCall; + m_hisGrid = qso.grid; + m_rptSent = qso.sent; + m_rptRcvd = qso.rcvd; + if (!m_foxLogWindow) on_fox_log_action_triggered(); + if (m_logBook.fox_log()->add_QSO(QSO_time, m_hisCall, m_hisGrid, + m_rptSent, m_rptRcvd, m_lastBand)) { + writeFoxQSO(QString {" Log: %1 %2 %3 %4 %5"}.arg(m_hisCall).arg(m_hisGrid) + .arg(m_rptSent).arg(m_rptRcvd).arg(m_lastBand)); + on_logQSOButton_clicked(); + QTimer::singleShot(13000, [=] { + m_foxQSOinProgress.removeOne(houndCall); + updateFoxQSOsInProgressDisplay(); + }); + } + m_loggedByFox[houndCall] += (m_lastBand + " "); + } else { + writeFoxQSO(QString {" Dup: %1 %2 %3 %4 %5"}.arg(houndCall) + .arg(qso.grid).arg(qso.sent) + .arg(qso.rcvd).arg(m_lastBand)); + } + }; + + auto commitPlan = [this, &rr73Records, &reportRecords, &logCompletedQSO] { + for (auto const& record : rr73Records) { + auto& qso = m_foxQSO[record.call]; + qso.tFoxTxRR73 = m_tFoxTx; + qso.nRR73++; + logCompletedQSO(record.call); + } + + int queuedReportsToRemove = 0; + for (auto const& record : reportRecords) { + auto& qso = m_foxQSO[record.call]; + if (record.fromQueue) { + m_foxQSOinProgress.enqueue(record.call); + qso.grid = record.grid; + qso.sent = record.report; + qso.ncall = 0; + qso.nRR73 = 0; + qso.rcvd = -99; + qso.tFoxRrpt = -1; + qso.tFoxTxRR73 = -1; + queuedReportsToRemove++; + } + qso.ncall++; + } + + for (int i = 0; i < queuedReportsToRemove && !m_houndQueue.isEmpty(); ++i) { + m_houndQueue.dequeue(); + } + if (queuedReportsToRemove > 0) refreshHoundQueueDisplay(); + }; + + int const maxRows = sendFreeText ? 4 : 5; + int const rowCount = qMin(maxRows, qMax(rr73Records.size(), reportRecords.size())); + for (int i = 0; i < rowCount; ++i) { + bool const hasRR73 = i < rr73Records.size(); + bool const hasReport = i < reportRecords.size(); + fm.clear(); + if (hasRR73 && hasReport) { + auto const& rr73 = rr73Records.at(i); + auto const& report = reportRecords.at(i); + fm = Radio::base_callsign(rr73.call) + " RR73; " + + Radio::base_callsign(report.call) + " <" + m_config.my_callsign() + "> " + + report.report; + } else if (hasRR73) { + auto const& rr73 = rr73Records.at(i); + fm = Radio::base_callsign(rr73.call) + " " + m_baseCall + " RR73"; + } else if (hasReport) { + auto const& report = reportRecords.at(i); + fm = Radio::base_callsign(report.call) + " " + m_baseCall + " " + report.report; + } + islot++; + foxGenWaveform(islot - 1, fm); + } + + if (islot == 0) { + fm = ui->comboBoxCQ->currentText() + " " + m_config.my_callsign(); + if (!fm.contains("/")) { + fm += " " + m_config.my_grid().mid(0, 4); + m_fullFoxCallTime = now; + } + m_tFoxTx0 = m_tFoxTx; + islot++; + foxGenWaveform(islot - 1, fm); + } + + foxcom_.nslots = islot; + foxcom_.nfreq = ui->TxFreqSpinBox->value(); + if (m_config.split_mode()) foxcom_.nfreq = foxcom_.nfreq - m_XIT; + QString foxCall = m_config.my_callsign() + " "; + ::memcpy(foxcom_.mycall, foxCall.toLatin1(), sizeof foxcom_.mycall); + bool bSuperFox = true; + foxcom_.bMoreCQs = ui->cbMoreCQs->isChecked(); + foxcom_.bSendMsg = sendFreeText; + ::memcpy(foxcom_.textMsg, m_freeTextMsg0.leftJustified(26, ' ').toLatin1(), 26); + auto fname {QDir::toNativeSeparators(m_config.writeable_data_dir().absoluteFilePath("sfox_1.dat")).toLocal8Bit()}; + foxgen_(&bSuperFox, fname.constData(), (FCL)fname.size()); + if (!sfox_tx()) { + --m_tFoxTx; + --m_tFoxTxSinceOTP; + m_tFoxTx0 = previousFoxTx0; + m_tFoxTxSinceCQ = previousFoxTxSinceCQ; + m_fullFoxCallTime = previousFullFoxCallTime; + m_fm1 = previousFirstMessage; + abortSuperFoxTxStart(); + return false; + } + + commitPlan(); + displayFoxTxMsgs(); + writeFoxTxMsgs(); + m_tFoxTxSinceCQ++; + + for (QString houndCall: m_foxQSO.keys()) { + auto& qso = m_foxQSO[houndCall]; + if (qso.ncall >= m_maxStrikes) qso.ncall++; + bool b1 = ((m_tFoxTx - qso.tFoxRrpt) > 2 * m_maxFoxWait) && + (qso.tFoxRrpt > 0); + bool b2 = ((m_tFoxTx - qso.tFoxTxRR73) > m_maxFoxWait) && + (qso.tFoxTxRR73 > 0); + bool b3 = (qso.ncall >= m_maxStrikes + m_maxFoxWait); + bool b4 = (qso.nRR73 >= m_maxStrikes); + if (b1 or b2 or b3 or b4) { + m_foxQSO.remove(houndCall); + m_foxQSOinProgress.removeOne(houndCall); + } + } + + if (m_foxLogWindow) { + update_foxLogWindow_rate(); + m_foxLogWindow->queued(m_foxQSOinProgress.count()); + } + updateFoxQSOsInProgressDisplay(); + return true; + } // Is it time for a stand-alone CQ? if(m_tFoxTxSinceCQ >= m_foxCQtime and ui->cbMoreCQs->isChecked()) { @@ -14834,7 +15224,7 @@ list2Done: writeFoxQSO (QString {" Log: %1 %2 %3 %4 %5"}.arg (m_hisCall).arg (m_hisGrid) .arg (m_rptSent).arg (m_rptRcvd).arg (m_lastBand)); on_logQSOButton_clicked (); - QTimer::singleShot (13000, [=] { + QTimer::singleShot (13000, this, [=] { m_foxQSOinProgress.removeOne(hc1); //Remove from In Progress window updateFoxQSOsInProgressDisplay(); //Update InProgress display after Tx is complete }); @@ -14887,8 +15277,10 @@ Transmit: auto fname {QDir::toNativeSeparators(m_config.writeable_data_dir().absoluteFilePath("sfox_1.dat")).toLocal8Bit()}; foxgen_(&bSuperFox, fname.constData(), (FCL)fname.size()); if(bSuperFox) { - writeFoxTxMsgs(); - sfox_tx(); + if(sfox_tx()) { + displayFoxTxMsgs(); + writeFoxTxMsgs(); + } } m_tFoxTxSinceCQ++; @@ -14912,6 +15304,7 @@ Transmit: m_foxLogWindow->queued (m_foxQSOinProgress.count ()); } updateFoxQSOsInProgressDisplay(); + return true; } void MainWindow::update_foxLogWindow_rate() @@ -14930,62 +15323,42 @@ void MainWindow::refreshHoundQueueDisplay() } } -void MainWindow::doubleClickOnFoxQueue(Qt::KeyboardModifiers modifiers) +void MainWindow::doubleClickOnFoxQueue(QString const& houndLine, QString const&, Qt::KeyboardModifiers modifiers) { - if(modifiers==9999) return; //Silence compiler warning - QTextCursor cursor=ui->houndQueueTextBrowser->textCursor(); - cursor.setPosition(cursor.selectionStart()); - QString houndLine=cursor.block().text(); QString houndCall=houndLine.mid(0,12).trimmed(); if (modifiers == (Qt::AltModifier)) { //Alt-click on a Fox queue entry - put on top of queue - // remove - for(auto i=0; i<m_houndQueue.size(); i++) { - QString t = m_houndQueue[i]; - QString hc = t.mid(0, 12).trimmed(); - if (hc == houndCall) { - m_houndQueue.removeAt(i); - break; - } + if (FoxOperatorActions::moveQueuedHoundToFront (m_houndQueue, houndLine)) + { + refreshHoundQueueDisplay(); } - m_houndQueue.prepend(houndLine); - refreshHoundQueueDisplay(); } else { - writeFoxQSO(" Del: " + houndCall); - QQueue <QString> tmpQueue; - while (!m_houndQueue.isEmpty()) + if (FoxOperatorActions::removeQueuedHound (m_houndQueue, houndLine)) { - QString t = m_houndQueue.dequeue(); - QString hc = t.mid(0, 12).trimmed(); - if (hc != houndCall) tmpQueue.enqueue(t); + writeFoxQSO(" Del: " + houndCall); + refreshHoundQueueDisplay(); } - m_houndQueue.swap(tmpQueue); - refreshHoundQueueDisplay(); } } -void MainWindow::doubleClickOnFoxInProgress(Qt::KeyboardModifiers modifiers) +void MainWindow::doubleClickOnFoxInProgress(QString const& houndLine, QString const&, Qt::KeyboardModifiers modifiers) { - if (modifiers == 9999) return; //Silence compiler warning - QTextCursor cursor = ui->foxTxListTextBrowser->textCursor(); - cursor.setPosition(cursor.selectionStart()); - QString houndLine = cursor.block().text(); - QString houndCall = houndLine.mid(0, 12).trimmed(); - if (modifiers == 0) { - m_foxQSO[houndCall].ncall = m_maxStrikes + 1; // time them out - updateFoxQSOsInProgressDisplay(); + if (FoxOperatorActions::timeoutIfActive (m_foxQSOinProgress, m_foxQSO, houndLine, + m_maxStrikes + 1)) + { + updateFoxQSOsInProgressDisplay(); + } } } void MainWindow::foxQueueTopCallCommand() { - m_decodedText2 = true; - if(SpecOp::FOX==m_specOp && m_decodedText2 && m_houndQueue.count() < MAX_HOUNDS_IN_QUEUE) + if(SpecOp::FOX==m_specOp && m_houndQueue.count() < MAX_HOUNDS_IN_QUEUE) { QTextCursor cursor = ui->decodedTextBrowser->textCursor(); @@ -15007,36 +15380,47 @@ void MainWindow::foxGenWaveform(int i,QString fm) QString txModeArg; txModeArg = txModeArg.asprintf("FT8fox %d",i+1); int nfreq=ui->TxFreqSpinBox->value()+60*i; + bool const superFoxTx = m_config.superFox() && SpecOp::FOX==m_specOp; - if(m_config.superFox() && SpecOp::FOX==m_specOp) { - nfreq=750; - if(i==0 && ui->cbSendMsg->isChecked()) { - ui->decodedTextBrowser2->displayTransmittedText(m_freeTextMsg0, txModeArg, - nfreq,m_bFastMode,m_TRperiod,m_config.superFox()); - } - } - - ui->decodedTextBrowser2->displayTransmittedText(fm.trimmed(), txModeArg, - nfreq,m_bFastMode,m_TRperiod,m_config.superFox()); foxcom_.i3bit[i]=0; if(fm.indexOf("<")>0) foxcom_.i3bit[i]=1; strncpy(&foxcom_.cmsg[i][0],fm.toLatin1(),40); //Copy this message into cmsg[i] if(i==0) m_fm1=fm; + + if(superFoxTx) return; + + ui->decodedTextBrowser2->displayTransmittedText(fm.trimmed(), txModeArg, + nfreq,m_bFastMode,m_TRperiod,m_config.superFox()); QString t; t = t.asprintf(" Tx%d: ",i+1); writeFoxQSO(t + fm.trimmed()); } -void MainWindow::writeFoxTxMsgs() { - // references extern struct foxcom_ - QString t; - for (int i = 0; i < 5; i++) { - t = QString::fromLatin1(foxcom_.cmsg[i]).left(40); - if (t.length() > 0) { - write_all("Tx", t); +void MainWindow::displayFoxTxMsgs() +{ + for(auto const& message: superFoxTxMessages()) { + QString txModeArg; + txModeArg = txModeArg.asprintf("FT8fox %d",message.slot); + if(message.slot==1 && foxcom_.bSendMsg) { + QString const freeText = QString::fromLatin1(foxcom_.textMsg, + sizeof foxcom_.textMsg).trimmed(); + ui->decodedTextBrowser2->displayTransmittedText(freeText, txModeArg, + 750,m_bFastMode,m_TRperiod,m_config.superFox()); } + ui->decodedTextBrowser2->displayTransmittedText(message.text, txModeArg, + 750,m_bFastMode,m_TRperiod,m_config.superFox()); + + QString prefix; + prefix = prefix.asprintf(" Tx%d: ",message.slot); + writeFoxQSO(prefix + message.text); + } +} + +void MainWindow::writeFoxTxMsgs() { + for(auto const& message: superFoxTxMessages()) { + write_all("Tx", message.text); } - t = QString::fromLatin1(foxcom_.textMsg).left(38); + QString const t = QString::fromLatin1(foxcom_.textMsg, sizeof foxcom_.textMsg).trimmed(); if (foxcom_.bSendMsg) { write_all("Tx", "-Free Text- "+t); } @@ -15057,7 +15441,7 @@ void MainWindow::writeFoxTxMsgs() { #else << fixed #endif - << qSetRealNumberPrecision (3) << (m_freqNominal/1.e6) + << qSetRealNumberPrecision (3) << (m_operatingFrequency.rx ()/1.e6) << t << msg #if QT_VERSION >= QT_VERSION_CHECK (5, 15, 0) << Qt::endl @@ -15160,7 +15544,7 @@ void MainWindow::foxTest() } } if(line.contains("Tx1:")) { - foxTxSequencer(); + if (!foxTxSequencer()) return; } else { t = t.asprintf("%3d %3d %3d %3d %5d ",m_houndQueue.count(), m_foxQSOinProgress.count(),m_foxQSO.count(), @@ -15175,7 +15559,8 @@ void MainWindow::foxTest() } } -void MainWindow::write_all(QString txRx, QString message) +void MainWindow::write_all(QString txRx, QString message, + DecodeOperatingContext const * context) { if (!(ui->actionDisable_writing_of_ALL_TXT->isChecked())) { QString line; @@ -15183,9 +15568,15 @@ void MainWindow::write_all(QString txRx, QString message) QString msg; QString mode_string; QString file_name="ALL.TXT"; + auto const mode = context ? context->mode : m_mode; + auto const specOp = context ? context->specOp : m_specOp; + auto const superFox = context ? context->superFox : m_config.superFox (); + auto const diskData = context ? context->diskData : m_diskData; + auto const periodFrequency = context ? context->periodFrequency : m_freqNominalPeriod; + auto const sequenceStart = context ? context->sequenceStart : m_dateTimeSeqStart; QRegularExpression verified_call_regex {"[A-Z0-9/]+\\sverified\\s*"}; - if(m_mode!="Echo") { + if(mode!="Echo") { if (message.size () > 5 && message[4]==' ') { msg=message.mid(4,-1); } else { @@ -15196,17 +15587,19 @@ void MainWindow::write_all(QString txRx, QString message) mode_string="JT65 "; } else if (message.size () > 19 && message[19]=='@') { mode_string="JT9 "; - } else if(m_mode=="Q65") { - mode_string=mode_label.text(); + } else if(mode=="Q65") { + auto const period = context ? context->trPeriod : m_TRperiod; + auto const submode = context ? context->submode : m_nSubMode; + mode_string = "Q65-" + QString::number(period) + QChar('A' + submode); } else { - mode_string=m_mode.leftJustified(6,' '); + mode_string=mode.leftJustified(6,' '); } - if(mode_string=="FT8 " and txRx=="Tx" and m_config.superFox() and - m_specOp==SpecOp::FOX) mode_string="FT8_SF"; + if(mode_string=="FT8 " and txRx=="Tx" and superFox and + specOp==SpecOp::FOX) mode_string="FT8_SF"; - if(mode_string=="FT8 " and m_config.superFox() and - m_specOp==SpecOp::HOUND) mode_string="FT8_SH"; + if(mode_string=="FT8 " and superFox and + specOp==SpecOp::HOUND) mode_string="FT8_SH"; if (mode_string == "FT8_SH" && verified_call_regex.match(message).hasMatch()) { msg = " "+message; @@ -15214,17 +15607,26 @@ void MainWindow::write_all(QString txRx, QString message) msg = msg.mid(0, 15) + msg.mid(18, -1); } - t = t.asprintf("%5d",ui->TxFreqSpinBox->value()); + int const txFrequency = mode=="JTTY" + ? ui->TxFreqSpinBox_2->value() : ui->TxFreqSpinBox->value(); + t = t.asprintf("%5d",txFrequency); if (txRx=="Tx") msg=" 0 0.0" + t + " " + message; + if (mode=="JTTY" and txRx=="Rx") { + auto const decoded = Jtty::parseDecodeLine(message); + int const frequency = decoded.valid + ? decoded.frequency : ui->RxFreqSpinBox_2->value(); + t = t.asprintf("%5d", frequency); + msg=" 0 0.0" + t + " " + decoded.message; + } auto time = QDateTime::currentDateTimeUtc (); - if( (txRx=="Rx" || txRx=="Ck") && !m_bFastMode ) time=m_dateTimeSeqStart; + if( (txRx=="Rx" || txRx=="Ck") && (context || !m_bFastMode) ) time=sequenceStart; if (txRx=="Rx") { - t = t.asprintf("%10.3f ",m_freqNominalPeriod/1.e6); // prevent writing of wrong frequencies + t = t.asprintf("%10.3f ",periodFrequency/1.e6); } else { - t = t.asprintf("%10.3f ",m_freqNominal/1.e6); + t = t.asprintf("%10.3f ",m_operatingFrequency.rx ()/1.e6); } - if (m_diskData) { + if (diskData and !(mode=="JTTY" and txRx=="Tx")) { if (m_fileDateTime.size()==11) { line=m_fileDateTime + " " + t + txRx + " " + mode_string + msg; } else { @@ -15236,7 +15638,7 @@ void MainWindow::write_all(QString txRx, QString message) if (ui->actionSplit_ALL_TXT_yearly->isChecked()) file_name=(time.toString("yyyy") + "-" + "ALL.TXT"); if (ui->actionSplit_ALL_TXT_monthly->isChecked()) file_name=(time.toString("yyyy-MM") + "-" + "ALL.TXT"); - if (m_mode=="WSPR") file_name="ALL_WSPR.TXT"; + if (mode=="WSPR") file_name="ALL_WSPR.TXT"; } else { file_name="all_echo.txt"; line=message; @@ -15256,7 +15658,7 @@ void MainWindow::write_all(QString txRx, QString message) } else { auto const& message2 = tr ("Cannot open \"%1\" for append: %2") .arg (f.fileName ()).arg (f.errorString ()); - QTimer::singleShot (0, [=] { // don't block guiUpdate + QTimer::singleShot (0, this, [=] { // don't block guiUpdate MessageBox::warning_message(this, tr ("Log File Error"), message2); }); } } @@ -15273,16 +15675,8 @@ void MainWindow::chkFT4() m_specOp=m_config.special_op_id(); if(m_specOp!=SpecOp::NONE and m_specOp!=SpecOp::FOX and m_specOp!=SpecOp::HOUND) { - QString t0=""; - if(SpecOp::NA_VHF==m_specOp && m_config.NCCC_Sprint()) t0="NCCC Sprint"; - if(SpecOp::NA_VHF==m_specOp && !m_config.NCCC_Sprint()) t0="NA VHF"; - if(SpecOp::EU_VHF==m_specOp) t0="EU VHF"; - if(SpecOp::FIELD_DAY==m_specOp) t0="Field Day"; - if(SpecOp::RTTY==m_specOp) t0="FT RU"; - if(SpecOp::WW_DIGI==m_specOp) t0="WW Digi"; - if(SpecOp::ARRL_DIGI==m_specOp) t0="ARRL Digi"; - if(SpecOp::Q65_PILEUP==m_specOp) t0="Q65 Pileup"; - if(t0=="") { + QString t0 = specOpLabel(); + if(t0.isEmpty()) { ui->labDXped->setVisible(false); } else { ui->labDXped->setVisible(true); @@ -15296,16 +15690,10 @@ void MainWindow::chkFT4() } -void MainWindow::on_pbBestSP_clicked() -{ - m_bBestSPArmed = !m_bBestSPArmed; - if(m_bBestSPArmed and !m_transmitting) ui->pbBestSP->setStyleSheet ("QPushButton{color:red}"); - if(!m_bBestSPArmed) ui->pbBestSP->setStyleSheet (""); - if(m_bBestSPArmed) m_dateTimeBestSP=QDateTime::currentDateTimeUtc(); -} void MainWindow::set_mode (QString const& mode) { + m_autoRespondPeriodState.disarm(); if ("FT4" == mode) on_actionFT4_triggered (); else if ("FST4" == mode) on_actionFST4_triggered (); else if ("FST4W" == mode) on_actionFST4W_triggered (); @@ -15315,6 +15703,7 @@ void MainWindow::set_mode (QString const& mode) else if ("JT65" == mode) on_actionJT65_triggered (); else if ("Q65" == mode) on_actionQ65_triggered (); else if ("FreqCal" == mode) on_actionFreqCal_triggered (); + else if ("JTTY" == mode) on_actionJTTY_triggered (); else if ("MSK144" == mode) on_actionMSK144_triggered (); else if ("WSPR" == mode) on_actionWSPR_triggered (); else if ("Echo" == mode) on_actionEcho_triggered (); @@ -15322,18 +15711,15 @@ void MainWindow::set_mode (QString const& mode) void MainWindow::configActiveStations() { - if (m_ActiveStationsWidget != NULL and (m_mode == "Q65" or m_mode == "FT4" or m_mode == "FT8")) { - if (m_specOp == SpecOp::Q65_PILEUP) { - m_ActiveStationsWidget->displayRecentStations("Q65-pileup", ""); - } else { - if (m_specOp == SpecOp::FOX) - if (m_config.superFox()) - m_ActiveStationsWidget->displayRecentStations("SuperFox Mode", ""); - else - m_ActiveStationsWidget->displayRecentStations("Fox Mode", ""); - else - m_ActiveStationsWidget->displayRecentStations(m_mode, ""); + if (m_ActiveStationsWidget) { + auto displayMode = ActiveStations::DisplayMode::Standard; + if (m_mode == "Q65") { + displayMode = m_specOp == SpecOp::Q65_PILEUP + ? ActiveStations::DisplayMode::Q65Pileup : ActiveStations::DisplayMode::Q65; + } else if (m_mode == "FT8" && m_specOp == SpecOp::FOX) { + displayMode = ActiveStations::DisplayMode::Fox; } + m_ActiveStationsWidget->displayRecentStations(displayMode, ""); } } @@ -15446,70 +15832,18 @@ QString MainWindow::WSPR_message() return msg2; } -void MainWindow::on_houndButton_clicked (bool checked) -{ - if (checked) { - HoldTxFreqStatus = ui->cbHoldTxFreq->isChecked(); // save state of the Hold Tx Freq checkbox - m_config.setSpecial_Hound(); - ui->tx1->setVisible(true); - ui->tx1->setEnabled(true); - ui->txb1->setEnabled(true); - } else { - m_config.setSpecial_None(); - keep_frequency = true; - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - m_specOp=m_config.special_op_id(); - on_actionFT8_triggered(); - check_button_color(); -} -void MainWindow::on_cbHoldTxFreq_clicked (bool) -{ - HoldTxFreqStatus = ui->cbHoldTxFreq->isChecked(); // save state of the Hold Tx Freq checkbox -} -void MainWindow::on_ft8Button_clicked() -{ - if (m_specOp==SpecOp::HOUND or m_specOp==SpecOp::FOX) { - m_config.setSpecial_None(); - m_specOp=m_config.special_op_id(); - } - on_actionFT8_triggered(); -} -void MainWindow::on_ft4Button_clicked() -{ - on_actionFT4_triggered(); -} -void MainWindow::on_msk144Button_clicked() -{ - on_actionMSK144_triggered(); -} -void MainWindow::on_q65Button_clicked() -{ - if (m_specOp==SpecOp::Q65_PILEUP) { - m_config.setSpecial_None(); - m_specOp=m_config.special_op_id(); - } - on_actionQ65_triggered(); -} -void MainWindow::on_jt65Button_clicked() -{ - on_actionJT65_triggered(); -} -void MainWindow::on_echoButton_clicked() -{ - on_actionEcho_triggered(); -} -void MainWindow::sfox_tx() { +bool MainWindow::sfox_tx() { auto fname{QDir::toNativeSeparators(m_config.writeable_data_dir().absoluteFilePath("sfox_1.dat")).toLocal8Bit()}; QString ckey{"OTP:000000"}; + int pack_error {0}; LOG_INFO(QString("sfox_tx: OTP code is %1").arg(foxOTPcode())); #ifdef FOX_OTP qint32 otp_key = 0; @@ -15535,488 +15869,48 @@ void MainWindow::sfox_tx() { } } #endif - sftx_sub_(ckey.toLatin1().constData(), (FCL)ckey.size()); + sftx_sub_(ckey.toLatin1().constData(), &pack_error, (FCL)ckey.size()); + if(pack_error != 0) { + QString message; + switch(pack_error) { + case SuperFoxPackBadToken: + message = tr ("SuperFox Tx stopped: invalid message tokens."); + break; + case SuperFoxPackBadOtp: + message = tr ("SuperFox Tx stopped: invalid verification code."); + break; + case SuperFoxPackBadCq: + message = tr ("SuperFox Tx stopped: invalid CQ call or grid."); + break; + case SuperFoxPackBadCall: + message = tr ("SuperFox Tx stopped: invalid callsign."); + break; + case SuperFoxPackBadReport: + message = tr ("SuperFox Tx stopped: report is outside the " + "SuperFox range."); + break; + case SuperFoxPackBadFreeText: + message = tr ("SuperFox Tx stopped: free text contains unsupported " + "characters."); + break; + default: + message = tr ("SuperFox Tx stopped: message could not be packed."); + break; + } + showStatusMessage (message); + LOG_WARN(QString("%1 Error code: %2").arg(message).arg(pack_error)); + return false; + } sfox_wave_gfsk_(); + return true; } -void MainWindow::on_pb15A_clicked() -{ - ui->sbTR->setValue(15); - ui->sbSubmode->setValue(0); -} -void MainWindow::on_pb15C_clicked() -{ - ui->sbTR->setValue(15); - ui->sbSubmode->setValue(2); - ui->TxFreqSpinBox->setValue(700); -} -void MainWindow::on_pb30B_clicked() -{ - ui->sbTR->setValue(30); - ui->sbSubmode->setValue(1); -} -void MainWindow::on_pb60C_clicked() -{ - ui->sbTR->setValue(60); - ui->sbSubmode->setValue(2); -} - -void MainWindow::on_pb60D_clicked() -{ - ui->sbTR->setValue(60); - ui->sbSubmode->setValue(3); -} -void MainWindow::on_pb60E_clicked() -{ - ui->sbTR->setValue(60); - ui->sbSubmode->setValue(4); - ui->TxFreqSpinBox->setValue(700); -} -void MainWindow::bandHoppingTimer() -{ - if(ui->pbBandHopping->isChecked()) { - static int startIndex = 0; - int nextStartIndex = startIndex +1; - switch (startIndex){ - case 0: - startIndex = nextStartIndex; // band hopping every other minute - return; - case 1: - m_displayBand = false; - bandHopping(); - startIndex = 0; - return; - } - } -} -void MainWindow::bandHopping() -{ - if(ui->pbBandHopping->isChecked() && !ui->autoButton->isChecked() && !ui->tuneButton->isChecked()) { - static int startIndex = 0; - int nextStartIndex = startIndex +1; - switch (startIndex){ - case 0: - if (ui->cb160m->isChecked()) { - on_actionFT8_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (1840000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 1: - if (ui->cb80m->isChecked()) { - on_actionFT8_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (3573000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 2: - if (ui->cb60m->isChecked()) { - on_actionFT8_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (5357000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 3: - if (ui->cb40m->isChecked()) { - on_actionFT8_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (7074000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 4: - if (ui->cb30m->isChecked()) { - on_actionFT8_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (10136000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 5: - if (ui->cb20m->isChecked()) { - on_actionFT8_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (14074000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 6: - if (ui->cb17m->isChecked()) { - on_actionFT8_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (18100000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 7: - if (ui->cb15m->isChecked()) { - on_actionFT8_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (21074000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 8: - if (ui->cb12m->isChecked()) { - on_actionFT8_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (24915000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 9: - if (ui->cb10m->isChecked()) { - on_actionFT8_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (28074000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 10: - if (ui->cb6m->isChecked()) { - on_actionFT8_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (50313000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 11: - if (ui->cb4m->isChecked()) { - on_actionFT8_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (70154000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 12: - if (ui->cb2m->isChecked()) { - on_actionFT8_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (144174000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 13: - if (ui->cb70cm->isChecked()) { - on_actionFT8_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (432174000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 14: - if (ui->cb80mFT4->isChecked()) { - on_actionFT4_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (3575000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 15: - if (ui->cb40mFT4->isChecked()) { - on_actionFT4_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (7047500); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 16: - if (ui->cb30mFT4->isChecked()) { - on_actionFT4_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (10140000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 17: - if (ui->cb20mFT4->isChecked()) { - on_actionFT4_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (14080000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 18: - if (ui->cb17mFT4->isChecked()) { - on_actionFT4_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (18104000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - - case 19: - if (ui->cb15mFT4->isChecked()) { - on_actionFT4_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (21140000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 20: - if (ui->cb12mFT4->isChecked()) { - on_actionFT4_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (24919000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 21: - if (ui->cb10mFT4->isChecked()) { - on_actionFT4_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (28180000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 22: - if (ui->cb2mMSK->isChecked()) { - on_actionMSK144_triggered(); - auto const& row = m_config.frequencies ()->best_working_frequency (144360000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) on_bandComboBox_activated (row); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 23: - if (ui->cbQRG1->isChecked()) { - int f1 = ui->sbQRG1->value()*1000; - keep_frequency = true; - QTimer::singleShot (250, [=] {keep_frequency = false;}); - setRig (f1); - on_actionFT8_triggered(); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 24: - if (ui->cbQRG2->isChecked()) { - int f2 = ui->sbQRG2->value()*1000; - keep_frequency = true; - QTimer::singleShot (250, [=] {keep_frequency = false;}); - setRig (f2); - on_actionFT8_triggered(); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 25: - if (ui->cbQRG3->isChecked()) { - int f3 = ui->sbQRG3->value()*1000; - keep_frequency = true; - QTimer::singleShot (250, [=] {keep_frequency = false;}); - setRig (f3); - on_actionFT8_triggered(); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 26: - if (ui->cbQRG4->isChecked()) { - int f4 = ui->sbQRG4->value()*1000; - keep_frequency = true; - QTimer::singleShot (250, [=] {keep_frequency = false;}); - setRig (f4); - on_actionFT8_triggered(); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 27: - if (ui->cbQRG5->isChecked()) { - int f5 = ui->sbQRG5->value()*1000; - keep_frequency = true; - QTimer::singleShot (250, [=] {keep_frequency = false;}); - setRig (f5); - on_actionFT8_triggered(); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 28: - if (ui->cbQRG6->isChecked()) { - int f6 = ui->sbQRG6->value()*1000; - keep_frequency = true; - QTimer::singleShot (250, [=] {keep_frequency = false;}); - setRig (f6); - on_actionFT8_triggered(); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 29: - if (ui->cbQRG7->isChecked()) { - int f7 = ui->sbQRG7->value()*1000; - keep_frequency = true; - QTimer::singleShot (250, [=] {keep_frequency = false;}); - setRig (f7); - on_actionFT8_triggered(); - ui->pbBandHopping->setChecked(true); - startIndex = nextStartIndex; - return; - } else { - nextStartIndex++; - } - Q_FALLTHROUGH(); - case 30: - if (ui->cbQRG8->isChecked()) { - int f8 = ui->sbQRG8->value()*1000; - keep_frequency = true; - QTimer::singleShot (250, [=] {keep_frequency = false;}); - setRig (f8); - on_actionFT8_triggered(); - ui->pbBandHopping->setChecked(true); - startIndex = 0; - return; - bandHopping(); - } else { - startIndex = 0; - bandHopping(); - } - } - } -} void MainWindow::on_actionDefault_event_logging_triggered() { @@ -16044,7 +15938,7 @@ void MainWindow::on_actionDiagnostic_mode_triggered() QString path = QStandardPaths::writableLocation (QStandardPaths::DataLocation); QStringList tw; if (path.contains("/WSJT-X")) tw=path.split("/WSJT-X"); - if (tw.size () > 0 && tw[1].remove(" - ") != "") instance = tw[1].remove(" - ") + "/"; + if (tw.size () > 1 && tw[1].remove(" - ") != "") instance = tw[1].remove(" - ") + "/"; QString EventConfig = ( "\[Sinks.SYSLOG]\n" "Destination=TextFile\n" @@ -16053,7 +15947,7 @@ void MainWindow::on_actionDiagnostic_mode_triggered() "FileName=\"${DesktopLocation}/logs/" + instance + "wsjtx_syslog.log\"\n" "Append=true\n" "Format=\"[%Channel%][%TimeStamp(format=\\\"%Y-%m-%d %H:%M:%S.%f\\\")%][%Uptime(format=\\\"%O:%M:%S.%f\\\")%][%Severity%] %Message%\"\n" - "Filter=\"%Channel% matches \\\"SYSLOG\\\" | %Severity% >= info\"\n" + "Filter=\"%Channel% matches \\\"SYSLOG\\\" & %Severity% >= info\"\n" "\n" "\[Sinks.RIGCTRL]\n" "Destination=TextFile\n" @@ -16062,7 +15956,7 @@ void MainWindow::on_actionDiagnostic_mode_triggered() "FileName=\"${DesktopLocation}/logs/" + instance + "WSJT-X_RigControl.log\"\n" "Append=true\n" "Format=\"[%TimeStamp(format=\\\"%Y-%m-%d %H:%M:%S.%f\\\")%][%Uptime(format=\\\"%O:%M:%S.%f\\\")%][%Channel%:%Severity%] %Message%\"\n" - "Filter=\"%Channel% matches \\\"RIGCTRL\\\" | %Severity% >= info\"" + "Filter=\"%Channel% matches \\\"RIGCTRL\\\" & %Severity% >= info\"" ); QTextStream out(&f); out << EventConfig; @@ -16112,56 +16006,7 @@ void MainWindow::on_actionDisable_event_logging_triggered() void MainWindow::on_actionUse_Dark_Style_triggered (bool checked) { - QFont font = m_config.text_font(); - if (checked) { - QFile f(":qdarkstyle/style.qss"); - if (!f.exists()) { - printf("Unable to set stylesheet, file not found\n"); - } else { - qApp->setFont (font); - QString ss; - f.open(QFile::ReadOnly | QFile::Text); - QTextStream ts(&f); - qApp->setStyleSheet(ts.readAll() + "* {" + font_as_stylesheet (font) + '}'); - m_useDarkStyle = true; - m_wideGraph->setDarkStyle(m_useDarkStyle); - check_button_color(); - ui->tabWidget->setTabShape(QTabWidget::Rounded); - } - } else { - m_useDarkStyle = false; - m_wideGraph->setDarkStyle(m_useDarkStyle); - check_button_color(); - ui->tabWidget->setTabShape(QTabWidget::Triangular); - qApp->setFont (font); - QString ss; - if (qApp->styleSheet ().size ()) { - auto sheet = qApp->styleSheet (); - sheet.remove ("file:///"); - QFile sf {sheet}; - if (sf.open (QFile::ReadOnly | QFile::Text)) ss = sf.readAll () + ss; - } - qApp->setStyleSheet (ss + "* {" + font_as_stylesheet (font) + '}'); - } - // ensure a balanced layout - qreal pointSize = m_config.text_font().pointSizeF(); -// if (pointSize < 9) ui->controls_stack_widget->setMaximumWidth(180); // UR for AL -// if (pointSize == 9) ui->controls_stack_widget->setMaximumWidth(200); // UR for AL -// if (pointSize == 10) ui->controls_stack_widget->setMaximumWidth(220); // UR for AL -// if (pointSize > 10) ui->controls_stack_widget->setMaximumWidth(240); // UR for AL - if (pointSize < 11) { -// ui->tabWidget->setMaximumHeight(210); // UR for AL -// ui->controls_stack_widget->setMaximumHeight(200); // UR for AL - if (ui->actionUse_Dark_Style->isChecked()) ui->tabWidget->setMaximumHeight(225); // UR for normal + widescreen - } else { -// ui->tabWidget->setMaximumHeight(255); // UR for AL -// ui->controls_stack_widget->setMaximumHeight(225); // UR for AL - ui->tabWidget->setMaximumHeight(500); // UR for normal + widescreen - } - for (auto& widget : qApp->topLevelWidgets ()) - { - widget->updateGeometry (); - } + applyApplicationStyle (m_config.text_font (), checked); statusChanged(); guiUpdate(); } @@ -16182,62 +16027,118 @@ void MainWindow:: on_actionVHF_UHF_Buttons_triggered () void MainWindow::check_button_color() { - // Yellow background for the DX Call and Enable Tx buttons when the rig is allowed to Tx automatically - if((((m_mode=="FT8" or m_mode=="FT4" or m_mode=="Q65" or m_mode=="FST4" or m_mode=="MSK144" or m_mode=="JT65" or m_mode=="JT9" or m_mode=="JT4") && - m_specOp==SpecOp::NONE && ui->cbAutoSeq->isChecked() && ui->cbAutoSeq->isChecked() - && m_config.Wait_features_enabled()) or m_specOp==SpecOp::HOUND) && (m_hisCall!="" or (m_mode=="FT8" && m_specOp==SpecOp::HOUND))) { - if (ui->DX_Call_Button->isChecked()) { - ui->DX_Call_Button->setStyleSheet("QPushButton {background-color: #ff0000; color: #ffffff; border-style: outset; border-width: 1px; border-radius: 5px; border-color: black; min-width: 5em; padding: 3px;}"); - } else { - if (m_mode=="FT8" && m_specOp==SpecOp::HOUND && m_hisCall=="") { - if (m_useDarkStyle) { - ui->DX_Call_Button->setStyleSheet("QPushButton {background-color: #505F69; color: #ffffff; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); - } else { - ui->DX_Call_Button->setStyleSheet("QPushButton {background-color: #9fafd5; border: none;}"); - } - } else { - ui->DX_Call_Button->setStyleSheet("QPushButton {background-color: #ffff00; color: #000000; border: 1px solid #32414B; border-radius: 4px; padding: 3px; outline: none;}"); - } - } - if (!m_auto) { - if (m_mode=="FT8" && m_specOp==SpecOp::HOUND && m_hisCall=="") { - if (m_useDarkStyle) { - ui->autoButton->setStyleSheet("QPushButton {background-color: #505F69; color: #ffffff; border: 1px solid #32414B; color: #F0F0F0; border-radius: 5px; padding: 3px; outline: none; min-width: 5em;}"); - } else { - ui->autoButton->setStyleSheet(""); - ui->autoButton->setStyleSheet("QPushButton {min-width: 5em;}"); - } - } else { - ui->autoButton->setStyleSheet("QPushButton {background-color: #ffff00; color: #000000; border: 1px solid #32414B; border-radius: 4px; padding: 3px; outline: none; min-width: 5em;}"); - } - } - if (m_auto) ui->autoButton->setStyleSheet("QPushButton {background-color: #ff0000; color: #ffffff; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none; min-width: 5em;}"); + WaitFeatureContext const waitContext { + m_mode, + m_specOp, + m_config.Wait_features_enabled(), + ui->cbAutoSeq->isChecked(), + !m_hisCall.isEmpty(), + m_config.NCCC_Sprint() + }; + auto const waitAndCallEligible = wait_and_call_arming_eligible (waitContext); + auto const enableTxWarning = enable_tx_warning (waitContext); + + if (!waitAndCallEligible) { + ui->DX_Call_Button->setChecked (false); + wait_and_call = false; + } else if (!ui->DX_Call_Button->isChecked()) { + wait_and_call = false; + } + + static QString const dx_call_button_style { + "QPushButton {border: 1px solid #32414B; border-radius: 4px; padding: 3px; " +#ifdef Q_OS_MAC + "margin-left: 6px; margin-right: 6px; " +#endif + "outline: none;}" + "QPushButton[wsjtxState=\"active\"] {background-color: #ff0000; color: #ffffff;}" + "QPushButton[wsjtxState=\"warning\"] {background-color: #ffff00; color: #000000;}" + "QPushButton[wsjtxState=\"dark\"] {background-color: #505F69; color: #F0F0F0;}" + "QPushButton[wsjtxState=\"idle\"] {background-color: #e1e1e1; color: #000000; " + "border-color: #adadad;}"}; + set_style_sheet_if_changed(ui->DX_Call_Button, dx_call_button_style); + + if (wait_and_call) { + set_button_style_state_if_changed(ui->DX_Call_Button, "active"); + } else if (wait_and_call_warning_eligible (waitContext)) { + set_button_style_state_if_changed(ui->DX_Call_Button, "warning"); + } else if (m_useDarkStyle) { + set_button_style_state_if_changed(ui->DX_Call_Button, "dark"); } else { - ui->DX_Call_Button->setChecked(false); - if (m_useDarkStyle) { - ui->DX_Call_Button->setStyleSheet("QPushButton {background-color: #505F69; color: #ffffff; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); - if (!m_auto) ui->autoButton->setStyleSheet("QPushButton {background-color: #505F69; color: #ffffff; border: 1px solid #32414B; color: #F0F0F0; border-radius: 5px; padding: 3px; outline: none; min-width: 5em;}"); - if (m_auto) ui->autoButton->setStyleSheet("QPushButton {background-color: #ff0000; color: #ffffff; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none; min-width: 5em;}"); - } else { - ui->DX_Call_Button->setStyleSheet("QPushButton {background-color: #9fafd5; border: none;}"); - if (!m_auto) { - ui->autoButton->setStyleSheet(""); - ui->autoButton->setStyleSheet("QPushButton {min-width: 5em;}"); - } - if (m_auto) ui->autoButton->setStyleSheet("QPushButton {background-color: #ff0000; color: #ffffff; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none; min-width: 5em;}"); - } + set_button_style_state_if_changed(ui->DX_Call_Button, "idle"); + } + + if (m_auto) { + set_style_sheet_if_changed(ui->autoButton, "QPushButton {background-color: #ff0000; color: #ffffff; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + } else if (EnableTxWarning::NONE != enableTxWarning) { + set_style_sheet_if_changed(ui->autoButton, "QPushButton {background-color: #ffff00; color: #000000; border: 1px solid #32414B; border-radius: 4px; padding: 3px; outline: none;}"); + } else if (m_useDarkStyle) { + set_style_sheet_if_changed(ui->autoButton, "QPushButton {background-color: #505F69; color: #ffffff; border: 1px solid #32414B; color: #F0F0F0; border-radius: 5px; padding: 3px; outline: none;}"); + } else { + set_style_sheet_if_changed(ui->autoButton, ""); } - ui->autoButton->setToolTip("Toggle Auto-Tx On/Off"); + auto const respondMode = ui->respondComboBox->currentText(); + auto const respondPolicy = autoRespondPolicy (); if (m_config.Wait_features_enabled()) { - ui->DX_Call_Button->setToolTip("Toggle Wait & Call On/Off.\n" - "Right-click to clear the DX Call box."); - ui->autoButton->setToolTip("Toggle Auto-Tx On/Off.\n" - "Right-click to toggle Wait & Pounce On/Off."); + if (waitAndCallEligible) { + ui->DX_Call_Button->setToolTip("Toggle Wait & Call On/Off.\n" + "Right-click to clear the DX Call box."); + } else if (!ui->cbAutoSeq->isChecked()) { + ui->DX_Call_Button->setToolTip("Wait & Call requires Auto-Seq.\n" + "Right-click to clear the DX Call box."); + } else if (!wait_and_call_mode_supported (m_mode) + || (SpecOp::HOUND == m_specOp && "FT8" != m_mode)) { + ui->DX_Call_Button->setToolTip("Wait & Call is unavailable in this mode.\n" + "Right-click to clear the DX Call box."); + } else if (SpecOp::NONE != m_specOp && SpecOp::HOUND != m_specOp) { + ui->DX_Call_Button->setToolTip("Wait & Call is unavailable for this special operation.\n" + "Right-click to clear the DX Call box."); + } else { + ui->DX_Call_Button->setToolTip("Enter a DX call to enable Wait & Call.\n" + "Right-click to clear the DX Call box."); + } } else { ui->DX_Call_Button->setToolTip("Right-click to clear the DX Call box"); - ui->autoButton->setToolTip("Toggle Auto-Tx On/Off"); } + + QString autoButtonToolTip {"Toggle Auto-Tx On/Off"}; + if (pounce) { + autoButtonToolTip = "Toggle Auto-Tx On/Off.\n" + "Wait & Pounce is On.\n" + "Right-click to turn Wait & Pounce Off."; + } else if (!m_auto && EnableTxWarning::HOUND_AUTO_REPLY == enableTxWarning) { + autoButtonToolTip = "Toggle Auto-Tx On/Off.\n" + "Hound mode can enable Auto-Tx when the selected Fox replies."; + } else if (!m_auto && EnableTxWarning::NCCC_SPRINT == enableTxWarning) { + autoButtonToolTip = "Toggle Auto-Tx On/Off.\n" + "NCCC Sprint can enable Auto-Tx when the selected station replies."; + } else if (!m_auto && EnableTxWarning::WAIT_AND_REPLY == enableTxWarning) { + autoButtonToolTip = "Toggle Auto-Tx On/Off.\n" + "Wait & Reply can enable Auto-Tx when the selected station replies."; + } else if (m_config.Wait_features_enabled()) { + if (respondPolicy == AutoRespondPolicy::None) { + autoButtonToolTip = "Toggle Auto-Tx On/Off.\n" + "Wait & Pounce requires a CQ response mode.\n" + "Change CQ: None to another option."; + } else if (m_auto) { + autoButtonToolTip = "Toggle Auto-Tx On/Off.\n" + "Turn Auto-Tx Off before enabling Wait & Pounce."; + } else if (SpecOp::FOX==m_specOp) { + autoButtonToolTip = "Toggle Auto-Tx On/Off.\n" + "Wait & Pounce is unavailable in Fox mode."; + } else { + autoButtonToolTip = QString {"Toggle Auto-Tx On/Off.\n" + "Right-click to enable Wait & Pounce using %1."}.arg(respondMode); + } + } + if (ui->cbAutoSeq->isChecked() + && AutoRespondPolicy::None != autoRespondPolicy()) { + autoButtonToolTip += "\nA direct caller may replace a pending CQ or QRZ."; + } + ui->autoButton->setToolTip(autoButtonToolTip); + ui->DX_Call_Button->setAccessibleDescription(ui->DX_Call_Button->toolTip()); + ui->autoButton->setAccessibleDescription(ui->autoButton->toolTip()); if (m_config.alternate_erase_button()) { ui->EraseButton->setToolTip("Left-click to erase left window.\n" "Right-click to erase right window."); @@ -16246,7 +16147,7 @@ void MainWindow::check_button_color() "Double-click to erase both windows."); } if (pounce && !m_auto) { - ui->autoButton->setStyleSheet("QPushButton {background-color: #ff7a05; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none; min-width: 5em;}"); + set_style_sheet_if_changed(ui->autoButton, "QPushButton {background-color: #ff7a05; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); ui->autoButton->setChecked(false); // ensure auoButton is unchecked } if (m_config.Territory1()=="") { @@ -16290,124 +16191,124 @@ void MainWindow::check_button_color() if (!m_config.button_coloring_disabled()) { if (m_mode=="Q65" && m_config.enable_VHF_features() && m_TRperiod==15 && m_nSubMode==0) { - ui->pb15A->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb15A, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb15A->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb15A, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb15A->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb15A, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (m_mode=="Q65" && m_config.enable_VHF_features() && m_TRperiod==15 && m_nSubMode==2) { - ui->pb15C->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb15C, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb15C->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb15C, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb15C->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb15C, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (m_mode=="Q65" && m_config.enable_VHF_features() && m_TRperiod==30 && m_nSubMode==1) { - ui->pb30B->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb30B, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb30B->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb30B, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb30B->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb30B, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (m_mode=="Q65" && m_config.enable_VHF_features() && m_TRperiod==60 && m_nSubMode==2) { - ui->pb60C->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb60C, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb60C->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb60C, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb60C->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb60C, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (m_mode=="Q65" && m_config.enable_VHF_features() && m_TRperiod==60 && m_nSubMode==3) { - ui->pb60D->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb60D, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb60D->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb60D, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb60D->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb60D, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (m_mode=="Q65" && m_config.enable_VHF_features() && m_TRperiod==60 && m_nSubMode==4) { - ui->pb60E->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb60E, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb60E->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb60E, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb60E->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb60E, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (ui->houndButton->isChecked() && !m_config.button_coloring_disabled()) { - ui->houndButton->setStyleSheet("QPushButton {background-color: #ff0000; color: #ffffff; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->houndButton, "QPushButton {background-color: #ff0000; color: #ffffff; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (SpecOp::FOX==m_specOp && !m_config.button_coloring_disabled()) { - ui->houndButton->setStyleSheet("QPushButton {background-color: #ffff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->houndButton, "QPushButton {background-color: #ffff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->houndButton->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->houndButton, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->houndButton->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->houndButton, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } } if (m_mode=="FT8") { - ui->ft8Button->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->ft8Button, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->ft8Button->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->ft8Button, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->ft8Button->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->ft8Button, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (m_mode=="FT4") { - ui->ft4Button->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->ft4Button, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->ft4Button->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->ft4Button, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->ft4Button->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->ft4Button, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (m_mode=="MSK144") { - ui->msk144Button->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->msk144Button, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->msk144Button->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->msk144Button, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->msk144Button->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->msk144Button, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (m_mode=="Q65") { - ui->q65Button->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->q65Button, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->q65Button->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->q65Button, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->q65Button->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->q65Button, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (m_mode=="JT65") { - ui->jt65Button->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->jt65Button, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->jt65Button->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->jt65Button, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->jt65Button->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->jt65Button, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (m_mode=="Echo" && ui->echoButton->isVisible()) { - ui->echoButton->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->echoButton, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->echoButton->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->echoButton, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->echoButton->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none; min-width: 3em;}"); + set_style_sheet_if_changed(ui->echoButton, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } } @@ -16417,16 +16318,16 @@ void MainWindow::check_button_color() ui->echoButton->setVisible (false); } if (m_mode=="JT65" && m_config.enable_VHF_features() && ui->cbShMsgs->isChecked()) { - ui->tx3->setStyleSheet("color: #000000; background-color: #66ffff"); - ui->tx4->setStyleSheet("color: #000000; background-color: #66ffff"); - if (!keepTx5) ui->tx5->setStyleSheet("color: #000000; background-color: #66ffff"); + set_style_sheet_if_changed(ui->tx3, "color: #000000; background-color: #66ffff"); + set_style_sheet_if_changed(ui->tx4, "color: #000000; background-color: #66ffff"); + if (!keepTx5) set_style_sheet_if_changed(ui->tx5, "color: #000000; background-color: #66ffff"); } else { - ui->tx3->setStyleSheet(""); - ui->tx4->setStyleSheet(""); - if (!keepTx5) ui->tx5->setStyleSheet(""); + set_style_sheet_if_changed(ui->tx3, ""); + set_style_sheet_if_changed(ui->tx4, ""); + if (!keepTx5) set_style_sheet_if_changed(ui->tx5, ""); } if (ui->actionBand_Buttons->isChecked()) { - QString band=m_config.bands()->find(m_freqNominal); + QString band=m_config.bands()->find(m_operatingFrequency.rx ()); if (ui->actionVHF_UHF_Buttons->isChecked()) { ui->pb160->setVisible(false); ui->pb80->setVisible(false); @@ -16455,120 +16356,120 @@ void MainWindow::check_button_color() ui->pb10G->setVisible(true); ui->pb24G->setVisible(true); if (band=="8m") { - ui->pb8->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb8, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb8->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb8, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb8->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb8, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="6m") { - ui->pb50->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb50, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb50->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb50, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb50->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb50, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="4m") { - ui->pb4->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb4, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb4->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb4, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb4->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb4, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="2m") { - ui->pb144->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb144, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb144->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb144, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb144->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb144, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="1.25m") { - ui->pb220->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb220, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb220->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb220, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb220->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb220, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="70cm") { - ui->pb432->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb432, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb432->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb432, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb432->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb432, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="33cm") { - ui->pb902->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb902, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb902->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb902, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb902->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb902, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="23cm") { - ui->pb23->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb23, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb23->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb23, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb23->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb23, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="13cm") { - ui->pb13->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb13, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb13->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb13, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb13->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb13, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="9cm") { - ui->pb9->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb9, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb9->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb9, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb9->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb9, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="6cm") { - ui->pb5G->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb5G, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb5G->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb5G, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb5G->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb5G, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="3cm") { - ui->pb10G->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb10G, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb10G->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb10G, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb10G->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb10G, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="1.25cm") { - ui->pb24G->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb24G, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb24G->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb24G, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb24G->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb24G, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } } else { @@ -16599,127 +16500,127 @@ void MainWindow::check_button_color() ui->pb10G->setVisible(false); ui->pb24G->setVisible(false); if (band=="160m") { - ui->pb160->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb160, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb160->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb160, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb160->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb160, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="80m") { - ui->pb80->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb80, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb80->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb80, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb80->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb80, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="60m") { - ui->pb60->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb60, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb60->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb60, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb60->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb60, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="40m") { - ui->pb40->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb40, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb40->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb40, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb40->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb40, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="30m") { - ui->pb30->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb30, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb30->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb30, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb30->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb30, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="20m") { - ui->pb20->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb20, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb20->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb20, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb20->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb20, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="17m") { - ui->pb17->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb17, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb17->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb17, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb17->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb17, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="15m") { - ui->pb15->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb15, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb15->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb15, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb15->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb15, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="12m") { - ui->pb12->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb12, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb12->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb12, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb12->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb12, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="10m") { - ui->pb10->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb10, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb10->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb10, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb10->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb10, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="6m") { - ui->pb6->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb6, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb6->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb6, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb6->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb6, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } if (band=="4m" or band=="1.25m" ) { - ui->pb2->setStyleSheet("QPushButton {background-color: #ffff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb2, "QPushButton {background-color: #ffff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (band=="2m") { - ui->pb2->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb2, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb2->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb2, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb2->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb2, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } } if (band=="23cm") { - ui->pb70->setStyleSheet("QPushButton {background-color: #ffff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb70, "QPushButton {background-color: #ffff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (band=="70cm") { - ui->pb70->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb70, "QPushButton {background-color: #00ff00; color: #000000; border: 1px solid #32414B; border-radius: 5px; padding: 3px; outline: none;}"); } else { if (m_useDarkStyle) { - ui->pb70->setStyleSheet("QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb70, "QPushButton {background-color: #505F69; border: 1px solid #32414B; color: #F0F0F0; border-radius: 4px; padding: 3px; outline: none;}"); } else { - ui->pb70->setStyleSheet("QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); + set_style_sheet_if_changed(ui->pb70, "QPushButton {background-color: #e1e1e1; border: 1px solid #adadad; border-radius: 0px; padding: 3px; outline: none;}"); } } } @@ -16752,526 +16653,62 @@ void MainWindow::check_button_color() ui->pb10G->setVisible(false); ui->pb24G->setVisible(false); } - if (ui->monitorButton->isChecked()) { - if (m_saveAll or m_saveDecoded) { - ui->monitorButton->setStyleSheet("QPushButton {background-color: #ffff00; color: #000000; border-style: outset; border-width: 1px; border-radius: 5px; border-color: black; min-width: 5em; padding: 3px;}"); - } else { - ui->monitorButton->setStyleSheet("QPushButton {background-color: #00ff00; color: #000000; border-style: outset; border-width: 1px; border-radius: 5px; border-color: black; min-width: 5em; padding: 3px;}"); - } - } else { - ui->monitorButton->setStyleSheet(""); - } + static QString const monitor_button_style { + "QPushButton {border: 1px solid palette(mid); border-radius: 5px; padding: 3px; " + "background-color: palette(button); color: palette(button-text);}" + "QPushButton[wsjtxState=\"active\"] {background-color: #00ff00; color: #000000; border-color: black;}" + "QPushButton[wsjtxState=\"saving\"] {background-color: #ffff00; color: #000000; border-color: black;}" + "QPushButton[wsjtxState=\"dark\"] {background-color: #505F69; color: #F0F0F0; border-color: #32414B;}" + "QPushButton:focus {border-color: palette(highlight);}" + "QPushButton:pressed {background-color: palette(midlight);}" + "QPushButton:disabled {color: palette(mid);}"}; + set_style_sheet_if_changed(ui->monitorButton, monitor_button_style); + set_button_style_state_if_changed(ui->monitorButton, + ui->monitorButton->isChecked() ? (m_saveAll or m_saveDecoded ? "saving" : "active") + : (m_useDarkStyle ? "dark" : "idle")); if (ui->pbBandHopping->isChecked()) { keep_last_tx_label = false; - ui->pbBandHopping->setStyleSheet("QPushButton {background-color: #ff0000; color: #ffffff; border-style: outset; border-width: 1px; border-radius: 5px; border-color: black; min-width: 5em; padding: 3px;}"); + set_style_sheet_if_changed(ui->pbBandHopping, "QPushButton {background-color: #ff0000; color: #ffffff; border-style: outset; border-width: 1px; border-radius: 5px; border-color: black; padding: 3px;}"); last_tx_label.setText(" Band Hopping On "); - last_tx_label.setStyleSheet ("QLabel{color: #ffffff; background-color: #ff0000}"); - ui->genStdMsgsPushButton->setStyleSheet("QPushButton {background-color: #ffff00; color: #000000; border-style: outset; border-width: 1px; border-radius: 5px; border-color: black; min-width: 5em; padding: 3px;}"); + set_style_sheet_if_changed(last_tx_label, "QLabel{color: #ffffff; background-color: #ff0000}"); + set_style_sheet_if_changed(ui->genStdMsgsPushButton, "QPushButton {background-color: #ffff00; color: #000000; border-style: outset; border-width: 1px; border-radius: 5px; border-color: black; padding: 3px;}"); } else { - ui->pbBandHopping->setStyleSheet (""); + set_style_sheet_if_changed(ui->pbBandHopping, ""); if (!keep_last_tx_label) last_tx_label.setText (""); - last_tx_label.setStyleSheet (""); - ui->genStdMsgsPushButton->setStyleSheet (""); + set_style_sheet_if_changed(last_tx_label, ""); + set_style_sheet_if_changed(ui->genStdMsgsPushButton, ""); } } -void MainWindow::on_pb160_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (1840000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(1837000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb80_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (3573000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(3576000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb60_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (5357000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(5357000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb40_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (7074000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(7077000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb30_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (10136000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(10139000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb20_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (14074000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(14077000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb17_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (18100000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(18103000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb15_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (21074000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(21077000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb12_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (24915000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(24918000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb10_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (28074000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(28077000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb6_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr6); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (50313000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(50316000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb2_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr2); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (144074000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(144077000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb70_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (432074000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(432077000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb8_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (40680000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(40680000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb50_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr6); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (50313000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(50316000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb4_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr6); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (70154000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(70154000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb144_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr2); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (144074000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(144077000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb220_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (222174000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(222177000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb432_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (432174000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(432177000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb902_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (902174000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(902177000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb23_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (1296065000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(1296065000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb13_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (2304065000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(2304065000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb9_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (3400065000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(3400065000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb5G_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (5760200000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(5760200000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb10G_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (10368200000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(10368200000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} -void MainWindow::on_pb24G_clicked() -{ - if (m_mode=="MSK144") { - ui->sbTR->setValue (m_msk144_tr); - programStart = true; - QTimer::singleShot (250, [=] {programStart = false;}); - } - auto const& row = m_config.frequencies ()->best_working_frequency (24048200000); - ui->bandComboBox->setCurrentIndex (row); - if (row >= 0) { - on_bandComboBox_activated (row); - } else { - keep_frequency = true; - setRig(24048200000); - QTimer::singleShot (250, [=] {keep_frequency = false;}); - } - setXIT (ui->TxFreqSpinBox->value ()); -} void MainWindow::read_txLog() { - static QFile logfile {QDir {QStandardPaths::writableLocation (QStandardPaths::DataLocation)}.absoluteFilePath ("wsjtx.log")}; + QFile logfile {writable_file_path (m_config.writeable_data_dir (), "wsjtx.log")}; QTextStream logstream(&logfile); if(logfile.open(QIODevice::ReadOnly | QIODevice::Text)) { while (!logstream.atEnd()) { @@ -17287,7 +16724,7 @@ void MainWindow::on_actionErase_Tx_Log_triggered() int ret = MessageBox::query_message (this, tr ("Confirm Erase"), tr ("Are you sure you want to erase the Tx Log?")); if(ret==MessageBox::Yes) { - static QFile logFile {QDir {QStandardPaths::writableLocation (QStandardPaths::DataLocation)}.absoluteFilePath ("wsjtx.log")}; + QFile logFile {writable_file_path (m_config.writeable_data_dir (), "wsjtx.log")}; logFile.remove(); txLog = ""; } @@ -17296,7 +16733,8 @@ void MainWindow::on_actionErase_Tx_Log_triggered() void MainWindow::addCallsignToignoreList() { if (m_hisCall!="") { - static QFile ignoreFile {QDir {QStandardPaths::writableLocation (QStandardPaths::DataLocation)}.absoluteFilePath ("ignore.list")}; + QFile ignoreFile {writable_file_path (m_config.writeable_data_dir (), "ignore.list")}; + ensure_parent_directory (ignoreFile.fileName ()); if(ignoreFile.open(QIODevice::Text | QIODevice::Append)) { QString ignoreEntry= (m_hisCall + ","); QTextStream out(&ignoreFile); @@ -17308,8 +16746,8 @@ void MainWindow::addCallsignToignoreList() #endif ; ignoreFile.close(); - QTimer::singleShot (2000, [=] {read_ignoreList();}); - QTimer::singleShot (7000, [=] {read_ignoreList();}); + QTimer::singleShot (2000, this, [=] {read_ignoreList();}); + QTimer::singleShot (7000, this, [=] {read_ignoreList();}); MessageBox::information_message (this, tr ("\"%1\" added to Ignore List").arg (m_hisCall)); } } @@ -17317,7 +16755,7 @@ void MainWindow::addCallsignToignoreList() void MainWindow::read_ignoreList() { - static QFile ignoreFile {QDir {QStandardPaths::writableLocation (QStandardPaths::DataLocation)}.absoluteFilePath ("ignore.list")}; + QFile ignoreFile {writable_file_path (m_config.writeable_data_dir (), "ignore.list")}; QTextStream ignoreStream(&ignoreFile); if(ignoreFile.open(QIODevice::ReadOnly | QIODevice::Text)) { while (!ignoreStream.atEnd()) { @@ -17333,7 +16771,7 @@ void MainWindow::on_actionErase_Ignore_List_triggered() int ret = MessageBox::query_message (this, tr ("Confirm Erase"), tr ("Are you sure you want to erase the Ignore List?")); if(ret==MessageBox::Yes) { - static QFile ignoreFile {QDir {QStandardPaths::writableLocation (QStandardPaths::DataLocation)}.absoluteFilePath ("ignore.list")}; + QFile ignoreFile {writable_file_path (m_config.writeable_data_dir (), "ignore.list")}; ignoreFile.remove(); ignoreList = ""; } @@ -17341,14 +16779,14 @@ void MainWindow::on_actionErase_Ignore_List_triggered() void MainWindow::read_ALLCALL7() { - static QFile AllCall7File {"ALLCALL7.TXT"}; + static QFile AllCall7File {m_decoderDataDir.absoluteFilePath ("ALLCALL7.TXT")}; QTextStream AllCall7Stream(&AllCall7File); if(AllCall7File.open(QIODevice::ReadOnly | QIODevice::Text)) { while (!AllCall7Stream.atEnd()) { ALLCALL7 = AllCall7Stream.readAll(); } - AllCall7Stream.flush(); - AllCall7File.close(); + AllCall7Stream.flush(); + AllCall7File.close(); } } @@ -17377,7 +16815,6 @@ void MainWindow::alertQSYmessage () { #ifdef WIN32 QAudioOutput info(QAudioDeviceInfo::defaultOutputDevice()); - QString binPath = QCoreApplication::applicationDirPath(); QAudioFormat format; format.setCodec("audio/pcm"); format.setSampleRate (48000); @@ -17388,11 +16825,603 @@ void MainWindow::alertQSYmessage () audio = new QAudioOutput(format, this); connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State))); QFile *effect1 = new QFile(this); - effect1->setFileName(QString("%1/%2").arg(binPath, "/sounds/Message.wav")); + effect1->setFileName (app_sounds_directory ().absoluteFilePath ("Message.wav")); + effect1->open(QIODevice::ReadOnly); + audio->start(effect1); +#else + QSound::play (app_sounds_directory ().absoluteFilePath ("Message.wav")); // for Linux and macOS +#endif +} + +void MainWindow::applyExperimentalFT8Filter(const DecodedText& decodedtext, bool& filtered) +{ + DecodeOutputPlan::ExperimentalFilterContext context; + context.mode = m_mode; + context.multithreadFt8 = m_multithreadFT8; + context.reduceFalseDecodes = ui->actionReduce_false_decodes->isChecked(); + context.allCallsigns = ALLCALL7; + context.alreadyFiltered = filtered; + filtered = DecodeOutputPlan::decideExperimentalFilter(decodedtext, context).filtered; +} + +void MainWindow::processFoxSignals(const DecodedText& decodedtext) +{ + if(m_mode=="FT8" and SpecOp::FOX == m_specOp and + (decodedtext.string().contains("R+") or decodedtext.string().contains("R-"))) { + auto for_us = decodedtext.string().contains(" " + m_config.my_callsign() + " ") or + decodedtext.string().contains(" "+m_baseCall) or + decodedtext.string().contains(m_baseCall+" ") or + decodedtext.string().contains(" <" + m_config.my_callsign() + "> "); + if(decodedtext.string().contains(" DE ")) for_us=true; + if(for_us) { + QString houndCall,houndGrid; + decodedtext.deCallAndGrid(/*out*/houndCall,houndGrid); + foxRxSequencer(decodedtext.string(),houndCall,houndGrid); + } + } +} + +void MainWindow::processSFoxVerification(const DecodedText& decodedtext0, bool& filtered) +{ +#ifdef FOX_OTP + if (SpecOp::HOUND == m_specOp) + { + // Payload formats (from column 24 onward): + // Standard: CALL.OTP e.g. "K8R.920749" + // SuperFox: $VERIFY$ CALL OTP e.g. "$VERIFY$ VP2X/K1JT 920749" + // Callsigns may include '/' and decoder output may contain variable spacing. + static const QRegularExpression stdPayloadRe{ + QStringLiteral("^([A-Z0-9]{2,6})\\.([0-9]{6})$")}; + static const QRegularExpression verifyPayloadRe{ + QStringLiteral("^\\$VERIFY\\$\\s+([A-Z0-9/]{2,13})\\s+([0-9]{6})$")}; + + QString const payload = decodedtext0.mid(24, -1).trimmed(); + QString callsign, otp; + unsigned int hz = 0; + + QRegularExpressionMatch payloadMatch = stdPayloadRe.match(payload); + if (payloadMatch.hasMatch()) { + callsign = payloadMatch.captured(1); + otp = payloadMatch.captured(2); + hz = static_cast<unsigned int>(decodedtext0.frequencyOffset()); + } else if (m_config.superFox() && + (payloadMatch = verifyPayloadRe.match(payload)).hasMatch()) { + callsign = payloadMatch.captured(1); + otp = payloadMatch.captured(2); + hz = 750; + } + + if (!callsign.isEmpty()) { + if (!m_config.ShowOTP() || otp == QLatin1String("000000")) + filtered = true; + + QDateTime verifyDateTime; + if (m_diskData) { + verifyDateTime = m_UTCdiskDateTime; + } else { + verifyDateTime = QDateTime(QDateTime::currentDateTimeUtc().date(), + QTime::fromString(decodedtext0.left(6), "hhmmss")); + } + if (otp != QLatin1String("000000")) { + FoxVerifier *fv = new FoxVerifier(http_user_agent (), + &m_network_manager, + m_config.OTPUrl(), + callsign, + verifyDateTime, + otp, + hz); + connect(fv, &FoxVerifier::verifyComplete, this, &MainWindow::handleVerifyMsg); + m_verifications << fv; + } + } + } +#endif +} + +DecodedMessageReaction::ReactionDisposition MainWindow::processWaitReplyCall( + DecodedText const& message, DecodedMessageReaction::WaitDecodeSource source, + bool * block_right_display) +{ + if (m_hisCall.isEmpty()) return DecodedMessageReaction::ReactionDisposition::NoReaction; + + bool const waitFeaturesEnabled = m_config.Wait_features_enabled(); + WaitFeatureContext const waitContext { + m_mode, + m_specOp, + waitFeaturesEnabled, + ui->cbAutoSeq->isChecked(), + !m_hisCall.isEmpty(), + m_config.NCCC_Sprint() + }; + bool eligible = false; + if (source == DecodedMessageReaction::WaitDecodeSource::SlowDecoder) { + bool const slowMode = slow_wait_feature_mode_supported (m_mode); + bool const nccc = nccc_sprint_auto_reply (waitContext); + bool const waitReply = waitFeaturesEnabled && !ui->autoButton->isChecked(); + bool const waitCall = wait_and_call && wait_and_call_arming_eligible (waitContext) + && !no_wait_and_call; + eligible = slowMode && (nccc || waitReply || waitCall); + } else { + bool const waitReply = waitFeaturesEnabled && !ui->autoButton->isChecked(); + bool const waitCall = wait_and_call && wait_and_call_arming_eligible (waitContext); + eligible = m_mode == "MSK144" + && (waitReply || waitCall || ui->DX_Call_Button->isChecked()); + } + if (!eligible) return DecodedMessageReaction::ReactionDisposition::NoReaction; + + auto const plan = DecodedMessageReaction::planWaitReplyCall( + message, qsoReactionSnapshot(), source); + applyQsoReactionPlan(plan, message, block_right_display); + return plan.disposition; +} +bool MainWindow::applyFiltering(const DecodedText& decodedtext, bool& filtered) +{ + DecodeOutputPlan::KeywordFilterContext keywordContext; + keywordContext.mode = m_mode; + keywordContext.specOp = m_specOp; + keywordContext.alreadyFiltered = filtered; + keywordContext.filterBySecondWord = m_config.filters_for_word2(); + keywordContext.alwaysPass = m_config.AlwaysPass(); + keywordContext.passKeywords = m_config.pass_keywords(); + keywordContext.blacklistEnabled = m_config.Blacklisted(); + keywordContext.blacklistKeywords = m_config.blacklist_keywords(); + keywordContext.whitelistEnabled = m_config.Whitelisted(); + keywordContext.whitelistKeywords = m_config.whitelist_keywords(); + keywordContext.waitAndPounceOnly = m_config.filters_for_Wait_and_Pounce_only(); + keywordContext.bypass = ui->cbBypass->isChecked(); + keywordContext.pounce = pounce; + keywordContext.respondPolicy = autoRespondPolicy (); + auto const keywordDecision = DecodeOutputPlan::decideKeywordFilter(decodedtext, keywordContext); + filtered = keywordDecision.filtered; + if (keywordDecision.resetPounceScores) m_autoRespondScores.reset(); + if (!keywordDecision.continueProcessing) return false; + + DecodeOutputPlan::VisibilityFilterContext visibilityContext; + visibilityContext.alreadyFiltered = filtered; + visibilityContext.alwaysPassed = keywordDecision.alwaysPassed; + visibilityContext.bypass = keywordContext.bypass; + visibilityContext.hideTerritory1 = ui->actionHideTerritory1->isChecked(); + visibilityContext.hideTerritory2 = ui->actionHideTerritory2->isChecked(); + visibilityContext.hideTerritory3 = ui->actionHideTerritory3->isChecked(); + visibilityContext.hideTerritory4 = ui->actionHideTerritory4->isChecked(); + visibilityContext.territory1 = m_config.Territory1(); + visibilityContext.territory2 = m_config.Territory2(); + visibilityContext.territory3 = m_config.Territory3(); + visibilityContext.territory4 = m_config.Territory4(); + visibilityContext.hideWorkedBefore = ui->actionHideB4->isChecked(); + visibilityContext.hideEurope = ui->actionHideEU->isChecked(); + visibilityContext.hideAsia = ui->actionHideAS->isChecked(); + visibilityContext.hideNorthAmerica = ui->actionHideNA->isChecked(); + visibilityContext.hideSouthAmerica = ui->actionHideSA->isChecked(); + visibilityContext.hideAfrica = ui->actionHideAF->isChecked(); + visibilityContext.hideOceania = ui->actionHideOC->isChecked(); + visibilityContext.hideAntarctica = ui->actionHideAN->isChecked(); + visibilityContext.hideIgnored = ui->actionHideIgnored->isChecked(); + visibilityContext.ignoreList = ignoreList; + visibilityContext.hideWorkedToday = ui->actionHideToday->isChecked(); + visibilityContext.includeYesterday = m_config.twoDays(); + visibilityContext.txLog = txLog; + if (visibilityContext.hideWorkedToday) { + visibilityContext.today = QDateTime::currentDateTimeUtc().toString("yyyy-MM-dd"); + visibilityContext.yesterday = QDateTime::currentDateTimeUtc().addDays(-1).toString("yyyy-MM-dd"); + } + visibilityContext.countryName = [this] (QString const& deCall) { + return m_logBook.countries()->lookup(deCall).abbreviated_entity_name; + }; + visibilityContext.continent = [this] (QString const& deCall) { + return AD1CCty::continent(m_logBook.countries()->lookup(deCall).continent); + }; + visibilityContext.workedBeforeOnBand = [this] (QString const& deCall, QString const& deGrid) { + bool callWorked {false}; + bool countryWorked; + bool gridWorked; + bool continentWorked; + bool cqZoneWorked; + bool ituZoneWorked; + auto const& lookedUp = m_logBook.countries()->lookup(deCall); + m_logBook.match(deCall, m_mode, deGrid, lookedUp, callWorked, countryWorked, + gridWorked, continentWorked, cqZoneWorked, ituZoneWorked, m_currentBand); + return callWorked; + }; + filtered = DecodeOutputPlan::decideVisibilityFilter(decodedtext, visibilityContext).filtered; + return true; +} + +void MainWindow::applyHighlighting(const DecodedText& decodedtext, DisplayText * decodePane, bool updateAlertState, + bool& play_Wanted, bool& play_DXcall) +{ + if (!decodePane) return; + + QString text = decodedtext.string().replace("<","").replace(">",""); + if(ui->actionHighlightB4->isChecked() or ui->actionHighlightToday->isChecked() or ui->actionHighlightIgnored->isChecked() + or ui->actionHighlightTerritory1->isChecked() or ui->actionHighlightTerritory2->isChecked() + or ui->actionHighlightTerritory3->isChecked() or ui->actionHighlightTerritory4->isChecked()) { + QString today = QDateTime::currentDateTimeUtc().toString ("yyyy-MM-dd"); + QString yesterday = QDateTime::currentDateTimeUtc().addDays(-1).toString ("yyyy-MM-dd"); + QString deCall; + QString deGrid; + decodedtext.deCallAndGrid(/*out*/deCall,deGrid); + bool callB4onBand; + bool countryB4onBand; + bool gridB4onBand; + bool continentB4onBand; + bool CQZoneB4onBand; + bool ITUZoneB4onBand; + if (ui->actionHighlightB4->isChecked()) { + auto const& looked_up = m_logBook.countries ()->lookup (deCall); + m_logBook.match (deCall, m_mode, deGrid, looked_up, callB4onBand, countryB4onBand, gridB4onBand, + continentB4onBand, CQZoneB4onBand, ITUZoneB4onBand, m_currentBand); + if (callB4onBand) decodePane->highlight_callsign(deCall, QColor(195,195,195), QColor(0,0,0), true); + } + if (ui->actionHighlightToday->isChecked() && ( + txLog.contains(QRegularExpression{today + ",[0-9][0-9]:[0-9][0-9]:[0-9][0-9]," + (deCall + ",")}) + or (m_config.twoDays() && txLog.contains(QRegularExpression{yesterday + ",[0-9][0-9]:[0-9][0-9]:[0-9][0-9]," + (deCall + ",")})))) { + decodePane->highlight_callsign(deCall, QColor(100,100,100), QColor(255,255,0), true); + } + if (ui->actionHighlightIgnored->isChecked() && ignoreList.contains(deCall + ",")) { + decodePane->highlight_callsign(deCall, QColor(85,0,0), QColor(255,255,0), true); + } + if (ui->actionHighlightTerritory1->isChecked() or ui->actionHighlightTerritory2->isChecked() or + ui->actionHighlightTerritory3->isChecked() or ui->actionHighlightTerritory4->isChecked()) { + auto const& looked_up = m_logBook.countries ()->lookup (deCall); + auto countryName = looked_up.abbreviated_entity_name; + if (ui->actionHighlightTerritory1->isChecked() && countryName.contains(m_config.Territory1()) + && (m_config.Territory1()!="") && !ui->cbBypass->isChecked()) decodePane->highlight_callsign(deCall, QColor(115,43,245), QColor(255,255,255), true); + if (ui->actionHighlightTerritory2->isChecked() && countryName.contains(m_config.Territory2()) + && (m_config.Territory2()!="") && !ui->cbBypass->isChecked()) decodePane->highlight_callsign(deCall, QColor(115,43,245), QColor(255,255,255), true); + if (ui->actionHighlightTerritory3->isChecked() && countryName.contains(m_config.Territory3()) + && (m_config.Territory3()!="") && !ui->cbBypass->isChecked()) decodePane->highlight_callsign(deCall, QColor(115,43,245), QColor(255,255,255), true); + if (ui->actionHighlightTerritory4->isChecked() && countryName.contains(m_config.Territory4()) + && (m_config.Territory4()!="") && !ui->cbBypass->isChecked()) decodePane->highlight_callsign(deCall, QColor(115,43,245), QColor(255,255,255), true); + } + } + + // highlight orange and blue callsigns + if (m_config.highlight_orange() or (m_config.highlight_blue()) or ui->actionHighlight_Whitelist_entries->isChecked()) { + QString deCall; + QString deGrid; + decodedtext.deCallAndGrid(/*out*/deCall,deGrid); + if (m_config.highlight_orange() && deCall.size()>2 + && HighlightingRules::matchesCallsignPrefix(m_config.highlight_orange_callsigns(), deCall)) { + decodePane->highlight_callsign(deCall, QColor(225,75,0), QColor(255,255,255), true); + if (updateAlertState && m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted) play_Wanted = true; + } + if (m_config.highlight_orange() && deGrid.size()>3 && m_config.highlight_orange_callsigns().contains(deGrid)) { + decodePane->highlight_callsign(deGrid, QColor(225,75,0), QColor(255,255,255), true); + if (updateAlertState && m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted) play_Wanted = true; + } + if (m_config.highlight_blue() && deCall.size()>2 + && HighlightingRules::matchesCallsignPrefix(m_config.highlight_blue_callsigns(), deCall)) { + decodePane->highlight_callsign(deCall, QColor(0,100,255), QColor(255,255,255), true); + if (updateAlertState && m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted) play_Wanted = true; + } + if (m_config.highlight_blue() && deGrid.size()>3 && m_config.highlight_blue_callsigns().contains(deGrid)) { + decodePane->highlight_callsign(deGrid, QColor(0,100,255), QColor(255,255,255), true); + if (updateAlertState && m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted) play_Wanted = true; + } + // highlight directional calls + QStringList tw; + if (m_mode == "FT8" or m_mode == "FT4" or m_mode == "Q65" or m_mode == "FST4") { + tw=text.mid(24).split(" ",SkipEmptyParts); + } else { + tw=text.mid(22).split(" ",SkipEmptyParts); + } + if (tw.size() > 2) { + if (m_config.highlight_orange() && tw[0]=="CQ" + && HighlightingRules::matchesDirectionalCall(m_config.highlight_orange_callsigns(), tw[1])) { + decodePane->highlight_callsign(tw[1], QColor(225,75,0), QColor(255,255,255), true); + if (updateAlertState && m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted && tw[1]!="") play_Wanted = true; + } + if (m_config.highlight_blue() && tw[0]=="CQ" + && HighlightingRules::matchesDirectionalCall(m_config.highlight_blue_callsigns(), tw[1])) { + decodePane->highlight_callsign(tw[1], QColor(0,100,255), QColor(255,255,255), true); + if (updateAlertState && m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted && tw[1]!="") play_Wanted = true; + } + } + // highlight Whitelist entries + if (ui->actionHighlight_Whitelist_entries->isChecked() && deCall.size()>2 && + MessageFilter::containsAny(deCall, m_config.whitelist_keywords())) { + decodePane->highlight_callsign(deCall, QColor(170,0,127), QColor(255,255,255), true); + if (updateAlertState && m_config.alert_Enabled() && m_config.alert_Wanted() && !m_muted) play_Wanted = true; + } + } + + // Highlight DX Call/Grid + if (!pounce && (m_config.highlight_DXcall() or (updateAlertState && m_config.alert_Enabled())) && (m_hisCall != "") && + ((decodedtext.string().contains(QRegularExpression{"(\\w+) " + m_hisCall})) + || (decodedtext.string().contains(QRegularExpression{"(\\w+) <" + m_hisCall + ">"})) + || (decodedtext.string().contains(QRegularExpression{"<(\\w+)> " + m_hisCall})) + || (decodedtext.string().contains(QRegularExpression{"<...> " + m_hisCall})))) { + if (updateAlertState && m_config.alert_Enabled() && m_config.alert_DXcall() && !m_muted) play_DXcall = true; + if (m_config.highlight_DXcall()) { + decodePane->highlight_callsign(m_hisCall, QColor(255,0,0), QColor(255,255,255), true); + if (updateAlertState) { + auto pane = QPointer<DisplayText> {decodePane}; + auto call = m_hisCall; + // Repeated highlighting keeps the Band Activity marking visible when external clients update it. + QTimer::singleShot (500, this, [pane, call] {if (pane) pane->highlight_callsign(call, QColor(255,0,0), QColor(255,255,255), true);}); + QTimer::singleShot (1000, this, [pane, call] {if (pane) pane->highlight_callsign(call, QColor(255,0,0), QColor(255,255,255), true);}); + QTimer::singleShot (2500, this, [pane, call] {if (pane) pane->highlight_callsign(call, QColor(255,0,0), QColor(255,255,255), true);}); + } + } + } + if (!pounce && (m_config.highlight_DXgrid () or (updateAlertState && m_config.alert_Enabled())) && (m_hisGrid!="") && + (decodedtext.string().contains(m_hisGrid.left(4)))) { + if (m_config.highlight_DXgrid()) decodePane->highlight_callsign(m_hisGrid.left(4), QColor(0,0,200), QColor(255,255,255), true); + if (updateAlertState && m_config.alert_Enabled() && m_config.alert_DXcall() && !m_muted) play_DXcall = true; + } +} + +void MainWindow::playDecodeAlertSound(bool play_Wanted, bool play_DXcall) +{ + QTimer::singleShot (100, this, [this, play_Wanted, play_DXcall] { + auto const sound = selectDecodeAlertSound(m_config.alert_Enabled(), m_config.alert_DXcall(), m_config.alert_Wanted(), + play_Wanted, play_DXcall, !m_hisCall.isEmpty()); + playDecodeAlertSound(sound); + }); +} + +void MainWindow::playDecodeAlertSound(DecodeAlertSound sound) +{ + if (sound == DecodeAlertSound::None) return; + +#ifdef WIN32 + QAudioOutput info(QAudioDeviceInfo::defaultOutputDevice()); + QString audioPath = m_config.voice_directory ().absolutePath (); + QAudioFormat format; + format.setCodec("audio/pcm"); + format.setSampleRate (48000); + format.setChannelCount (1); + format.setSampleSize (16); + format.setSampleType(QAudioFormat::SignedInt); + QAudioOutput* audio; + audio = new QAudioOutput(format, this); + connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State))); + QFile *effect1 = new QFile(this); + if (sound == DecodeAlertSound::DXcall) effect1->setFileName(QString("%1/%2").arg(audioPath, "DXcall.wav")); + else if (sound == DecodeAlertSound::Wanted) effect1->setFileName(QString("%1/%2").arg(audioPath, "Wanted.wav")); effect1->open(QIODevice::ReadOnly); audio->start(effect1); #else - QString binPath = QCoreApplication::applicationDirPath(); - QSound::play(binPath + "/sounds/Message.wav"); // for Linux and macOS + if (sound == DecodeAlertSound::DXcall) QSound::play (m_config.voice_directory ().absoluteFilePath ("DXcall.wav")); // for Linux and macOS + else if (sound == DecodeAlertSound::Wanted) QSound::play (m_config.voice_directory ().absoluteFilePath ("Wanted.wav")); // for Linux and macOS +#endif +} + +MainWindow::DecodeAlertSound MainWindow::selectDecodeAlertSound(bool alertsEnabled, bool dxCallAlertEnabled, + bool wantedAlertEnabled, bool play_Wanted, + bool play_DXcall, bool hasDXCall) +{ + if (!alertsEnabled) return DecodeAlertSound::None; + if (dxCallAlertEnabled && play_DXcall && hasDXCall) return DecodeAlertSound::DXcall; + if (wantedAlertEnabled && play_Wanted) return DecodeAlertSound::Wanted; + return DecodeAlertSound::None; +} + +void MainWindow::updateRespondTarget(const DecodedText& decodedtext, const QString& text, bool pounce, + QDateTime const& decodePeriodStart, bool diskData) +{ + bool const fullDuplexBlocked = ui->actionFull_Duplex_Mode->isChecked() && m_txing; + bool const currentPeriodCaller = !diskData + && !filtered + && !ignored + && !fullDuplexBlocked + && m_autoRespondPeriodState.accepts(decodePeriodStart) + && isDirectAutoRespondCandidate(decodedtext, m_config.my_callsign()); + auto const periodPolicy = m_autoRespondPeriodState.policy(); + auto const pouncePolicy = autoRespondPolicy (); + bool const pounceCq = pounce + && text.contains(" CQ ") + && m_config.Wait_features_enabled(); + + bool const selectPounceFirst = pounceCq + && !filtered + && !ignored + && !fullDuplexBlocked + && !m_autoRespondSelectionLatch.isSelected() + && ui->respondComboBox->isVisible() + && pouncePolicy == AutoRespondPolicy::First; + bool const selectCurrentFirst = currentPeriodCaller + && AutoRespondPolicy::First == periodPolicy + && m_autoRespondPeriodState.claimFirst(decodePeriodStart); + if (selectPounceFirst || selectCurrentFirst) { + m_bDoubleClicked=true; + if (selectPounceFirst) m_autoRespondSelectionLatch.selectFor(); + auto_tx_mode(true); + processSyntheticMessage(decodedtext); + auto now = QDateTime::currentDateTimeUtc(); + m_dateTimeQSOOn = now.addSecs (-(m_ntx - 1) * int(m_TRperiod) - int(fmod(double(now.time().second()),m_TRperiod))); + if (pounce) stopWCTimer.start(int(6200.0*m_TRperiod)); + } + + QString deCall; + QString deGrid; + decodedtext.deCallAndGrid(/*out*/deCall,deGrid); + + bool const selectPounceDistance = pounceCq + && !filtered + && !ignored + && !fullDuplexBlocked + && !txLog.contains(deCall) + && deGrid.contains(MainWindow::grid_regexp) + && ui->respondComboBox->isVisible() + && pouncePolicy == AutoRespondPolicy::MaxDistance; + bool const selectCurrentDistance = currentPeriodCaller + && AutoRespondPolicy::MaxDistance == periodPolicy; + if (selectPounceDistance || selectCurrentDistance) { + double utch=0.0; + int nAz,nEl,nDmiles,nDkm,nHotAz,nHotABetter; + azdist_(const_cast <char *> ((m_config.my_grid () + " ").left (6).toLatin1().constData()), + const_cast <char *> ((deGrid + " ").left (6).toLatin1().constData()),&utch, + &nAz,&nEl,&nDmiles,&nDkm,&nHotAz,&nHotABetter,6,6); + int distancePoints=nDkm; + if (!deGrid.contains(MainWindow::grid_regexp)) distancePoints=1; + if(m_autoRespondScores.considerDistance(distancePoints)) { + m_deCall=deCall; + m_bDoubleClicked=true; + auto_tx_mode(true); + processSyntheticMessage(decodedtext); + if (pounce) stopWCTimer.start(int(6200.0*m_TRperiod)); + ui->dxCallEntry->setText(deCall); + genStdMsgs(QString::number(decodedtext.snr())); + ui->RxFreqSpinBox->setValue(decodedtext.frequencyOffset()); + setTxMsg(m_ntx); + m_currentMessageType=m_ntx; + auto now = QDateTime::currentDateTimeUtc(); + m_dateTimeQSOOn = now.addSecs (-(m_ntx - 1) * int(m_TRperiod) - int(fmod(double(now.time().second()),m_TRperiod))); + } + } + + bool const selectPounceMaximum = pounceCq + && !filtered + && !ignored + && !fullDuplexBlocked + && !txLog.contains(deCall) + && ui->respondComboBox->isVisible() + && pouncePolicy == AutoRespondPolicy::MaxSignal; + bool const selectCurrentMaximum = currentPeriodCaller + && AutoRespondPolicy::MaxSignal == periodPolicy; + if ((selectPounceMaximum || selectCurrentMaximum) + && m_autoRespondScores.considerMaximumDb(decodedtext.snr())) { + m_deCall=deCall; + m_bDoubleClicked=true; + auto_tx_mode(true); + processSyntheticMessage(decodedtext); + if (pounce) stopWCTimer.start(int(6200.0*m_TRperiod)); + ui->dxCallEntry->setText(deCall); + genStdMsgs(QString::number(decodedtext.snr())); + ui->RxFreqSpinBox->setValue(decodedtext.frequencyOffset()); + setTxMsg(m_ntx); + m_currentMessageType=m_ntx; + auto now = QDateTime::currentDateTimeUtc(); + m_dateTimeQSOOn = now.addSecs (-(m_ntx - 1) * int(m_TRperiod) - int(fmod(double(now.time().second()),m_TRperiod))); + } + + bool const selectPounceMinimum = pounceCq + && !filtered + && !ignored + && !fullDuplexBlocked + && !txLog.contains(deCall) + && ui->respondComboBox->isVisible() + && pouncePolicy == AutoRespondPolicy::MinSignal; + bool const selectCurrentMinimum = currentPeriodCaller + && AutoRespondPolicy::MinSignal == periodPolicy; + if ((selectPounceMinimum || selectCurrentMinimum) + && m_autoRespondScores.considerMinimumDb(decodedtext.snr())) { + m_deCall=deCall; + m_bDoubleClicked=true; + auto_tx_mode(true); + processSyntheticMessage(decodedtext); + if (pounce) stopWCTimer.start(int(6200.0*m_TRperiod)); + ui->dxCallEntry->setText(deCall); + genStdMsgs(QString::number(decodedtext.snr())); + ui->RxFreqSpinBox->setValue(decodedtext.frequencyOffset()); + setTxMsg(m_ntx); + m_currentMessageType=m_ntx; + auto now = QDateTime::currentDateTimeUtc(); + m_dateTimeQSOOn = now.addSecs (-(m_ntx - 1) * int(m_TRperiod) - int(fmod(double(now.time().second()),m_TRperiod))); + } +} + +void MainWindow::processSuperHoundVerification(const DecodedText& decodedtext0) +{ + if (isHoundOperation () && decodedtext0.mid(3,18).contains(" verified")) { + m_houndVerified = true; + write_all("Vf",decodedtext0.string()); + } else { +#ifndef FOX_OTP + if (isSuperHoundOperation () && (decodedtext0.mid(4,2).contains("00") or decodedtext0.mid(4,2).contains("30"))) m_houndVerified = false; #endif + } + updateHoundVerificationStyle (); +} + +QString MainWindow::calculateDistanceAndBearing(const DecodedText& decodedtext) +{ + QString distance; + QString deCall; + QString deGrid; + decodedtext.deCallAndGrid(deCall,deGrid); + if ((m_config.showDistance() || m_config.showAzimuth()) && deGrid.contains(MainWindow::grid_regexp)) { + double utch=0.0; + int nAz,nEl,nDmiles,nDkm,nHotAz,nHotABetter; + QString my_Grid = m_config.my_grid(); + if (my_Grid.length() < 5) my_Grid = m_config.my_grid().left(4)+"mm"; + QString de_Grid= deGrid.left(4)+"mm"; + azdist_(const_cast <char *> (my_Grid.toLatin1().constData()), + const_cast <char *> (de_Grid.toLatin1().constData()),&utch, + &nAz,&nEl,&nDmiles,&nDkm,&nHotAz,&nHotABetter,(FCL)6,(FCL)6); + if (m_config.showDistance()) { + int nd=nDkm; + if(m_config.miles()) nd=nDmiles; + distance = QString::number(nd); + if(m_config.miles()) distance += " mi"; + if(!m_config.miles()) distance += " km"; + } + if (m_config.showAzimuth()) { + if (distance.length()) distance += " / "; + distance += QString::number(nAz) + "°"; + } + } + return distance; +} + +void MainWindow::displayDecodedTextLine(const DecodedText& decodedtext, const QByteArray& line_read, const QString& distance, bool haveFSpread, float fSpread, bool bDisplayPoints) +{ + bool displayed; + if ((m_mode == "JT65" or m_mode == "JT9" or m_mode == "JT4") && m_config.DXCC()) { + DecodedText decodedtextJT {((QString::fromUtf8(line_read.left(44).constData())) + (QString::fromUtf8(line_read.mid(62, 2).constData())))}; + displayed = ui->decodedTextBrowser->displayDecodedText ( + decodedtextJT, m_config.my_callsign (), m_mode, m_config.DXCC (), + m_logBook, m_currentBandPeriod, m_config.ppfx (), + ui->cbCQonly->isVisible() && ui->cbCQonly->isChecked(), + haveFSpread, fSpread, bDisplayPoints, m_points, distance, m_muted); + } else { + if (ui->actionHide_AP_info->isVisible() && ui->actionHide_AP_info->isChecked()) { + // Hide FT8 AP information + QByteArray line = line_read; + DecodedText decodedtext2 {(QString::fromUtf8(line.replace("a1","").replace("a2","").replace("a3","").replace("a4","") + .replace("a5","").replace("a6","").replace("a7","").replace("a8","").replace("a9","").replace("?","")))}; + displayed = ui->decodedTextBrowser->displayDecodedText ( + decodedtext2, m_config.my_callsign (), m_mode, m_config.DXCC (), + m_logBook, m_currentBandPeriod, m_config.ppfx (), + ui->cbCQonly->isVisible() && ui->cbCQonly->isChecked(), + haveFSpread, fSpread, bDisplayPoints, m_points, distance, m_muted); + } else { + displayed = ui->decodedTextBrowser->displayDecodedText ( + decodedtext, m_config.my_callsign (), m_mode, m_config.DXCC (), + m_logBook, m_currentBandPeriod, m_config.ppfx (), + ui->cbCQonly->isVisible() && ui->cbCQonly->isChecked(), + haveFSpread, fSpread, bDisplayPoints, m_points, distance, m_muted); + } + } + if (displayed) + { + Q_EMIT decodedMessageDisplayed (decodedtext.message ().simplified ()); + } +} + +void MainWindow::set_mode_from_command_line(const QString& mode, bool lock_mode) +{ + QString m = mode.toLower(); + if (m == "ft8") { + on_actionFT8_triggered(); + } else if (m == "ft4") { + on_actionFT4_triggered(); + } else if (m == "jtty") { + on_actionJTTY_triggered(); + } else { + LOG_INFO("Invalid or unsupported mode specified via command line: " << mode); + } + + if (lock_mode) { + m_modeLocked = true; + ui->menuMode->setEnabled(false); + ui->ft8Button->setEnabled(false); + ui->ft4Button->setEnabled(false); + ui->msk144Button->setEnabled(false); + ui->q65Button->setEnabled(false); + ui->jt65Button->setEnabled(false); + ui->houndButton->setEnabled(false); + } } diff --git a/widgets/mainwindow.h b/widgets/mainwindow.h index 7aee7db6..fdc0d444 100644 --- a/widgets/mainwindow.h +++ b/widgets/mainwindow.h @@ -12,31 +12,51 @@ #include <QProgressBar> #include <QTimer> #include <QDateTime> +#include <QElapsedTimer> +#include <QMap> +#include <QRegExp> +#include <QRegularExpression> #include <QList> #include <QAudioDeviceInfo> #include <QStringList> #include <QScopedPointer> #include <QDir> -#include <QProgressDialog> #include <QAbstractSocket> #include <QHostAddress> #include <QPointer> #include <QSet> +#include <QHash> #include <QVector> #include <QScrollBar> +#include <QTextBlock> #include <QQueue> #include <QFuture> +#include <QFutureSynchronizer> #include <QFutureWatcher> #include <QDateTime> +#include <array> +#include <initializer_list> +#include <memory> + +class QHBoxLayout; #include "MultiGeometryWidget.hpp" #include "NonInheritingProcess.hpp" #include "Audio/AudioDevice.hpp" +#include "Audio/TxIdentity.hpp" +#include "Audio/TxPlaybackDiagnostics.hpp" +#include "Audio/TxPlaybackEvidence.hpp" +#include "Audio/TxRequest.hpp" +#include "Audio/WavLoadCoordinator.hpp" #include "commons.h" +#include "FastDecode.hpp" +#include "ReferenceSpectrum.hpp" #include "Radio.hpp" +#include "OperatingFrequency.hpp" #include "models/Modes.hpp" #include "models/FrequencyList.hpp" #include "Configuration.hpp" +#include "JttyN1mmOutput.hpp" #include "WSPR/WSPRBandHopping.hpp" #include "Transceiver/Transceiver.hpp" #include "DisplayManual.hpp" @@ -44,11 +64,24 @@ #include "Network/Cloudlog.hpp" #include "logbook/logbook.h" #include "astro.h" +#include "qtextbrowser.h" #include "widgets/QSYMessageCreator.h" #include "widgets/QSYMessage.h" +#include "widgets/displaytext.h" #include "widgets/qsymonitor.h" #include "MessageBox.hpp" #include "Network/NetworkAccessManager.hpp" +#include "AutoRespondSelectionLatch.hpp" +#include "AutoRespondScoring.hpp" +#include "AutoRespondPeriod.hpp" +#include "HoundTransmissionPolicy.hpp" +#include "JttyDraftAcceptanceTracker.hpp" +#include "QsoProgress.hpp" +#include "DecodeOperatingContext.hpp" +#include "DecoderOutputFramer.hpp" +#include "Ft8MtdDecodeCoordinator.hpp" +#include "RigFrequencyChangePolicy.hpp" +#include "BeaconTxController.hpp" #define NUM_JT4_SYMBOLS 206 //(72+31)*2, embedded sync #define NUM_JT65_SYMBOLS 126 //63 data + 63 sync @@ -74,7 +107,15 @@ namespace Ui { class MainWindow; } +class QWidget; +class QRadioButton; +struct QMapDecodeRecord; +class QFocusFrame; +class QFrame; +class QButtonGroup; + class QProcessEnvironment; +class QPaintEvent; class QSharedMemory; class QSplashScreen; class QSettings; @@ -99,14 +140,32 @@ class EQSL; class WSPRNet; class SoundOutput; class Modulator; -class SoundInput; +class AudioInputSource; class Detector; class SampleDownloader; class MultiSettings; + +namespace DecodedMessageReaction +{ + enum class ContestHint; + enum class ReactionDisposition; + enum class SelectionOrigin; + enum class WaitDecodeSource; + struct QsoReactionEffect; + struct QsoReactionPlan; + struct QsoReactionSnapshot; +} class EqualizationToolsDialog; class DecodedText; class Cloudlog; +#include "Audio/TxAudioQueue.hpp" +#include "Modulator/JttyTxStream.hpp" + +#ifdef WIN32 +class MMTTYIF; +#endif + class MainWindow : public MultiGeometryWidget<3, QMainWindow> { @@ -118,28 +177,128 @@ public: using Mode = Modes::Mode; using SpecOp = Configuration::SpecialOperatingActivity; + enum class JttyTxRejectReason + { + Empty, + EncodingFailed, + QueueFull, + BackendRejected, + Aborted, + NotAvailable + }; + Q_ENUM(JttyTxRejectReason) + + static QRegExp const message_alphabet; + static QRegularExpression const grid_regexp; + static QRegularExpression const non_r_db_regexp; + explicit MainWindow(QDir const& temp_directory, bool multiple, MultiSettings *, QSharedMemory *shdmem, unsigned downSampleFactor, - QSplashScreen *, QProcessEnvironment const&, + QSplashScreen *, QProcessEnvironment const&, bool automated_test, + QString base_style_sheet, + std::unique_ptr<AudioInputSource> audio_input_source = {}, + std::unique_ptr<SoundOutput> sound_output = {}, + QString decoder_data_path = {}, QWidget *parent = nullptr); ~MainWindow(); - int decoderBusy () const {return m_decoderBusy;} +#ifdef WIN32 + void initMMTTY(quint16 port); + MMTTYIF *getMmttyIf() const; +#endif + + bool decoderBusy () const + {return m_fastDecodePending || DecodeOwner::None != m_decodeOwner || m_ft8MtdDecodeCoordinator.hasPending ();} + void set_mode_from_command_line(const QString& mode, bool lock_mode = false); + bool decoderBackendRunning () const; + bool diskDataActive () const {return m_diskData;} + bool monitoringActive () const {return m_monitoring;} +#if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) + struct LiveAudioTestFt8TransmitRequest + { + qint64 session_id {-1}; + qint64 generation {-1}; + }; + + bool liveAudioTestMultithreadedFt8Enabled () const {return m_multithreadFT8;} + int liveAudioTestFt8ThreadCount () const {return m_ft8threads;} + int liveAudioTestDecodeDepth () const {return m_ndepth & 7;} + int liveAudioTestFt8Cycles () const {return m_nFT8Cycles;} + int liveAudioTestFt8Sensitivity () const {return m_ft8Sensitivity;} + int liveAudioTestFt8DecoderStart () const {return m_ft8DecoderStart;} + QString liveAudioTestFt8BackpressureDiagnostics () const; + static constexpr int liveAudioTestDecodeLowFrequency () {return 200;} + static constexpr int liveAudioTestDecodeHighFrequency () {return 3000;} + bool configureLiveAudioTestDecodeRange (); + bool prepareLiveAudioTestFt8InputCompletion (); + QString completeLiveAudioTestFt8Input (qint64 frames); + bool configureLiveAudioTestHandoff (); + quint64 liveAudioTestPublishedDecoderGeneration () const + { + return m_automated_test && DecodeOwner::Jt9 == m_decodeOwner + && m_activeJt9Decode.generation == m_nextDecoderGeneration + ? m_activeJt9Decode.generation : 0; + } + quint64 liveAudioTestDecodeCycleGeneration () const {return m_decodeCycleGeneration;} + quint64 liveAudioTestReceiveEpoch () const {return m_receiveConsumer.epoch ();} + bool liveAudioTestReceivingAudio () const {return m_receivingAudio;} + LiveAudioTestFt8TransmitRequest startLiveAudioTestFt8Transmit ( + qint64 targetPeriodStartMs); +#endif -public slots: + Q_SIGNALS: + void decoderBackendStarted () const; + void decoderBackendFailed (QString reason) const; + void decodeCycleStarted (quint64 generation) const; + void decodeCycleCompleted (quint64 generation) const; + void decodeCycleAborted (quint64 generation) const; +#if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) + void ft8DecoderInvocation (bool multithreaded, int threadCount, int depth, + int cycles, bool subpass, int decoderStart, + int halfSymbols, int sampleCount, + int lowFrequency, int highFrequency) const; + void decoderOutputLine (QByteArray line) const; + void liveAudioTestJttyFramesConsumed (qint64 frames) const; + void liveAudioTestReceiveRejected (qint64 notifiedFrames) const; + void liveAudioTestReceiveRange (quint64 epoch, int start, int end, bool accepted) const; + void liveAudioTestReceiveBlock (ReceiveAudio block) const; + void liveAudioTestReceiveCallback (qint64 notifiedFrames, + qint64 currentFrames, + qint16 observedLastSample) const; + void liveAudioTestFt8TransmitStartDecided (qint64 sessionId, + qint64 generation, + qint64 targetPeriodStartMs, + bool accepted, + qint64 actualStartMs) const; +#endif + void decodedMessageProcessed (QString message) const; + void decodedMessageDisplayed (QString message) const; + void jttyTextAccepted(qint64 requestId) const; + void jttyTextRejected(qint64 requestId, JttyTxRejectReason reason) const; + void jttyTextCompleted(qint64 requestId) const; + void jttySessionDrained(qint64 sessionId) const; + + public slots: void showSoundInError(const QString& errorMsg); void showSoundOutError(const QString& errorMsg); void showStatusMessage(const QString& statusMsg); + // JTTY text submission is asynchronous. The returned request id is completed + // by accepted/rejected signals; accepted means queued for backend transmit, + // not finished on RF. Graceful external OFF commands should stop submitting + // new text and let the JTTY drain path stop TX; use abort_jtty_tx() for hard + // abort. + qint64 submitJttyText(QString message); + void updateJttyDecodeHeadings(); void dataSink(qint64 frames); void fastSink(qint64 frames); void tci_mod_active(bool on) {m_tci_mod_active = on;} void diskDat(); void freezeDecode(int n); void guiUpdate(); - void doubleClickOnCall (Qt::KeyboardModifiers); - void doubleClickOnCall2(Qt::KeyboardModifiers); - void doubleClickOnFoxQueue(Qt::KeyboardModifiers); - void doubleClickOnFoxInProgress(Qt::KeyboardModifiers modifiers); + void doubleClickOnCall (QString const& line, QString const& word, Qt::KeyboardModifiers); + void doubleClickOnCall2(QString const& line, QString const& word, Qt::KeyboardModifiers); + void doubleClickOnFoxQueue(QString const& line, QString const& word, Qt::KeyboardModifiers); + void doubleClickOnFoxInProgress(QString const& line, QString const& word, Qt::KeyboardModifiers modifiers); void readFromStdout(); void p1ReadFromStdout(); void setXIT(int n, Frequency base = 0u); @@ -147,14 +306,63 @@ public slots: void msgAvgDecode2(); void fastPick(int x0, int x1, int y); void skedFreq(double sf); + void jttyDecodeAgainAt(float secondsAgo); private: + enum class DecodeOwner + { + None, + Jt9, + Wsprd + }; + + enum class DecodeEndState + { + Completed, + Aborted + }; + + enum class Jt9ProcessPhase + { + InitialStarting, + Ready, + StopRequested, + Terminating, + Killing, + ReplacementStarting, + Closing + }; + + enum class DecodePublishResult + { + Published, + Unavailable, + Failed + }; + + struct ActiveJt9Decode + { + qint32 generation {0}; + DecodeOperatingContext context; + bool copiedSamples {false}; + bool obsolete {false}; + Ft8MtdDecodeCoordinator::Stage ft8Stage {Ft8MtdDecodeCoordinator::Stage::None}; + qint64 ft8Period {-1}; + }; + + static constexpr int MaxActiveStationRows = 50; + // Keep this matched with MAX_CALLERS in the Q65 q3list Fortran helpers. + static constexpr int MaxQ65PileupCallers = 50; + void change_layout (std::size_t) override; void keyPressEvent (QKeyEvent *) override; void closeEvent(QCloseEvent *) override; + void paintEvent(QPaintEvent *) override; void childEvent(QChildEvent *) override; bool eventFilter(QObject *, QEvent *) override; void showQSYMessage(QString message); + void save_wave_file(QString const& name, int samples, Frequency frequency, + QString const& dgrd); private slots: void initialize_fonts (); @@ -189,10 +397,11 @@ private slots: void on_pb10G_clicked(); void on_pb24G_clicked(); void check_button_color(); + void reset_transmit_controls_after_stop (); void stopWRTimeout(); void stopWCTimeout(); void bandHoppingTimer(); - void bandHopping(); + void bandHopping(bool user_requested = false); void on_houndButton_clicked(bool checked); void on_cbHoldTxFreq_clicked (bool); void on_ft8Button_clicked(); @@ -227,7 +436,6 @@ private slots: void on_actionQSG_Q65_triggered(); void on_actionQSG_X250_M3_triggered(); void on_actionQuick_Start_Guide_to_WSJT_X_2_7_and_QMAP_triggered(); - void on_actionRecommended_Audio_Settings_triggered(); void on_actionOnline_User_Guide_triggered(); void on_actionLocal_User_Guide_triggered(); void on_actionWide_Waterfall_triggered(); @@ -246,10 +454,10 @@ private slots: void on_actionSpecial_mouse_commands_triggered(); void on_actionSolve_FreqCal_triggered(); void on_actionCopyright_Notice_triggered(); + void on_actionTrademark_Policy_triggered(); void on_actionSWL_Mode_triggered (bool checked); void on_DecodeButton_clicked (bool); void decode(); - void decodeBusy(bool b); void on_EraseButton_clicked(); void band_activity_cleared (); void rx_frequency_activity_cleared (); @@ -302,6 +510,7 @@ private slots: void on_actionFST4_triggered(); void on_actionFST4W_triggered(); void on_TxFreqSpinBox_valueChanged(int arg1); + void on_TxFreqSpinBox_2_valueChanged(int arg1); void on_actionSave_decoded_triggered(); void on_actionQuickDecode_toggled (bool); void on_actionMediumDecode_toggled (bool); @@ -337,7 +546,6 @@ private slots: void on_actionStartLate_toggled(bool checked); void on_actionFT8WidebandDXCallSearch_toggled(bool checked); void on_actionUse_multithreaded_FT8_decoder_triggered(bool checked); - //ft8md void bumpFqso(int n); void on_actionErase_ALL_TXT_triggered(); @@ -346,15 +554,17 @@ private slots: void on_actionErase_WSPR_hashtable_triggered(); void on_actionErase_list_of_Q65_callers_triggered(); void on_actionExport_Cabrillo_log_triggered(); - void startTx2(); + bool startTx2(); void startP1(); void stopTx(); void stopTx2(); void on_rptSpinBox_valueChanged(int n); - void killFile(); + void killWaveFile(); void on_tuneButton_clicked (bool); void on_pbR2T_clicked(); + void on_pbR2T_2_clicked(); void on_pbT2R_clicked(); + void on_pbT2R_2_clicked(); void acceptQSO (QDateTime const&, QString const& call, QString const& grid , Frequency dial_freq, QString const& mode , QString const& rpt_sent, QString const& rpt_received @@ -370,9 +580,11 @@ private slots: void on_bandComboBox_activated (int index); void on_readFreq_clicked(); void on_RxFreqSpinBox_valueChanged(int n); + void on_RxFreqSpinBox_2_valueChanged(int n); void on_outAttenuation_valueChanged (int); void rigOpen (); void handle_transceiver_update (Transceiver::TransceiverState const&); + void handle_transceiver_closing (bool failed); void handle_transceiver_failure (QString const& reason); void handle_leavingSettings(); void on_actionAstronomical_data_toggled (bool); @@ -382,6 +594,9 @@ private slots: void on_actionShort_list_of_add_on_prefixes_and_suffixes_triggered(); void band_changed (Frequency); void monitor (bool); + void applyMonitorEffects (bool checked, bool restored); + void applyOperatingFrequencyTransition (OperatingFrequency::Transition const&); + OperatingFrequency::Context operatingFrequencyContext () const; void end_tuning (); void stop_tuning (); void stopTuneATU(); @@ -402,8 +617,8 @@ private slots: void on_cbSWL_toggled(bool b); void on_cbTx6_toggled(bool b); void on_cbMenus_toggled(bool b); - void on_cbCQonly_toggled(bool b); void on_cbAutoSeq_toggled(bool b); + void on_cbIncludeTime_toggled(bool b); void networkError (QString const&); void on_ClrAvgButton_clicked(); void on_actionWSPR_triggered(); @@ -429,10 +644,12 @@ private slots: void on_sbTR_valueChanged (int); void on_sbTR_FST4W_valueChanged (int); void on_sbFtol_valueChanged (int); + void on_sbFtol_2_valueChanged (int); void on_cbFast9_clicked(bool b); void on_sbCQTxFreq_valueChanged(int n); void on_cbCQTx_toggled(bool b); void on_actionMSK144_triggered(); + void on_actionJTTY_triggered(); void on_actionQ65_triggered(); void on_actionFreqCal_triggered(); void splash_done (); @@ -446,16 +663,16 @@ private slots: void on_pbFreeText_clicked(); void FoxReset(QString reason); void on_comboBoxHoundSort_activated (int index); - void not_GA_warning_message (); void checkMSK144ContestType(); void on_pbBestSP_clicked(); - void on_RoundRobin_currentTextChanged(QString text); + void on_RoundRobin_currentTextChanged(QString); void setTxMsg(int n); bool stdCall(QString const& w); void remote_configure (QString const& mode, quint32 frequency_tolerance, QString const& submode , bool fast_mode, quint32 tr_period, quint32 rx_df, QString const& dx_call , QString const& dx_grid, bool generate_messages); void callSandP2(int nline); + void qmapCallSandP(QMapDecodeRecord const& record, bool doubleClick); void refreshHoundQueueDisplay(); void queueActiveWindowHound2(QString text); void update_tx5(const QString &qsy_text); @@ -465,6 +682,62 @@ private slots: void on_rbEchoMessage_toggled(bool b); void on_rbEchoCW_toggled(bool b); void on_leEchoMessage_textChanged(); + void on_pbSendMessage_clicked(); + void on_Tx_Message_returnPressed(); + + void on_pbF1_clicked(); + void on_pbF2_clicked(); + void on_pbF3_clicked(); + void on_pbF4_clicked(); + void on_pbF5_clicked(); + void on_pbF6_clicked(); + void on_pbF7_clicked(); + void on_pbF8_clicked(); +#ifdef WIN32 + void logText(const QString &text); +#endif + +private: + enum class FrequencyRequestOrigin + { + User, + Automatic + }; + + enum class DecodeAlertSound { None, DXcall, Wanted }; + + struct Q65StationSelection + { + QString call; + QString grid; + QString submode; + QString report; + bool txFirst; + }; + + void applyExperimentalFT8Filter(const DecodedText& dt, bool& filtered); + void applyQ65StationSelection (Q65StationSelection const& selection); + void processFoxSignals(const DecodedText& dt); + void processSFoxVerification(const DecodedText& dt, bool& filtered); + DecodedMessageReaction::ReactionDisposition processWaitReplyCall( + DecodedText const& dt, DecodedMessageReaction::WaitDecodeSource source, + bool * block_right_display = nullptr); + bool applyFiltering(const DecodedText& dt, bool& filtered); + void applyHighlighting(const DecodedText& dt, DisplayText * decodePane, bool updateAlertState, + bool& play_Wanted, bool& play_DXcall); + void cycleRespondMode(); + static DecodeAlertSound selectDecodeAlertSound(bool alertsEnabled, bool dxCallAlertEnabled, bool wantedAlertEnabled, + bool play_Wanted, bool play_DXcall, bool hasDXCall); + void playDecodeAlertSound(bool play_Wanted, bool play_DXcall); + void playDecodeAlertSound(DecodeAlertSound sound); + void updateRespondTarget(const DecodedText& dt, const QString& text, bool pounce, + QDateTime const& decodePeriodStart, bool diskData); + QString selectedTxMessage() const; + AutoRespondPolicy autoRespondPolicy() const; + bool pendingCqAutoRespondIntent() const; + void displayDecodedTextLine(const DecodedText& dt, const QByteArray& line_read, const QString& distance, bool haveFSpread, float fSpread, bool bDisplayPoints); + QString calculateDistanceAndBearing(const DecodedText& dt); + void processSuperHoundVerification(const DecodedText& dt); private: Q_SIGNAL void initializeAudioOutputStream (QAudioDeviceInfo, @@ -475,6 +748,7 @@ private: unsigned downSampleFactor, AudioDevice::Channel) const; Q_SIGNAL void suspendAudioInputStream () const; Q_SIGNAL void resumeAudioInputStream () const; + Q_SIGNAL void stopAudioInputStream () const; Q_SIGNAL void startDetector (AudioDevice::Channel) const; Q_SIGNAL void FFTSize (unsigned) const; Q_SIGNAL void detectorClose () const; @@ -482,17 +756,27 @@ private: Q_SIGNAL void transmitFrequency (double) const; Q_SIGNAL void endTransmitMessage (bool quick = false) const; Q_SIGNAL void tune (bool = true) const; - Q_SIGNAL void sendMessage (QString mode, unsigned symbolsLength, - double framesPerSymbol, double frequency, double toneSpacing, - SoundOutput *, AudioDevice::Channel = AudioDevice::Mono, - bool synchronize = true, bool fastMode = false, double dBSNR = 99., - int TRperiod=60) const; + Q_SIGNAL void sendMessage (TxEvidence::TxRequest, SoundOutput *) const; + Q_SIGNAL void startJttyStream (TxEvidence::TxRequest, SoundOutput *); + Q_SIGNAL void endJttyStream () const; Q_SIGNAL void outAttenuationChanged (qreal) const; Q_SIGNAL void toggleShorthand () const; Q_SIGNAL void reset_audio_input_stream (bool report_dropped_frames) const; private: void set_mode (QString const& mode); + void dispatchTxRequest (TxEvidence::TxRequest const& request); + void beginTxEvidenceSession (); + void beginTxEvidenceGeneration (qint64 committedEndSample = -1, + bool targetKnown = false); + void recordTxSourceCommit (TxEvidence::TxStartSnapshot const& snapshot); + void recordRawTxPlayout (TxEvidence::TxRawPlayoutSnapshot const& snapshot); + void noteTxStopReason (TxEvidence::TxStopReason reason); + void noteTxModeChange (QString const& mode); + int txStopTailMs (bool tciAudio) const; + void stopTxEvidence (int tailMs); + void captureJttyTxEvidenceTotals (qint64 servedSamples, qint64 totalSamples, + QString const& diagnostic); void astroUpdate (); void writeAllTxt(QString message); void auto_sequence (DecodedText const& message, unsigned start_tolerance, unsigned stop_tolerance); @@ -501,29 +785,117 @@ private: void setColorHighlighting(); void chkFT4(); bool elide_tx1_not_allowed () const; + void toggle_tx1_enabled_preference (); + bool rr73_tx4_allowed () const; + bool send_rr73_for_tx4 () const; + void set_rr73_tx4 (bool enabled); void readWidebandDecodes(); void configActiveStations(); - void sfox_tx(); + bool sfox_tx(); + void clearSuperFoxPreparedTx(); + void abortSuperFoxTxStart(); + void displayFoxTxMsgs(); + void jtty_tx(QString message); + void submitJttyDraft(QString message); +#ifdef WIN32 + void handleMmttyTxString(QString message); + void handleMmttyStartTx(); + void handleMmttyStopTx(); + void handleMmttyAbortTx(); + void handleMmttyJttyAccepted(qint64 requestId); + void handleMmttyJttyRejected(qint64 requestId, JttyTxRejectReason reason); + void handleMmttyJttyCompleted(qint64 requestId); + void handleMmttyJttySessionDrained(qint64 sessionId); + void completeMmttyJttyOutput(bool drained = false); + void startPendingMmttyJttyTx(); + QString jttyRejectReasonText(JttyTxRejectReason reason) const; +#endif + void execute_jtty_tx(qint64 requestId, QString message); + void execute_jtty_tones(qint64 requestId, QString const& message, + int const itone[], int nsym); + void advanceJttyTxQueueEpoch(); + qint64 jttyTxCommittedSamples() const; + void completeJttyTxEnqueue(qint64 requestId, QString const& message, + TxAudioQueueProgress progress, bool newSession, + bool useTciAudio); + void recordAcceptedJttyTextRequest(qint64 requestId, qint64 endSample); + QVector<qint64> takeCompletedJttyTextRequests(TxAudioQueueEpoch epoch, + qint64 totalAtDrain); + void clearAcceptedJttyTextRequests(TxAudioQueueEpoch epoch); + void handleJttyContestSerial(QString const& message); + void abort_jtty_tx(); + void interruptJttyTx(); + void rejectPendingJttyTciMessages(JttyTxRejectReason reason); + void sync_tci_tx_volume (bool force = false); + void onJttyBackendDrained(TxAudioQueueDrainState drain); + void onJttyBackendEnqueueAccepted(qint64 enqueueId, qint64 sampleCount, + TxAudioQueueProgress progress); + void onJttyBackendEnqueueFailed(TxAudioQueueEpoch epoch, qint64 enqueueId); + void handleJttyTxWatchdog(); + void resetJttyTxState(); + void startJttyTxWatchdog(int durationMs); + void jtty_save_wav(); + bool jtty_key_struck(QKeyEvent * e); + bool sendJttyFunctionKey(int index); + // istart0/istop (sample indices into dec_data.d2) bound the Fortran scan + // to a window instead of the whole buffer; -1/-1 (the default) means + // unwindowed, matching the original behavior exactly. Returns true when + // this call delivers a completed message admitted to the QSO history. + bool jtty_decode(int k, int istart0 = -1, int istop = -1); + void renderJttyAllFreqLines(); + void renderJttyQsoLines(); + void jtty_again(); + void flushJttyDecodeLines(); + QString jtty_msg_expand(QString msg); + QString specOpLabel() const; + void initializeFFT(int nsps); + void initializeFFT(int nsps, int fftSize); + void setTxButtonsEnabled(bool enabled); + void setDXInfo(QString const& call, QString const& grid); + void setDecodeTitles(QString const& lh, QString const& rh); + void setDecodeHeadings(QString const& lh, QString const& rh); + void updateDecodeAccessibility(); + bool play_DXcall = false; bool play_Wanted = false; bool inSettings = false; + quint64 m_startup_trace_run {0}; + bool m_startup_paint_reported {false}; + bool m_startup_decoder_reported {false}; + bool m_startup_audio_reported {false}; + bool m_startup_logbook_reported {false}; + bool m_startup_rig_reported {false}; + bool m_event_filter_ready {false}; QProcessEnvironment const& m_env; NetworkAccessManager m_network_manager; bool m_valid; QSplashScreen * m_splash; QString m_revision; bool m_multiple; + bool m_automated_test; MultiSettings * m_multi_settings; QPushButton * m_configurations_button; QSettings * m_settings; + QString m_base_style_sheet; QScopedPointer<Ui::MainWindow> ui; + QButtonGroup * m_tx_message_button_group {nullptr}; + QFocusFrame * m_main_window_focus_frame {nullptr}; + QFrame * m_message_selector_focus_frame {nullptr}; + bool m_keyboard_focus_active {false}; + bool m_tx_first_user_enabled {true}; + bool m_tx_first_mode_enabled {true}; + +#ifdef WIN32 + MMTTYIF * m_mmttyif {nullptr}; +#endif Configuration m_config; + QDir m_decoderDataDir; LogBook m_logBook; // must be after Configuration construction Cloudlog m_cloudlog; WSPRBandHopping m_WSPR_band_hopping; - bool m_WSPR_tx_next; + BeaconTx::Controller m_beaconTxController; MessageBox m_rigErrorMessageBox; QScopedPointer<SampleDownloader> m_sampleDownloader; QScopedPointer<EqualizationToolsDialog> m_equalizationToolsDialog; @@ -554,8 +926,11 @@ private: Detector * m_detector; unsigned m_FFTSize; - SoundInput * m_soundInput; + AudioInputSource * m_soundInput; + quint64 m_decodeCycleGeneration {0}; Modulator * m_modulator; + QScopedPointer<TxAudioQueue> m_jttyTxQueue; + JttyTxStream * m_jttyTxStream; SoundOutput * m_soundOutput; int m_rx_audio_buffer_frames; int m_tx_audio_buffer_frames; @@ -568,11 +943,9 @@ private: qint64 m_fullFoxCallTime; qint64 m_msEchoTxStart=0; - Frequency m_freqNominal; + OperatingFrequency m_operatingFrequency; Frequency m_freqNominalPeriod; - Frequency m_freqTxNominal; - quint64 m_msk144basefreq; - quint64 m_msk144oldfreq; + Frequency m_msk144basefreq {0}; quint64 m_mslastTX; //ft8md qint32 m_nlasttx; //ft8md qint32 m_lapmyc; //ft8md @@ -581,11 +954,11 @@ private: double m_tRemaining; double m_TRperiod; - double m_fSpread; + double m_fSpread {0.}; double m_s6; - double m_fDither; - double m_fAudioShift; - double m_skedFreq; + double m_fDither {0.}; + double m_fAudioShift {0.}; + double m_skedFreq {1296.065}; float m_DTtol; float m_t0; @@ -614,12 +987,12 @@ private: qint32 m_ft8DecoderStart; qint32 m_nsecBandChanged; qint32 m_nFT4depth; + qint32 m_nsym_jtty; //ft8md qint32 m_sec0; qint32 m_RxLog; qint32 m_nutc0; - qint32 m_ntr; qint32 m_tx; quint64 m_mslastMon; int m_addtx; @@ -660,8 +1033,7 @@ private: qint32 m_maxFoxWait=3; //Max wait time for expected Hound replies qint32 m_foxCQtime=10; //CQs at least every 5 minutes qint32 m_tFoxTxSinceCQ=999; //Fox Tx cycles since most recent CQ - qint32 m_nFoxFreq; //Audio freq at which Hound received a call from Fox - qint32 m_nSentFoxRrpt=0; //Serial number for next R+rpt Hound will send to Fox + HoundTransmissionPolicy::State m_houndTransmissionState; qint32 m_kin0=0; qint32 m_earlyDecode=41; qint32 m_earlyDecode2=47; @@ -674,15 +1046,50 @@ private: qint32 m_echoSec0=0; qint32 m_fetched=0; qint32 m_position; + qint64 m_decoderDiagSequence=0; + qint64 m_decoderDiagActiveSequence=0; + qint32 m_nextDecoderGeneration=0; + qint32 m_decoderDiagStartIhsym=0; + qint32 m_decoderDiagStartHsymStop=0; + qint32 m_decoderDiagStartNzhsym=0; + qint32 m_decoderDiagStartNewdat=0; + qint32 m_decoderDiagStartNagain=0; + qint32 m_decoderDiagStartNdiskdat=0; + qint32 m_decoderDiagProgressCount=0; + double m_decoderDiagStartTRperiod=0.0; + QElapsedTimer m_decoderDiagElapsedTimer; + QElapsedTimer m_decoderDiagProgressTimer; + QString m_decoderDiagStartMode; + QMap<QString, QDateTime> m_decoderDiagLastSampleUtc; bool m_btxok; //True if OK to transmit bool m_diskData; bool m_loopall; - bool m_decoderBusy; + DecodeOwner m_decodeOwner=DecodeOwner::None; + Jt9ProcessPhase m_jt9ProcessPhase=Jt9ProcessPhase::InitialStarting; + bool m_modeLocked = false; + bool m_decoderDiagActive=false; + bool m_decoderDiagBusyRequestLogged=false; + bool m_decoderDiagOverrunLogged=false; + bool m_decoderDiagHardHangLogged=false; + bool m_decoderDiagAbnormalClear=false; + bool m_decoderCompletedSinceStart=false; + bool m_jt9PayloadValid=false; + bool m_closing=false; bool m_txFirst; + bool m_tx1_enabled_preference {true}; bool m_auto; bool m_restart; + bool m_generated_message_error; bool m_startAnother; + ActiveJt9Decode m_activeJt9Decode; + DecoderOutputFramer m_decoderOutputFramer; + Ft8MtdDecodeCoordinator m_ft8MtdDecodeCoordinator; +#if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) + qint64 m_liveAudioTestPendingFt8FinalPeriod {-1}; + bool m_liveAudioTestAwaitFt8InputCompletion {false}; + bool m_liveAudioTestFt8InputComplete {false}; +#endif // start ft8md bool m_FT8EarlyStart; @@ -711,7 +1118,6 @@ private: bool m_dataAvailable; bool m_bDecoded; bool m_noSuffix; - bool m_decodedText2; bool m_sentFirst73; bool m_tci_mod_active; bool m_tci; @@ -724,16 +1130,13 @@ private: bool m_bShMsgs; bool m_bSWL; bool m_uploadWSPRSpots; - bool m_uploading; bool m_grid6; - bool m_tuneup; bool m_bTxTime; - bool m_rxDone; bool m_bSimplex; // not using split even if it is available bool m_bEchoTxOK; bool m_bTransmittedEcho; bool m_bEchoTxed; - bool m_bFastMode; + bool m_bFastMode=false; bool m_bFast9; bool m_bFastDecodeCalled; bool m_bDoubleClickAfterCQnnn; @@ -748,26 +1151,24 @@ private: bool m_bCallingCQ; bool m_bAutoReply; QString m_lastloggedcall; //ft8md - bool m_bCheckedContest; + bool m_contestModeHintShown; bool m_bWarnedSplit=false; bool m_bTUmsg; bool m_bBestSPArmed=false; bool m_bOK_to_chk=false; bool m_bSentReport=false; bool m_discard_decoded_hounds_this_cycle=false; // if something changes, like frequency, discard decoded messages that may be in-flight. + bool m_houndVerified=false; SpecOp m_specOp; - enum - { - CALLING, - REPLYING, - REPORT, - ROGER_REPORT, - ROGERS, - SIGNOFF - } - m_QSOProgress; //State machine counter + static constexpr QsoProgress CALLING {QsoProgress::Calling}; + static constexpr QsoProgress REPLYING {QsoProgress::Replying}; + static constexpr QsoProgress REPORT {QsoProgress::Report}; + static constexpr QsoProgress ROGER_REPORT {QsoProgress::RogerReport}; + static constexpr QsoProgress ROGERS {QsoProgress::Rogers}; + static constexpr QsoProgress SIGNOFF {QsoProgress::Signoff}; + QsoProgress m_QSOProgress; enum {CALL, GRID, DXCC, MULT}; @@ -787,6 +1188,7 @@ private: // labels in status bar QLabel tx_status_label; + bool m_tx_inhibited {false}; QLabel config_label; QLabel mode_label; QLabel last_tx_label; @@ -795,10 +1197,24 @@ private: QLabel ndecodes_label; QProgressBar progressBar; QLabel watchdog_label; - - QFuture<void> m_wav_future; - QFutureWatcher<void> m_wav_future_watcher; - QFutureWatcher<void> watcher3; + QLabel * m_txFrequencyLabel {}; + QLabel * m_frequencyToleranceLabel {}; + QLabel * m_rxFrequencyLabel {}; + QLabel * m_reportLabel {}; + QLabel * m_trPeriodLabel {}; + QLabel * m_submodeLabel {}; + QLabel * m_maxDriftLabel {}; + QHBoxLayout * m_frequencyToleranceRow {}; + QHBoxLayout * m_modeCheckboxRow {}; + WavLoadCoordinator m_wav_load_coordinator; + QFutureWatcher<FastDecodeResult> watcher3; + bool m_fastDecodePending = false; + ReferenceSpectrumInput m_referenceInput; + ReceiveAudioConsumer m_receiveConsumer; + QQueue<ReceiveAudio> m_receiveQueue; + ReceiveAudio m_activeReceiveAudio; + bool m_receivingAudio = false; + QFutureSynchronizer<QString> m_saveWAVSynchronizer; QFutureWatcher<QString> m_saveWAVWatcher; NonInheritingProcess proc_jt9; @@ -812,6 +1228,10 @@ private: EQSL *Eqsl; QTimer m_guiTimer; + QTimer m_decoderShutdownTimer; + QTimer m_decoderTerminateTimer; + QTimer m_decoderKillTimer; + QTimer m_decoderStartTimer; QTimer stopWRTimer; //Wait & Reply QTimer stopWCTimer; //Wait & Call QTimer ptt1Timer; //StartTx delay @@ -819,12 +1239,19 @@ private: QTimer logQSOTimer; QTimer killFileTimer; QTimer tuneButtonTimer; + QTimer rigTuneTimer; QTimer uploadTimer; QTimer tuneATU_Timer; QTimer TxAgainTimer; QTimer minuteTimer; QTimer splashTimer; QTimer p1Timer; + QTimer m_jttyTxWatchdog; + QTimer m_refSpecTimer; + AutoRespondSelectionLatch m_autoRespondSelectionLatch; + AutoRespondScores m_autoRespondScores; + AutoRespondPeriodState m_autoRespondPeriodState; + int m_refSpecSecondsRemaining = 0; QString m_path; QString m_baseCall; @@ -835,7 +1262,6 @@ private: QString m_palette; QString m_dateTime; QString m_mode; - QString m_modeTx;//ft8md QString m_fnameWE; // save path without extension QString m_rpt; QString m_nextRpt; @@ -864,8 +1290,13 @@ private: QString m_deGrid; QString m_freeTextMsg; QString m_freeTextMsg0; - QString m_ready2call[50]; - QString m_callers[50]; + std::array<QString, MaxActiveStationRows> m_ready2call; + std::array<QString, MaxQ65PileupCallers> m_callers; + // Q65 Pileup mode: selected DX call whose last Tx was copied by a decode. + // The value is consumed by the next matching Q65 Tx message. + QString m_q65PileupCopiedLastRxCall; + // Q65 Pileup mode: callers whose latest decode carried the copied flag ('#'); a standing display annotation, cleared only on leaving the Pileup context, not per decode pass. + QSet<QString> m_q65PileupCopiedCallers; QSet<QString> m_pfx; QSet<QString> m_sfx; @@ -959,13 +1390,77 @@ private: bool m_transmitting; bool m_tune; bool m_tx_watchdog; // true when watchdog triggered + TxEvidence::TxPlaybackDiagnostics m_txPlaybackDiagnostics; + TxEvidence::TxSessionId m_txEvidenceSession; + TxEvidence::TxSessionId m_txEvidenceSourceSession; + TxEvidence::TxGeneration m_txEvidenceGeneration; + TxEvidence::TxStopReason m_pendingTxStopReason {TxEvidence::TxStopReason::NormalEnd}; +#if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) + qint64 m_liveAudioTestFt8StartWindowOpenMs {-1}; + qint64 m_liveAudioTestFt8StartWindowCloseMs {-1}; + qint64 m_liveAudioTestFt8StartSessionId {-1}; + qint64 m_liveAudioTestFt8StartGeneration {-1}; +#endif + bool m_jttyTxActive; + bool m_jttyTxUsesTciAudio; + TxAudioQueueEpoch m_jttyTxQueueEpoch; + TxAudioQueueProgress m_jttyTxQueueProgress; + struct PendingJttyTciMessage + { + TxAudioQueueEpoch epoch; + qint64 enqueueId; + qint64 requestId; + qint64 sampleCount; + QString message; + bool newSession; + }; + QVector<PendingJttyTciMessage> m_pendingJttyTciMessages; + struct AcceptedJttyTxRequest + { + TxAudioQueueEpoch epoch; + qint64 requestId; + qint64 endSample; + }; + QVector<AcceptedJttyTxRequest> m_acceptedJttyTxRequests; + JttyDraftAcceptanceTracker m_jttyDraftAcceptanceTracker; + qint64 m_jttyTxRequestId; + qint64 m_jttyTciEnqueueId; + struct JttyQsoLine + { + qint64 messageId {0}; + float frequency {0.f}; + QString text; + float sequenceStart {0.f}; + QDateTime messageStartUtc; + }; + QVector<JttyQsoLine> m_jttyQsoLines; + QTextBlock m_jttyQsoGroupStart; + QTextBlock m_jttyQsoGroupEnd; + int m_jttyQsoGroupEndPosition {-1}; + bool m_jttyQsoRenderedLowerCase {false}; + bool m_jttyQsoRenderedIncludeTime {false}; + struct JttyDecodeLine + { + qint64 messageId {0}; + float frequency {0.f}; + QString text; + float sequenceStart {0.f}; + QDateTime messageStartUtc; + bool complete {false}; + bool written {false}; + DecodeOperatingContext context; + }; + QVector<JttyDecodeLine> m_jttyAllFreqLines; + int m_jttyLastAllFreqsK = -1; // detects a restarted decode (new WAV, or "decode again") + qint32 m_jttyLastSavedWavK0 = -1; // m_k0 at last JTTY WAV save; skips saving unchanged audio again + QTextBlock m_jttyAllFreqsGroupStart; // start of decodedTextBrowser's currently-growing group +#ifdef WIN32 + Jtty::N1mmOutput m_mmttyJttyOutput; +#endif bool m_block_pwr_tooltip; bool m_PwrBandSetOK; bool m_bDisplayedOnce; - Frequency m_lastMonitoredFrequency; double m_toneSpacing; - int m_firstDecode; - QProgressDialog m_optimizingProgress; QTimer m_heartbeat; MessageClient * m_messageClient; PSKReporter m_psk_Reporter; @@ -979,28 +1474,73 @@ private: //---------------------------------------------------- private functions void readSettings(); + void configureModeControlsLayout(); + void updateModeControlsLayout(); + void applyApplicationStyle(QFont const&, bool dark); + void setTrPeriodVisible(bool); void set_application_font (QFont const&); + void updateMainWindowControlSizes(); + void updateFrequencyToleranceRowAlignment(); void setDecodedTextFont (QFont const&); void writeSettings(); void createStatusBar(); + void handleTxInhibitStatus (bool supported, bool inhibited, QString const& holder, + quint32 hold_rx, quint32 release_rx, + quint32 expiries, quint32 invalid); + void startTxAudioAfterPttDelay (); void updateStatusBar(); + void updateMainWindowAccessibility(); + void registerMainWindowFocusControls(); + std::array<QRadioButton *, 6> txNextButtons() const; + std::array<QWidget *, 13> focusIndicatorWidgets() const; + void showMainWindowFocusIndicator(QWidget *widget); + void hideMainWindowFocusIndicators(); + void updateTxNextFocusPolicies(); + void updateTxFirstEnabledState(); + void setTxFirstModeEnabled(bool enabled); + bool switchTxNextMessage(QKeyEvent const *key_event); + bool switchMainWindowTab(QKeyEvent const *key_event); void genStdMsgs(QString rpt, bool unconditional = false); void genCQMsg(); void clearDX (); void lookup(); + QString expandTxMacros(QString const& message) const; void ba2msg(QByteArray ba, char* message); void msgtype(QString t, QLineEdit* tx); + void show_generated_message_error (); + void clear_generated_message_error (); + void update_generated_message_error (); void stub(); void statusChanged(); void fixStop(); + void finishReferenceSpectrumMeasurement(bool notify); + void updateReferenceSpectrumCountdown(); bool shortList(QString callsign) const; void transmit (double snr = 99.); void rigFailure (QString const& reason); void pskSetLocal (); void pskPost(DecodedText const& decodedtext); + void pskPost(DecodedText const& decodedtext, + DecodeOperatingContext const& context); void displayDialFrequency (); void transmitDisplay (bool); - void processMessage(DecodedText const& message, Qt::KeyboardModifiers = Qt::NoModifier); + void handleDecodeSelection(QString const& line, QString const& word, + Qt::KeyboardModifiers modifiers, + DecodedMessageReaction::SelectionOrigin selection_origin); + void processMessage(DecodedText const& message, Qt::KeyboardModifiers modifiers, + DecodedMessageReaction::SelectionOrigin selection_origin); + void processSyntheticMessage(DecodedText const& message); + DecodedMessageReaction::QsoReactionSnapshot qsoReactionSnapshot( + Qt::KeyboardModifiers modifiers = Qt::NoModifier) const; + DecodedMessageReaction::QsoReactionSnapshot qsoReactionSnapshot( + Qt::KeyboardModifiers modifiers, + DecodedMessageReaction::SelectionOrigin selection_origin) const; + void applyQsoReactionPlan(DecodedMessageReaction::QsoReactionPlan const& plan, + DecodedText const& message, bool * block_right_display = nullptr); + void applyQsoReactionEffect(DecodedMessageReaction::QsoReactionEffect const& effect, + DecodedText const& message, bool * block_right_display); + void showContestHint(DecodedMessageReaction::ContestHint hint); + void refreshQsoPane(DecodedText const& message); void replyToCQ (QTime, qint32 snr, float delta_time, quint32 delta_frequency, QString const& mode, QString const& message_text, bool low_confidence, quint8 modifiers); void locationChange(QString const& location); void replayDecodes (); @@ -1008,9 +1548,28 @@ private: void postWSPRDecode (bool is_new, QStringList message_parts); void enable_DXCC_entity (bool on); void switch_mode (Mode); - void WSPR_scheduling (); + bool hasMsk144BaseFrequency () const {return m_msk144basefreq > 0;} + BeaconTx::RoundRobinPolicy beaconRoundRobinPolicy () const; + BeaconTx::RoundRobinPolicy configuredRoundRobinPolicy () const; + void enterBeaconMode (); + void processBeaconActions (BeaconTx::Controller::Actions actions); + BeaconTx::ScheduleProposal beaconScheduleProposal (); + bool applyBeaconBandChange (BeaconTx::HoppingProposal const& proposal); void freqCalStep(); - void setRig (Frequency = 0); // zero frequency means no change + RigFrequencyChangePolicy::Activity rigFrequencyActivity () const; + RigFrequencyChangePolicy::Decision rigFrequencyChangeDecision ( + RigFrequencyChangePolicy::ChangeKind) const; + bool nominalFrequencyChangeAllowed (FrequencyRequestOrigin); + bool requestNominalFrequencyChange (Frequency, FrequencyRequestOrigin); + bool dispatchNominalFrequency (Frequency corrected, FrequencyRequestOrigin, bool monitoring); + bool requestBandChange (Frequency, FrequencyRequestOrigin); + bool workingFrequencyAt (int row, Frequency&) const; + void applyBandChange (Frequency, Frequency previous_frequency); + bool requestBandButtonFrequency (Frequency lookup_frequency, Frequency fallback_frequency, + double msk144_tr_period = 0.); + bool requestAlternateBandFrequency (Frequency); + bool reapplyCurrentRigFrequencyCorrection (); + void restoreNominalFrequencySelection (); void WSPR_history(Frequency dialFreq, int ndecodes); QString beacon_start_time (int n = 0); QString WSPR_message(); @@ -1019,36 +1578,73 @@ private: void useNextCall(); void abortQSO(); void updateRate(); - void write_all(QString txRx, QString message); + void write_all(QString txRx, QString message, + DecodeOperatingContext const * context = nullptr); bool isWorked(int itype, QString key, float fMHz=0, QString=""); - QString save_wave_file (QString const& name - , short const * data - , int samples - , QString const& my_callsign - , QString const& my_grid - , QString const& mode - , qint32 sub_mode - , Frequency frequency - , QString const& his_call - , QString const& his_grid) const; - void hound_reply (); + void hound_reply (int foxFrequency); QString sortHoundCalls(QString t, int isort, int max_dB); void rm_tb4(QString houndCall); void read_wav_file (QString const& fname); - void decodeDone (); + void wav_file_loaded (); + void update_wav_file_actions (); + void finishDecodeUi (); bool subProcessFailed (QProcess *, int exit_code, QProcess::ExitStatus); void subProcessError (QProcess *, QProcess::ProcessError); void statusUpdate () const; void update_watchdog_label (); + bool normalWatchdogWarningActive () const; + bool isHoundOperation () const; + bool isSuperHoundOperation () const; + void updateHoundVerificationStyle (); void invalidate_frequencies_filter (); void on_the_minute (); void add_child_to_event_filter (QObject *); void remove_child_from_event_filter (QObject *); void setup_status_bar (bool vhf); void tx_watchdog (bool triggered); - qint64 nWidgets(QString t); - void displayWidgets(qint64 n); + enum class ModeUiControl + { + TxFirst, + TxFrequency, + RxFrequency, + FrequencyTolerance, + Report, + TrPeriod, + CqTxFrequency, + ShortMessages, + Fast9, + AutoSequence, + Tx6, + CopyRxToTx, + CopyTxToRx, + HoldTxFrequency, + Submode, + Sync, + WsprControls, + ClearAverage, + DecodeDepth, + IncludeAveraging, + IncludeCorrelation, + EchoGraph, + Swl, + ApFt8, + ApJt65, + ApDxCall, + Respond, + Measure, + DxpedLabel, + RxAll, + CqOnly, + Fst4wTrPeriod, + LowFrequency, + HighFrequency, + AutoClearAverage, + MaxDrift, + FoxQueueTab + }; + using ModeUiState = std::initializer_list<ModeUiControl>; + void applyModeUiState(ModeUiState); QChar current_submode () const; // returns QChar {0} if submode is not appropriate void write_transmit_entry (QString const& file_name); void selectHound(QString t, bool bTopQueue); @@ -1057,11 +1653,60 @@ private: void updateFoxQSOsInProgressDisplay(); void foxQueueTopCallCommand(); void foxRxSequencer(QString msg, QString houndCall, QString rptRcvd); - void foxTxSequencer(); + bool foxTxSequencer(); void foxGenWaveform(int i,QString fm); void writeFoxQSO (QString const& msg); void update_foxLogWindow_rate(); - void to_jt9(qint32 n, qint32 istart, qint32 idone); + DecodePublishResult publishDecodeRequest( + bool copySamples, + Ft8MtdDecodeCoordinator::Stage ft8Stage = Ft8MtdDecodeCoordinator::Stage::None, + qint64 ft8Period = -1); + DecodePublishResult publishPendingFt8Decode (); + void decode (Ft8MtdDecodeCoordinator::Stage stage, qint64 ft8Period = -1); + qint64 currentFt8DecodePeriod () const; + bool usesFt8MtdFinal () const; + int configuredFt8MtdEarlyStageCount () const; + std::unique_ptr<Ft8MtdDecodeCoordinator::PendingMtdDecode> + capturePendingFt8MtdDecode (qint64 period) const; + void cancelPendingFt8Decode (QString const& reason); + void reportFt8BackpressureDecision ( + Ft8MtdDecodeCoordinator::Decision const& decision, qint64 period); + void reportFt8BackpressureRecovery (qint64 period); + void emitFt8DecoderInvocation (decoder_params_t const& params) const; + bool handleDecoderOutputEvent(DecoderOutputFramer::Event const& event, + bool& decodeCompleted); + DecodeOperatingContext currentDecodeOperatingContext() const; + bool decodeOperatingContextMatchesCurrent( + DecodeOperatingContext const& context) const; + bool pendingFt8DecodeOperatingContextMatchesCurrent( + DecodeOperatingContext const& context) const; + bool activeDecodeOperatingContextMatchesCurrent() const; + bool initializeDecoderSharedMemory(); + void startDecoderProcess(); + bool beginDecode( + DecodeOwner owner, decoder_params_t const * diagnosticParams = nullptr, + DecodeOperatingContext const * diagnosticContext = nullptr); + void endDecode(DecodeOwner owner, + DecodeEndState state = DecodeEndState::Completed); + void updateDecodeControls(); + bool usesJt9Process() const; + bool decoderRestartInProgress() const; + void abortJt9Transaction(); + void recoverDecoderAtBoundary(QString const& reason, bool manual); + void requestDecoderRestart(QString const& reason); + qint64 decoderDiagnosticElapsedMs() const; + qint64 decoderDiagnosticIdleMs() const; + qint64 decoderRequestDeadlineMs() const; + bool decoderRequestDeadlineExpired() const; + void beginDecoderDiagnostic( + decoder_params_t const * params = nullptr, + DecodeOperatingContext const * context = nullptr); + void markDecoderProgress(); + void logDecoderBusyRequest(QString const& reason); + void logDecoderProgress(); + void logDecoderAbnormalClear(QString const& reason); + void finishDecoderDiagnostic(); + void clearHungDecoderStatus(QString const& reason); bool is77BitMode () const; void cease_auto_Tx_after_QSO (); Q_SLOT void ARRL_Digi_Display(); @@ -1069,7 +1714,6 @@ private: void activeWorked(QString call, QString band); void read_log(); void refreshPileupList(); - QString userAgent(); void handleVerifyMsg(int status, QDateTime ts, QString callsign, QString code, unsigned int hz, QString const &response); void writeFoxTxMsgs(); #ifdef FOX_OTP diff --git a/widgets/mainwindow.ui b/widgets/mainwindow.ui index d9d83bac..0353de83 100644 --- a/widgets/mainwindow.ui +++ b/widgets/mainwindow.ui @@ -6,8 +6,8 @@ <rect> <x>0</x> <y>0</y> - <width>880</width> - <height>685</height> + <width>876</width> + <height>688</height> </rect> </property> <property name="minimumSize"> @@ -17,7 +17,7 @@ </size> </property> <property name="windowTitle"> - <string>WSJT-X by K1JT</string> + <string>WSJT-Xâ„¢ by K1JT et al.</string> </property> <property name="toolTip"> <string/> @@ -26,7 +26,7 @@ <string notr="true"/> </property> <widget class="QWidget" name="centralWidget"> - <layout class="QVBoxLayout" name="verticalLayout_6" stretch="0,0"> + <layout class="QVBoxLayout" name="verticalLayout_6" stretch="0,0,0"> <item> <widget class="QSplitter" name="decodes_splitter"> <property name="orientation"> @@ -42,11 +42,11 @@ <height>16777215</height> </size> </property> - <property name="font"> - <font> - <pointsize>10</pointsize> - <bold>false</bold> - </font> + <property name="accessibleName"> + <string>Band Activity decode pane title</string> + </property> + <property name="accessibleDescription"> + <string>Title for the Band Activity decoded messages pane.</string> </property> <property name="text"> <string>Band Activity</string> @@ -134,6 +134,12 @@ </disabled> </palette> </property> + <property name="accessibleName"> + <string>Band Activity decoded messages headings</string> + </property> + <property name="accessibleDescription"> + <string>Columns: UTC dB DT Freq Message.</string> + </property> <property name="autoFillBackground"> <bool>true</bool> </property> @@ -150,6 +156,12 @@ </item> <item> <widget class="DisplayText" name="decodedTextBrowser"> + <property name="accessibleName"> + <string>Band Activity decoded messages</string> + </property> + <property name="accessibleDescription"> + <string>Decoded messages in the Band Activity pane. Columns: UTC dB DT Freq Message.</string> + </property> <property name="frameShape"> <enum>QFrame::StyledPanel</enum> </property> @@ -185,11 +197,11 @@ </property> <item> <widget class="QLabel" name="rh_decodes_title_label"> - <property name="font"> - <font> - <pointsize>10</pointsize> - <bold>false</bold> - </font> + <property name="accessibleName"> + <string>Rx Frequency decode pane title</string> + </property> + <property name="accessibleDescription"> + <string>Title for the Rx Frequency decoded messages pane.</string> </property> <property name="text"> <string>Rx Frequency</string> @@ -277,6 +289,12 @@ </disabled> </palette> </property> + <property name="accessibleName"> + <string>Rx Frequency decoded messages headings</string> + </property> + <property name="accessibleDescription"> + <string>Columns: UTC dB DT Freq Message.</string> + </property> <property name="autoFillBackground"> <bool>true</bool> </property> @@ -296,6 +314,12 @@ <property name="enabled"> <bool>true</bool> </property> + <property name="accessibleName"> + <string>Rx Frequency decoded messages</string> + </property> + <property name="accessibleDescription"> + <string>Decoded messages in the Rx Frequency pane. Columns: UTC dB DT Freq Message.</string> + </property> <property name="verticalScrollBarPolicy"> <enum>Qt::ScrollBarAlwaysOn</enum> </property> @@ -312,6 +336,43 @@ </widget> </item> <item> + <layout class="QHBoxLayout" name="horizontalLayout_decodeOptions"> + <item> + <widget class="QCheckBox" name="cbLowerCase"> + <property name="toolTip"> + <string>Check to display received messages in lower case.</string> + </property> + <property name="text"> + <string> Lower case</string> + </property> + <property name="checked"> + <bool>false</bool> + </property> + </widget> + </item> + <item> + <widget class="QCheckBox" name="cbIncludeTime"> + <property name="text"> + <string>Include Time</string> + </property> + </widget> + </item> + <item> + <spacer name="horizontalSpacer_9"> + <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> + <item> <widget class="QWidget" name="lower_panel_widget" native="true"> <property name="sizePolicy"> <sizepolicy hsizetype="Preferred" vsizetype="Maximum"> @@ -337,8 +398,8 @@ <property name="spacing"> <number>3</number> </property> - <item row="0" column="3"> - <widget class="QPushButton" name="pb40"> + <item row="0" column="7"> + <widget class="QPushButton" name="pb15"> <property name="minimumSize"> <size> <width>20</width> @@ -349,12 +410,12 @@ <enum>Qt::StrongFocus</enum> </property> <property name="text"> - <string>40</string> + <string>15</string> </property> </widget> </item> - <item row="0" column="9"> - <widget class="QPushButton" name="pb10"> + <item row="0" column="6"> + <widget class="QPushButton" name="pb17"> <property name="minimumSize"> <size> <width>20</width> @@ -365,15 +426,15 @@ <enum>Qt::StrongFocus</enum> </property> <property name="text"> - <string>10</string> + <string>17</string> </property> </widget> </item> - <item row="0" column="6"> - <widget class="QPushButton" name="pb17"> + <item row="0" column="11"> + <widget class="QPushButton" name="pb2"> <property name="minimumSize"> <size> - <width>20</width> + <width>15</width> <height>0</height> </size> </property> @@ -381,102 +442,93 @@ <enum>Qt::StrongFocus</enum> </property> <property name="text"> - <string>17</string> + <string>2</string> </property> </widget> </item> - <item row="0" column="2"> - <widget class="QPushButton" name="pb60"> + <item row="1" column="7"> + <widget class="QPushButton" name="pb23"> <property name="minimumSize"> <size> - <width>20</width> + <width>25</width> <height>0</height> </size> </property> <property name="text"> - <string>60</string> + <string>23</string> </property> </widget> </item> - <item row="0" column="8"> - <widget class="QPushButton" name="pb12"> + <item row="1" column="3"> + <widget class="QPushButton" name="pb144"> <property name="minimumSize"> <size> - <width>20</width> + <width>25</width> <height>0</height> </size> </property> - <property name="focusPolicy"> - <enum>Qt::StrongFocus</enum> - </property> <property name="text"> - <string>12</string> + <string>2</string> </property> </widget> </item> - <item row="0" column="0"> - <widget class="QPushButton" name="pb160"> + <item row="0" column="9"> + <widget class="QPushButton" name="pb10"> <property name="minimumSize"> <size> - <width>25</width> + <width>20</width> <height>0</height> </size> </property> + <property name="focusPolicy"> + <enum>Qt::StrongFocus</enum> + </property> <property name="text"> - <string>160</string> + <string>10</string> </property> </widget> </item> - <item row="0" column="5"> - <widget class="QPushButton" name="pb20"> + <item row="1" column="1"> + <widget class="QPushButton" name="pb50"> <property name="minimumSize"> <size> - <width>20</width> + <width>25</width> <height>0</height> </size> </property> - <property name="focusPolicy"> - <enum>Qt::StrongFocus</enum> - </property> <property name="text"> - <string>20</string> + <string>6</string> </property> </widget> </item> - <item row="0" column="1"> - <widget class="QPushButton" name="pb80"> + <item row="1" column="6"> + <widget class="QPushButton" name="pb902"> <property name="minimumSize"> <size> - <width>20</width> + <width>25</width> <height>0</height> </size> </property> - <property name="focusPolicy"> - <enum>Qt::StrongFocus</enum> - </property> <property name="text"> - <string>80</string> + <string>33</string> </property> </widget> </item> - <item row="0" column="13"> - <widget class="QPushButton" name="pb70"> + <item row="1" column="5"> + <widget class="QPushButton" name="pb432"> <property name="minimumSize"> <size> - <width>20</width> + <width>25</width> <height>0</height> </size> </property> - <property name="focusPolicy"> - <enum>Qt::StrongFocus</enum> - </property> <property name="text"> <string>70</string> </property> </widget> </item> - <item row="0" column="7"> - <widget class="QPushButton" name="pb15"> + <item row="0" column="1"> + <widget class="QPushButton" name="pb80"> <property name="minimumSize"> <size> <width>20</width> @@ -487,28 +539,25 @@ <enum>Qt::StrongFocus</enum> </property> <property name="text"> - <string>15</string> + <string>80</string> </property> </widget> </item> - <item row="0" column="11"> - <widget class="QPushButton" name="pb2"> + <item row="1" column="11"> + <widget class="QPushButton" name="pb10G"> <property name="minimumSize"> <size> - <width>15</width> + <width>25</width> <height>0</height> </size> </property> - <property name="focusPolicy"> - <enum>Qt::StrongFocus</enum> - </property> <property name="text"> - <string>2</string> + <string>10G</string> </property> </widget> </item> - <item row="0" column="4"> - <widget class="QPushButton" name="pb30"> + <item row="0" column="3"> + <widget class="QPushButton" name="pb40"> <property name="minimumSize"> <size> <width>20</width> @@ -519,28 +568,25 @@ <enum>Qt::StrongFocus</enum> </property> <property name="text"> - <string>30</string> + <string>40</string> </property> </widget> </item> - <item row="0" column="10"> - <widget class="QPushButton" name="pb6"> + <item row="0" column="2"> + <widget class="QPushButton" name="pb60"> <property name="minimumSize"> <size> - <width>15</width> + <width>20</width> <height>0</height> </size> </property> - <property name="focusPolicy"> - <enum>Qt::StrongFocus</enum> - </property> <property name="text"> - <string>6</string> + <string>60</string> </property> </widget> </item> - <item row="1" column="13"> - <widget class="QPushButton" name="pb24G"> + <item row="1" column="8"> + <widget class="QPushButton" name="pb13"> <property name="minimumSize"> <size> <width>25</width> @@ -548,12 +594,12 @@ </size> </property> <property name="text"> - <string>24G</string> + <string>13</string> </property> </widget> </item> - <item row="1" column="11"> - <widget class="QPushButton" name="pb10G"> + <item row="1" column="13"> + <widget class="QPushButton" name="pb24G"> <property name="minimumSize"> <size> <width>25</width> @@ -561,12 +607,12 @@ </size> </property> <property name="text"> - <string>10G</string> + <string>24G</string> </property> </widget> </item> - <item row="1" column="10"> - <widget class="QPushButton" name="pb5G"> + <item row="1" column="2"> + <widget class="QPushButton" name="pb4"> <property name="minimumSize"> <size> <width>25</width> @@ -574,12 +620,12 @@ </size> </property> <property name="text"> - <string>5G</string> + <string>4</string> </property> </widget> </item> - <item row="1" column="9"> - <widget class="QPushButton" name="pb9"> + <item row="1" column="0"> + <widget class="QPushButton" name="pb8"> <property name="minimumSize"> <size> <width>25</width> @@ -587,12 +633,12 @@ </size> </property> <property name="text"> - <string>9</string> + <string>8</string> </property> </widget> </item> - <item row="1" column="8"> - <widget class="QPushButton" name="pb13"> + <item row="1" column="4"> + <widget class="QPushButton" name="pb220"> <property name="minimumSize"> <size> <width>25</width> @@ -600,38 +646,44 @@ </size> </property> <property name="text"> - <string>13</string> + <string>1.25</string> </property> </widget> </item> - <item row="1" column="7"> - <widget class="QPushButton" name="pb23"> + <item row="0" column="13"> + <widget class="QPushButton" name="pb70"> <property name="minimumSize"> <size> - <width>25</width> + <width>20</width> <height>0</height> </size> </property> + <property name="focusPolicy"> + <enum>Qt::StrongFocus</enum> + </property> <property name="text"> - <string>23</string> + <string>70</string> </property> </widget> </item> - <item row="1" column="6"> - <widget class="QPushButton" name="pb902"> + <item row="0" column="4"> + <widget class="QPushButton" name="pb30"> <property name="minimumSize"> <size> - <width>25</width> + <width>20</width> <height>0</height> </size> </property> + <property name="focusPolicy"> + <enum>Qt::StrongFocus</enum> + </property> <property name="text"> - <string>33</string> + <string>30</string> </property> </widget> </item> - <item row="1" column="5"> - <widget class="QPushButton" name="pb432"> + <item row="0" column="0"> + <widget class="QPushButton" name="pb160"> <property name="minimumSize"> <size> <width>25</width> @@ -639,25 +691,28 @@ </size> </property> <property name="text"> - <string>70</string> + <string>160</string> </property> </widget> </item> - <item row="1" column="4"> - <widget class="QPushButton" name="pb220"> + <item row="0" column="5"> + <widget class="QPushButton" name="pb20"> <property name="minimumSize"> <size> - <width>25</width> + <width>20</width> <height>0</height> </size> </property> + <property name="focusPolicy"> + <enum>Qt::StrongFocus</enum> + </property> <property name="text"> - <string>1.25</string> + <string>20</string> </property> </widget> </item> - <item row="1" column="3"> - <widget class="QPushButton" name="pb144"> + <item row="1" column="10"> + <widget class="QPushButton" name="pb5G"> <property name="minimumSize"> <size> <width>25</width> @@ -665,12 +720,12 @@ </size> </property> <property name="text"> - <string>2</string> + <string>5G</string> </property> </widget> </item> - <item row="1" column="2"> - <widget class="QPushButton" name="pb4"> + <item row="1" column="9"> + <widget class="QPushButton" name="pb9"> <property name="minimumSize"> <size> <width>25</width> @@ -678,60 +733,46 @@ </size> </property> <property name="text"> - <string>4</string> + <string>9</string> </property> </widget> </item> - <item row="1" column="1"> - <widget class="QPushButton" name="pb50"> + <item row="0" column="10"> + <widget class="QPushButton" name="pb6"> <property name="minimumSize"> <size> - <width>25</width> + <width>15</width> <height>0</height> </size> </property> + <property name="focusPolicy"> + <enum>Qt::StrongFocus</enum> + </property> <property name="text"> <string>6</string> </property> </widget> </item> - <item row="1" column="0"> - <widget class="QPushButton" name="pb8"> + <item row="0" column="8"> + <widget class="QPushButton" name="pb12"> <property name="minimumSize"> <size> - <width>25</width> + <width>20</width> <height>0</height> </size> </property> + <property name="focusPolicy"> + <enum>Qt::StrongFocus</enum> + </property> <property name="text"> - <string>8</string> + <string>12</string> </property> </widget> </item> </layout> </item> <item> - <layout class="QHBoxLayout" name="horizontalLayout_2" stretch="0,0,2,2,2,2,2,0,2,2,2,2,1"> - <item> - <widget class="QCheckBox" name="cbCQonly"> - <property name="toolTip"> - <string>CQ messages only.</string> - </property> - <property name="text"> - <string>CQ only</string> - </property> - </widget> - </item> - <item> - <widget class="QCheckBox" name="cbBypass"> - <property name="toolTip"> - <string>Bypass Filters toggled via Settings or the Filters menu.</string> - </property> - <property name="text"> - <string>BP</string> - </property> - </widget> - </item> + <layout class="QHBoxLayout" name="horizontalLayout_2" stretch="2,2,2,2,2,0,2,2,2,2,1"> <item> <widget class="QPushButton" name="logQSOButton"> <property name="minimumSize"> @@ -783,7 +824,6 @@ border-width: 1px; border-radius: 5px; border-color: black; - min-width: 5em; padding: 3px; }</string> </property> @@ -883,7 +923,6 @@ border-width: 1px; border-radius: 5px; border-color: black; - min-width: 5em; padding: 3px; }</string> </property> @@ -920,7 +959,6 @@ border-width: 1px; border-radius: 5px; border-color: black; - min-width: 5em; padding: 3px; }</string> </property> @@ -973,7 +1011,6 @@ border-width: 1px; border-radius: 5px; border-color: black; - min-width: 5em; padding: 3px; }</string> </property> @@ -1009,7 +1046,7 @@ </property> <property name="minimumSize"> <size> - <width>114</width> + <width>154</width> <height>0</height> </size> </property> @@ -1031,7 +1068,7 @@ <item row="0" column="0"> <widget class="QPushButton" name="DX_Call_Button"> <property name="sizePolicy"> - <sizepolicy hsizetype="Preferred" vsizetype="Preferred"> + <sizepolicy hsizetype="Preferred" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> @@ -1048,12 +1085,6 @@ <property name="toolTip"> <string><html><head/><body><p>Toggle Wait &amp; Call On/Off. Right-click to clear the DX Call box.</p></body></html></string> </property> - <property name="styleSheet"> - <string notr="true">QPushButton { - background-color: #9fafd5; - border: none; -}</string> - </property> <property name="text"> <string>DX Call</string> </property> @@ -1062,10 +1093,10 @@ </property> </widget> </item> - <item row="1" column="0"> - <widget class="QLineEdit" name="dxCallEntry"> + <item row="1" column="1"> + <widget class="QLineEdit" name="dxGridEntry"> <property name="toolTip"> - <string>Callsign of station to be worked</string> + <string>Locator of station to be worked</string> </property> <property name="text"> <string/> @@ -1083,73 +1114,6 @@ <verstretch>0</verstretch> </sizepolicy> </property> - <property name="palette"> - <palette> - <active> - <colorrole role="Base"> - <brush brushstyle="SolidPattern"> - <color alpha="255"> - <red>252</red> - <green>252</green> - <blue>252</blue> - </color> - </brush> - </colorrole> - <colorrole role="Window"> - <brush brushstyle="SolidPattern"> - <color alpha="255"> - <red>159</red> - <green>175</green> - <blue>213</blue> - </color> - </brush> - </colorrole> - </active> - <inactive> - <colorrole role="Base"> - <brush brushstyle="SolidPattern"> - <color alpha="255"> - <red>252</red> - <green>252</green> - <blue>252</blue> - </color> - </brush> - </colorrole> - <colorrole role="Window"> - <brush brushstyle="SolidPattern"> - <color alpha="255"> - <red>159</red> - <green>175</green> - <blue>213</blue> - </color> - </brush> - </colorrole> - </inactive> - <disabled> - <colorrole role="Base"> - <brush brushstyle="SolidPattern"> - <color alpha="255"> - <red>159</red> - <green>175</green> - <blue>213</blue> - </color> - </brush> - </colorrole> - <colorrole role="Window"> - <brush brushstyle="SolidPattern"> - <color alpha="255"> - <red>159</red> - <green>175</green> - <blue>213</blue> - </color> - </brush> - </colorrole> - </disabled> - </palette> - </property> - <property name="autoFillBackground"> - <bool>true</bool> - </property> <property name="text"> <string>DX Grid</string> </property> @@ -1167,10 +1131,10 @@ </property> </widget> </item> - <item row="1" column="1"> - <widget class="QLineEdit" name="dxGridEntry"> + <item row="1" column="0"> + <widget class="QLineEdit" name="dxCallEntry"> <property name="toolTip"> - <string>Locator of station to be worked</string> + <string>Callsign of station to be worked</string> </property> <property name="text"> <string/> @@ -1272,9 +1236,9 @@ </widget> </item> <item row="1" column="7" rowspan="2"> - <widget class="QSlider" name="outAttenuation"> + <widget class="TxDriveSlider" name="outAttenuation"> <property name="toolTip"> - <string>Adjust Tx audio level</string> + <string>Adjust transmit drive level</string> </property> <property name="maximum"> <number>450</number> @@ -1291,12 +1255,6 @@ <property name="invertedControls"> <bool>true</bool> </property> - <property name="tickPosition"> - <enum>QSlider::TicksBelow</enum> - </property> - <property name="tickInterval"> - <number>50</number> - </property> </widget> </item> <item row="0" column="7"> @@ -1408,7 +1366,7 @@ Yellow when too low</string> </layout> </item> <item row="0" column="6" rowspan="3"> - <widget class="QStackedWidget" name="controls_stack_widget"> + <widget class="CurrentPageHeightStackedWidget" name="controls_stack_widget"> <property name="sizePolicy"> <sizepolicy hsizetype="MinimumExpanding" vsizetype="Preferred"> <horstretch>0</horstretch> @@ -1416,7 +1374,7 @@ Yellow when too low</string> </sizepolicy> </property> <property name="currentIndex"> - <number>0</number> + <number>1</number> </property> <widget class="QWidget" name="page"> <layout class="QHBoxLayout" name="horizontalLayout_8"> @@ -1561,7 +1519,6 @@ Not available to nonstandard callsign holders.</string> border-width: 1px; border-radius: 5px; border-color: black; - min-width: 5em; padding: 3px; }</string> </property> @@ -1634,7 +1591,7 @@ When not checked you can view the calibration results.</string> <item> <widget class="QComboBox" name="respondComboBox"> <property name="toolTip"> - <string><html><head/><body><p>Select <span style=" font-weight:600;">CQ: None</span> to choose callers manually.</p><p>Select <span style=" font-weight:600;">CQ: First</span> to respond automatically to the first decoded reply to your CQ. </p><p>Select <span style=" font-weight:600;">CQ: Max Dist</span> to respond automatically to the reply yielding most points in the ARRL International Digital Contest, or in general to the most distant station, if its message has a valid grid.</p><p>Select <span style=" font-weight:600;">CQ: Max dB</span> to respond automatically to the the strongest station's reply to your CQ. </p><p>Select <span style=" font-weight:600;">CQ: Min dB</span> to respond automatically to the the weakest station's reply to your CQ. </p></body></html></string> + <string><html><head/><body><p>Select <span style=" font-weight:600;">CQ: None</span> to choose callers manually.</p><p>Select <span style=" font-weight:600;">CQ: First</span> to respond automatically to the first decoded reply to your CQ.</p><p>Select <span style=" font-weight:600;">CQ: Max Dist</span> to respond automatically to the reply yielding most points in the ARRL International Digital Contest, or in general to the most distant station, if its message has a valid grid.</p><p>Select <span style=" font-weight:600;">CQ: Max dB</span> to respond automatically to the strongest station's reply to your CQ.</p><p>Select <span style=" font-weight:600;">CQ: Min dB</span> to respond automatically to the weakest station's reply to your CQ.</p><p>When CQ or QRZ is pending, Enable Tx may be armed before or during a receive period. Only eligible direct callers decoded after it is armed in that period can replace the pending transmission; earlier callers are not retained.</p></body></html></string> </property> <property name="currentText"> <string/> @@ -1670,10 +1627,10 @@ When not checked you can view the calibration results.</string> <enum>Qt::StrongFocus</enum> </property> <property name="toolTip"> - <string><html><head/><body><p>Check to Tx in even-numbered minutes or sequences, starting at 0; uncheck for odd sequences. Right-click to freeze the state of the checkbox. Right-click either the FT8 or MSK button to unfreeze.</p></body></html></string> + <string><html><head/><body><p>Check to Tx in even-numbered minutes or sequences, starting at 0; uncheck for odd sequences. Right-click to toggle the checkbox enabled/disabled. Fox and Hound modes lock the required sequence.</p></body></html></string> </property> <property name="accessibleDescription"> - <string><html><head/><body><p>Check to Tx in even-numbered minutes or sequences, starting at 0; uncheck for odd sequences. Right-click to freeze the state of the checkbox. Right-click either the FT8 or MSK button to unfreeze.</p></body></html></string> + <string><html><head/><body><p>Check to Tx in even-numbered minutes or sequences, starting at 0; uncheck for odd sequences. Right-click to toggle the checkbox enabled/disabled. Fox and Hound modes lock the required sequence.</p></body></html></string> </property> <property name="text"> <string>Tx even/1st</string> @@ -2013,7 +1970,7 @@ When not checked you can view the calibration results.</string> <item> <widget class="QStackedWidget" name="opt_controls_stack"> <property name="currentIndex"> - <number>1</number> + <number>0</number> </property> <widget class="QWidget" name="page_0"> <layout class="QVBoxLayout" name="verticalLayout"> @@ -2217,6 +2174,12 @@ When not checked you can view the calibration results.</string> <string>1</string> </attribute> <layout class="QGridLayout" name="gridLayout_7"> + <property name="leftMargin"> + <number>4</number> + </property> + <property name="rightMargin"> + <number>4</number> + </property> <item row="0" column="0"> <layout class="QGridLayout" name="gridLayout_6" columnstretch="1,0,0"> <item row="6" column="1"> @@ -2264,11 +2227,11 @@ When not checked you can view the calibration results.</string> <item row="4" column="1"> <widget class="DoubleClickableRadioButton" name="txrb4"> <property name="toolTip"> - <string><html><head/><body><p>Send this message in next Tx interval</p><p>Double-click to toggle between RRR and RR73 messages in Tx4 (not allowed for type 2 compound call holders)</p><p>RR73 messages should only be used when you are reasonably confident that no message repetitions will be required</p></body></html></string> + <string><html><head/><body><p>Send this message in next Tx interval</p><p>Double-click to toggle between RRR and RR73 messages in Tx4 when supported by the current mode</p><p>RR73 messages should only be used when you are reasonably confident that no message repetitions will be required</p></body></html></string> </property> <property name="accessibleDescription"> <string>Send this message in next Tx interval -Double-click to toggle between RRR and RR73 messages in Tx4 (not allowed for type 2 compound call holders) +Double-click to toggle between RRR and RR73 messages in Tx4 when supported by the current mode RR73 messages should only be used when you are reasonably confident that no message repetitions will be required</string> </property> <property name="styleSheet"> @@ -2323,9 +2286,6 @@ Double click to toggle the use of the Tx1 message to start a QSO with a station <property name="accessibleDescription"> <string><html><head/><body><p>Switch to this Tx message NOW</p><p>Double-click to reset to the standard 73 message</p><p>Right-click to retain Tx5 free text</p></body></html></string> </property> - <property name="styleSheet"> - <string notr="true">padding-left: 15%; padding-right: 15%; padding-top: 3%; padding-bottom: 3%</string> - </property> <property name="text"> <string>Tx &5</string> </property> @@ -2339,9 +2299,6 @@ Double click to toggle the use of the Tx1 message to start a QSO with a station <property name="toolTip"> <string>Switch to this Tx message NOW</string> </property> - <property name="styleSheet"> - <string notr="true">padding-left: 15%; padding-right: 15%; padding-top: 3%; padding-bottom: 3%</string> - </property> <property name="text"> <string>Tx &2</string> </property> @@ -2424,9 +2381,6 @@ Double click to toggle the use of the Tx1 message to start a QSO with a station <property name="toolTip"> <string>Switch to this Tx message NOW</string> </property> - <property name="styleSheet"> - <string notr="true">padding-left: 15%; padding-right: 15%; padding-top: 3%; padding-bottom: 3%</string> - </property> <property name="text"> <string>Tx &3</string> </property> @@ -2438,16 +2392,13 @@ Double click to toggle the use of the Tx1 message to start a QSO with a station <item row="4" column="2"> <widget class="DoubleClickablePushButton" name="txb4"> <property name="toolTip"> - <string><html><head/><body><p>Switch to this Tx message NOW</p><p>Double-click to toggle between RRR and RR73 messages in Tx4 (not allowed for type2 compound call holders)</p><p>RR73 messages should only be used when you are reasonably confident that no message repetitions will be required</p></body></html></string> + <string><html><head/><body><p>Switch to this Tx message NOW</p><p>Double-click to toggle between RRR and RR73 messages in Tx4 when supported by the current mode</p><p>RR73 messages should only be used when you are reasonably confident that no message repetitions will be required</p></body></html></string> </property> <property name="accessibleDescription"> <string>Switch to this Tx message NOW -Double-click to toggle between RRR and RR73 messages in Tx4 (not allowed for type2 compound call holders) +Double-click to toggle between RRR and RR73 messages in Tx4 when supported by the current mode RR73 messages should only be used when you are reasonably confident that no message repetitions will be required</string> </property> - <property name="styleSheet"> - <string notr="true">padding-left: 15%; padding-right: 15%; padding-top: 3%; padding-bottom: 3%</string> - </property> <property name="text"> <string>Tx &4</string> </property> @@ -2468,9 +2419,6 @@ Double click to toggle the use of the Tx1 message to start a QSO with a station <property name="layoutDirection"> <enum>Qt::LeftToRight</enum> </property> - <property name="styleSheet"> - <string notr="true">padding-left: 15%; padding-right: 15%; padding-top: 3%; padding-bottom: 3%</string> - </property> <property name="text"> <string>Tx &1</string> </property> @@ -2484,9 +2432,6 @@ Double click to toggle the use of the Tx1 message to start a QSO with a station <property name="toolTip"> <string>Switch to this Tx message NOW</string> </property> - <property name="styleSheet"> - <string notr="true">padding-left: 15%; padding-right: 15%; padding-top: 3%; padding-bottom: 3%</string> - </property> <property name="text"> <string>Tx &6</string> </property> @@ -2701,11 +2646,6 @@ Double-click to reset to the standard 73 message</string> </item> <item row="0" column="0"> <widget class="QLabel" name="label_queue"> - <property name="font"> - <font> - <pointsize>9</pointsize> - </font> - </property> <property name="text"> <string>Queue</string> </property> @@ -3032,7 +2972,6 @@ Double-click to reset to the standard 73 message</string> border-width: 1px; border-radius: 5px; border-color: black; - min-width: 5em; padding: 3px; }</string> </property> @@ -3696,6 +3635,479 @@ Double-click to reset to the standard 73 message</string> </item> </layout> </widget> + <widget class="QWidget" name="page_4"> + <layout class="QGridLayout" name="gridLayout_12"> + <item row="0" column="0"> + <widget class="QWidget" name="widget" native="true"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Maximum" vsizetype="Preferred"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <layout class="QGridLayout" name="gridLayout_14"> + <item row="0" column="0" colspan="4"> + <widget class="QSpinBox" name="TxFreqSpinBox_2"> + <property name="maximumSize"> + <size> + <width>16777215</width> + <height>16777215</height> + </size> + </property> + <property name="toolTip"> + <string>Audio Tx frequency</string> + </property> + <property name="alignment"> + <set>Qt::AlignCenter</set> + </property> + <property name="suffix"> + <string> Hz</string> + </property> + <property name="prefix"> + <string>Tx </string> + </property> + <property name="minimum"> + <number>200</number> + </property> + <property name="maximum"> + <number>5000</number> + </property> + <property name="value"> + <number>1500</number> + </property> + </widget> + </item> + <item row="1" column="1" colspan="2"> + <widget class="HintedSpinBox" name="sbFtol_2"> + <property name="sizePolicy"> + <sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="toolTip"> + <string>Frequency tolerance (Hz)</string> + </property> + <property name="alignment"> + <set>Qt::AlignCenter</set> + </property> + <property name="prefix"> + <string>F Tol </string> + </property> + <property name="minimum"> + <number>1</number> + </property> + <property name="maximum"> + <number>1000</number> + </property> + <property name="value"> + <number>10</number> + </property> + </widget> + </item> + <item row="1" column="0"> + <widget class="QPushButton" name="pbR2T_2"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Minimum" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="minimumSize"> + <size> + <width>15</width> + <height>0</height> + </size> + </property> + <property name="maximumSize"> + <size> + <width>35</width> + <height>16777215</height> + </size> + </property> + <property name="toolTip"> + <string>Set Tx frequency to Rx Frequency</string> + </property> + <property name="accessibleName"> + <string>Set Tx frequency to Rx Frequency</string> + </property> + <property name="text"> + <string>â–²</string> + </property> + </widget> + </item> + <item row="2" column="0" colspan="4"> + <widget class="QSpinBox" name="RxFreqSpinBox_2"> + <property name="maximumSize"> + <size> + <width>16777215</width> + <height>16777215</height> + </size> + </property> + <property name="toolTip"> + <string>Audio Rx frequency</string> + </property> + <property name="alignment"> + <set>Qt::AlignCenter</set> + </property> + <property name="suffix"> + <string> Hz</string> + </property> + <property name="prefix"> + <string>Rx </string> + </property> + <property name="minimum"> + <number>200</number> + </property> + <property name="maximum"> + <number>5000</number> + </property> + <property name="value"> + <number>1500</number> + </property> + </widget> + </item> + <item row="1" column="3"> + <widget class="QPushButton" name="pbT2R_2"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Minimum" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="minimumSize"> + <size> + <width>15</width> + <height>0</height> + </size> + </property> + <property name="maximumSize"> + <size> + <width>35</width> + <height>16777215</height> + </size> + </property> + <property name="toolTip"> + <string>Set Rx frequency to Tx Frequency</string> + </property> + <property name="accessibleName"> + <string>Set Rx frequency to Tx Frequency</string> + </property> + <property name="text"> + <string>â–¼</string> + </property> + </widget> + </item> + </layout> + </widget> + </item> + <item row="0" column="1" colspan="2"> + <widget class="QWidget" name="widget2" native="true"> + <property name="title" stdset="0"> + <string>GroupBox</string> + </property> + <layout class="QHBoxLayout" name="horizontalLayout"> + <item> + <layout class="QGridLayout" name="gridLayout_15" columnstretch="1,1,1,1"> + <item row="1" column="0"> + <widget class="QLineEdit" name="msg1"> + <property name="text"> + <string>CQ %M CQ</string> + </property> + <property name="alignment"> + <set>Qt::AlignCenter</set> + </property> + </widget> + </item> + <item row="1" column="1"> + <widget class="QLineEdit" name="msg2"> + <property name="text"> + <string>%H 599 %N</string> + </property> + <property name="alignment"> + <set>Qt::AlignCenter</set> + </property> + </widget> + </item> + <item row="1" column="2"> + <widget class="QLineEdit" name="msg3"> + <property name="text"> + <string>%H TU CQ %M CQ</string> + </property> + <property name="alignment"> + <set>Qt::AlignCenter</set> + </property> + </widget> + </item> + <item row="1" column="3"> + <widget class="QLineEdit" name="msg4"> + <property name="text"> + <string>%M</string> + </property> + <property name="alignment"> + <set>Qt::AlignCenter</set> + </property> + </widget> + </item> + <item row="3" column="0"> + <widget class="QLineEdit" name="msg5"> + <property name="text"> + <string>%H</string> + </property> + <property name="alignment"> + <set>Qt::AlignCenter</set> + </property> + </widget> + </item> + <item row="3" column="1"> + <widget class="QLineEdit" name="msg6"> + <property name="text"> + <string>TU NOW %Q 599 %N</string> + </property> + <property name="alignment"> + <set>Qt::AlignCenter</set> + </property> + </widget> + </item> + <item row="3" column="2"> + <widget class="QLineEdit" name="msg7"> + <property name="text"> + <string>%H AGN?</string> + </property> + <property name="alignment"> + <set>Qt::AlignCenter</set> + </property> + </widget> + </item> + <item row="3" column="3"> + <widget class="QLineEdit" name="msg8"> + <property name="text"> + <string>599 %N</string> + </property> + <property name="alignment"> + <set>Qt::AlignCenter</set> + </property> + </widget> + </item> + <item row="0" column="0"> + <widget class="QPushButton" name="pbF1"> + <property name="toolTip"> + <string>CQ</string> + </property> + <property name="text"> + <string>F1</string> + </property> + </widget> + </item> + <item row="0" column="1"> + <widget class="QPushButton" name="pbF2"> + <property name="toolTip"> + <string>HisCall Exchange</string> + </property> + <property name="text"> + <string>F2</string> + </property> + </widget> + </item> + <item row="0" column="2"> + <widget class="QPushButton" name="pbF3"> + <property name="toolTip"> + <string>TU CQ</string> + </property> + <property name="text"> + <string>F3</string> + </property> + </widget> + </item> + <item row="0" column="3"> + <widget class="QPushButton" name="pbF4"> + <property name="toolTip"> + <string>MyCall</string> + </property> + <property name="text"> + <string>F4</string> + </property> + </widget> + </item> + <item row="2" column="0"> + <widget class="QPushButton" name="pbF5"> + <property name="toolTip"> + <string>HisCall</string> + </property> + <property name="text"> + <string>F5</string> + </property> + </widget> + </item> + <item row="2" column="1"> + <widget class="QPushButton" name="pbF6"> + <property name="toolTip"> + <string>Now QueuedCall Exchange</string> + </property> + <property name="text"> + <string>F6</string> + </property> + </widget> + </item> + <item row="2" column="2"> + <widget class="QPushButton" name="pbF7"> + <property name="toolTip"> + <string>HisCall AGN ?</string> + </property> + <property name="text"> + <string>F7</string> + </property> + </widget> + </item> + <item row="2" column="3"> + <widget class="QPushButton" name="pbF8"> + <property name="toolTip"> + <string>Exchange</string> + </property> + <property name="text"> + <string>F8</string> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </widget> + </item> + <item row="2" column="0" colspan="3"> + <layout class="QGridLayout" name="gridLayout_4"> + <item row="8" column="0"> + <spacer name="verticalSpacer_8"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + <item row="3" column="2"> + <spacer name="horizontalSpacer_8"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeType"> + <enum>QSizePolicy::Minimum</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>300</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="3" column="1"> + <widget class="QSpinBox" name="sbSerialNumber_2"> + <property name="minimumSize"> + <size> + <width>75</width> + <height>0</height> + </size> + </property> + <property name="maximumSize"> + <size> + <width>100</width> + <height>16777215</height> + </size> + </property> + <property name="toolTip"> + <string>Serial number of QSO for contest exchange.</string> + </property> + <property name="alignment"> + <set>Qt::AlignCenter</set> + </property> + <property name="minimum"> + <number>1</number> + </property> + <property name="maximum"> + <number>5000</number> + </property> + <property name="value"> + <number>1</number> + </property> + </widget> + </item> + <item row="1" column="0"> + <widget class="QPushButton" name="pbSendMessage"> + <property name="minimumSize"> + <size> + <width>0</width> + <height>0</height> + </size> + </property> + <property name="toolTip"> + <string>Send and clear the message. Press Enter in the field.</string> + </property> + <property name="text"> + <string>Send message</string> + </property> + </widget> + </item> + <item row="2" column="0"> + <widget class="QLabel" name="label_3"> + <property name="sizePolicy"> + <sizepolicy hsizetype="MinimumExpanding" vsizetype="Preferred"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="maximumSize"> + <size> + <width>100</width> + <height>16777215</height> + </size> + </property> + <property name="text"> + <string>Call next </string> + </property> + <property name="alignment"> + <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> + </property> + </widget> + </item> + <item row="1" column="1" colspan="4"> + <widget class="QLineEdit" name="Tx_Message"> + <property name="toolTip"> + <string>Press Enter to send and clear the message.</string> + </property> + </widget> + </item> + <item row="3" column="0"> + <widget class="QLabel" name="label_6"> + <property name="text"> + <string>Serial Number </string> + </property> + <property name="alignment"> + <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> + </property> + </widget> + </item> + <item row="2" column="1"> + <widget class="QLineEdit" name="lineEdit"> + <property name="maximumSize"> + <size> + <width>100</width> + <height>16777215</height> + </size> + </property> + <property name="toolTip"> + <string>Callsign to be worked next.</string> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </widget> <widget class="QWidget" name="page_2"> <layout class="QVBoxLayout" name="verticalLayout_5"> <property name="leftMargin"> @@ -3848,111 +4260,6 @@ Double-click to reset to the standard 73 message</string> <property name="currentIndex"> <number>0</number> </property> - <item> - <property name="text"> - <string>Random</string> - </property> - </item> - <item> - <property name="text"> - <string>1/2</string> - </property> - </item> - <item> - <property name="text"> - <string>2/2</string> - </property> - </item> - <item> - <property name="text"> - <string>1/3</string> - </property> - </item> - <item> - <property name="text"> - <string>2/3</string> - </property> - </item> - <item> - <property name="text"> - <string>3/3</string> - </property> - </item> - <item> - <property name="text"> - <string>1/4</string> - </property> - </item> - <item> - <property name="text"> - <string>2/4</string> - </property> - </item> - <item> - <property name="text"> - <string>3/4</string> - </property> - </item> - <item> - <property name="text"> - <string>4/4</string> - </property> - </item> - <item> - <property name="text"> - <string>1/5</string> - </property> - </item> - <item> - <property name="text"> - <string>2/5</string> - </property> - </item> - <item> - <property name="text"> - <string>3/5</string> - </property> - </item> - <item> - <property name="text"> - <string>4/5</string> - </property> - </item> - <item> - <property name="text"> - <string>5/5</string> - </property> - </item> - <item> - <property name="text"> - <string>1/6</string> - </property> - </item> - <item> - <property name="text"> - <string>2/6</string> - </property> - </item> - <item> - <property name="text"> - <string>3/6</string> - </property> - </item> - <item> - <property name="text"> - <string>4/6</string> - </property> - </item> - <item> - <property name="text"> - <string>5/6</string> - </property> - </item> - <item> - <property name="text"> - <string>6/6</string> - </property> - </item> </widget> </item> <item> @@ -4085,7 +4392,6 @@ Double-click to reset to the standard 73 message</string> border-width: 1px; border-radius: 5px; border-color: black; - min-width: 5em; padding: 3px; }</string> </property> @@ -4284,6 +4590,9 @@ Double-click to reset to the standard 73 message</string> <property name="text"> <string>K1JT</string> </property> + <property name="maxLength"> + <number>6</number> + </property> <property name="alignment"> <set>Qt::AlignCenter</set> </property> @@ -4361,8 +4670,6 @@ Double-click to reset to the standard 73 message</string> </property> <property name="styleSheet"> <string notr="true">QLabel { - font-family: MS Shell Dlg 2; - font-size: 16pt; color : yellow; background-color : black; } @@ -4382,7 +4689,20 @@ QLabel[oob="true"] { </widget> </item> <item row="1" column="3" rowspan="2"> - <layout class="QVBoxLayout" name="verticalLayout_15"> + <widget class="QWidget" name="modeButtonsWidget"> + <layout class="QVBoxLayout" name="verticalLayout_15"> + <property name="leftMargin"> + <number>0</number> + </property> + <property name="topMargin"> + <number>0</number> + </property> + <property name="rightMargin"> + <number>0</number> + </property> + <property name="bottomMargin"> + <number>0</number> + </property> <item> <widget class="QPushButton" name="houndButton"> <property name="minimumSize"> @@ -4549,7 +4869,8 @@ QLabel[oob="true"] { </property> </widget> </item> - </layout> + </layout> + </widget> </item> <item row="2" column="4" colspan="2"> <widget class="QLabel" name="labUTC"> @@ -4561,8 +4882,6 @@ QLabel[oob="true"] { </property> <property name="styleSheet"> <string notr="true">QLabel { - font-family: MS Shell Dlg 2; - font-size: 16pt; background-color : black; color : yellow; }</string> @@ -4591,7 +4910,77 @@ QLabel[oob="true"] { </widget> </item> <item row="0" column="2" colspan="2"> - <layout class="QHBoxLayout" name="horizontalLayout_16" stretch="1,0"> + <widget class="QWidget" name="band_controls_widget"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Preferred" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <layout class="QVBoxLayout" name="band_controls_layout"> + <property name="spacing"> + <number>2</number> + </property> + <property name="leftMargin"> + <number>0</number> + </property> + <property name="topMargin"> + <number>0</number> + </property> + <property name="rightMargin"> + <number>0</number> + </property> + <property name="bottomMargin"> + <number>0</number> + </property> + <item> + <layout class="QHBoxLayout" name="decode_filter_layout"> + <property name="spacing"> + <number>12</number> + </property> + <property name="rightMargin"> + <number>8</number> + </property> + <item> + <widget class="QCheckBox" name="cbCQonly"> + <property name="toolTip"> + <string>CQ messages only.</string> + </property> + <property name="text"> + <string>CQ only</string> + </property> + </widget> + </item> + <item> + <widget class="QCheckBox" name="cbBypass"> + <property name="toolTip"> + <string>Bypass Filters toggled via Settings or the Filters menu.</string> + </property> + <property name="text"> + <string>BP</string> + </property> + </widget> + </item> + <item> + <spacer name="decode_filter_spacer"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeType"> + <enum>QSizePolicy::Expanding</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>0</width> + <height>0</height> + </size> + </property> + </spacer> + </item> + </layout> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_16" stretch="1,0"> <item> <widget class="BandComboBox" name="bandComboBox"> <property name="sizePolicy"> @@ -4677,7 +5066,10 @@ QPushButton[state="ok"] { </property> </widget> </item> - </layout> + </layout> + </item> + </layout> + </widget> </item> </layout> </item> @@ -4691,8 +5083,8 @@ QPushButton[state="ok"] { <rect> <x>0</x> <y>0</y> - <width>880</width> - <height>17</height> + <width>876</width> + <height>22</height> </rect> </property> <widget class="QMenu" name="menuFile"> @@ -4898,13 +5290,13 @@ QPushButton[state="ok"] { <addaction name="download_samples_action"/> <addaction name="actionDownload_EME_Ephemeris_Chart"/> <addaction name="separator"/> - <addaction name="actionRecommended_Audio_Settings"/> <addaction name="separator"/> <addaction name="actionKeyboard_shortcuts"/> <addaction name="actionSpecial_mouse_commands"/> <addaction name="actionShort_list_of_add_on_prefixes_and_suffixes"/> <addaction name="separator"/> <addaction name="actionCopyright_Notice"/> + <addaction name="actionTrademark_Policy"/> <addaction name="separator"/> <addaction name="actionAbout"/> </widget> @@ -4920,6 +5312,7 @@ QPushButton[state="ok"] { <addaction name="actionJT65"/> <addaction name="actionQ65"/> <addaction name="separator"/> + <addaction name="actionJTTY"/> <addaction name="actionMSK144"/> <addaction name="separator"/> <addaction name="actionFST4W"/> @@ -4968,7 +5361,7 @@ QPushButton[state="ok"] { </action> <action name="actionAbout"> <property name="text"> - <string>About WSJT-X</string> + <string>About WSJT-Xâ„¢</string> </property> <property name="menuRole"> <enum>QAction::AboutRole</enum> @@ -4991,13 +5384,16 @@ QPushButton[state="ok"] { <property name="text"> <string>Open next in directory</string> </property> + <property name="shortcut"> + <string>Ctrl+X</string> + </property> </action> <action name="actionDecode_remaining_files_in_directory"> <property name="text"> <string>Decode remaining files in directory</string> </property> <property name="shortcut"> - <string>Shift+F6</string> + <string>Alt+X</string> </property> </action> <action name="actionDelete_all_wav_files_in_SaveDir"> @@ -5173,9 +5569,6 @@ QPushButton[state="ok"] { <property name="text"> <string>Message averaging</string> </property> - <property name="shortcut"> - <string>F7</string> - </property> </action> <action name="actionInclude_averaging"> <property name="checkable"> @@ -5205,9 +5598,6 @@ QPushButton[state="ok"] { <property name="text"> <string>Echo Graph</string> </property> - <property name="shortcut"> - <string>F8</string> - </property> </action> <action name="actionEcho"> <property name="checkable"> @@ -5232,9 +5622,6 @@ QPushButton[state="ok"] { <property name="text"> <string>Fast Graph</string> </property> - <property name="shortcut"> - <string>F9</string> - </property> </action> <action name="download_samples_action"> <property name="text"> @@ -5349,6 +5736,11 @@ QPushButton[state="ok"] { <string>Shift+F1</string> </property> </action> + <action name="actionTrademark_Policy"> + <property name="text"> + <string>Trademark policy</string> + </property> + </action> <action name="fox_log_action"> <property name="checkable"> <bool>false</bool> @@ -5552,14 +5944,6 @@ QPushButton[state="ok"] { <string>Quick-Start Guide to WSJT-X 2.7 and QMAP</string> </property> </action> - <action name="actionRecommended_Audio_Settings"> - <property name="text"> - <string>Recommended audio settings</string> - </property> - <property name="whatsThis"> - <string><html><head/><body><p>Recommended Audio Settings.</p></body></html></string> - </property> - </action> <action name="actionRig_Control_Errors"> <property name="text"> <string>How to deal with rig control errors</string> @@ -6124,9 +6508,23 @@ QPushButton[state="ok"] { <string>Highlight Whitelist entries</string> </property> </action> + <action name="actionJTTY"> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="text"> + <string>JTTY</string> + </property> + </action> </widget> <layoutdefault spacing="6" margin="11"/> <customwidgets> + <customwidget> + <class>CurrentPageHeightStackedWidget</class> + <extends>QStackedWidget</extends> + <header>widgets/CurrentPageHeightStackedWidget.hpp</header> + <container>1</container> + </customwidget> <customwidget> <class>DisplayText</class> <extends>QTextBrowser</extends> @@ -6144,6 +6542,11 @@ QPushButton[state="ok"] { <container>1</container> </customwidget> <customwidget> + <class>TxDriveSlider</class> + <extends>QSlider</extends> + <header>widgets/TxDriveSlider.hpp</header> + </customwidget> + <customwidget> <class>HintedSpinBox</class> <extends>QSpinBox</extends> <header>widgets/HintedSpinBox.hpp</header> @@ -6172,7 +6575,6 @@ QPushButton[state="ok"] { <tabstops> <tabstop>decodedTextBrowser</tabstop> <tabstop>decodedTextBrowser2</tabstop> - <tabstop>cbCQonly</tabstop> <tabstop>logQSOButton</tabstop> <tabstop>stopButton</tabstop> <tabstop>monitorButton</tabstop> @@ -6183,21 +6585,64 @@ QPushButton[state="ok"] { <tabstop>stopTxButton</tabstop> <tabstop>tuneButton</tabstop> <tabstop>cbMenus</tabstop> + <tabstop>cbCQonly</tabstop> + <tabstop>cbBypass</tabstop> <tabstop>sbNB</tabstop> + <tabstop>bandComboBox</tabstop> + <tabstop>pb160</tabstop> + <tabstop>pb80</tabstop> + <tabstop>pb60</tabstop> + <tabstop>pb40</tabstop> + <tabstop>pb30</tabstop> + <tabstop>pb20</tabstop> + <tabstop>pb17</tabstop> + <tabstop>pb15</tabstop> + <tabstop>pb12</tabstop> + <tabstop>pb10</tabstop> + <tabstop>pb8</tabstop> + <tabstop>pb6</tabstop> + <tabstop>pb4</tabstop> + <tabstop>pb2</tabstop> + <tabstop>pb70</tabstop> + <tabstop>pb50</tabstop> + <tabstop>pb144</tabstop> + <tabstop>pb220</tabstop> + <tabstop>pb432</tabstop> + <tabstop>pb902</tabstop> + <tabstop>pb23</tabstop> + <tabstop>pb13</tabstop> + <tabstop>pb9</tabstop> + <tabstop>pb5G</tabstop> + <tabstop>pb10G</tabstop> + <tabstop>pb24G</tabstop> + <tabstop>labDialFreq</tabstop> + <tabstop>readFreq</tabstop> + <tabstop>houndButton</tabstop> + <tabstop>ft8Button</tabstop> + <tabstop>ft4Button</tabstop> + <tabstop>msk144Button</tabstop> + <tabstop>q65Button</tabstop> + <tabstop>jt65Button</tabstop> <tabstop>dxCallEntry</tabstop> <tabstop>dxGridEntry</tabstop> + <tabstop>DX_Call_Button</tabstop> + <tabstop>lookupButton</tabstop> + <tabstop>addButton</tabstop> + <tabstop>ignoreButton</tabstop> <tabstop>txFirstCheckBox</tabstop> + <tabstop>cbHoldTxFreq</tabstop> <tabstop>TxFreqSpinBox</tabstop> + <tabstop>sbSubmode</tabstop> <tabstop>pbR2T</tabstop> <tabstop>sbFtol</tabstop> <tabstop>pbT2R</tabstop> + <tabstop>sbMaxDrift</tabstop> <tabstop>RxFreqSpinBox</tabstop> <tabstop>rptSpinBox</tabstop> - <tabstop>sbTR</tabstop> - <tabstop>cbHoldTxFreq</tabstop> + <tabstop>sbSerialNumber</tabstop> <tabstop>sbF_Low</tabstop> <tabstop>sbF_High</tabstop> - <tabstop>sbSubmode</tabstop> + <tabstop>sbTR</tabstop> <tabstop>syncSpinBox</tabstop> <tabstop>sbCQTxFreq</tabstop> <tabstop>cbCQTx</tabstop> @@ -6205,30 +6650,81 @@ QPushButton[state="ok"] { <tabstop>cbShMsgs</tabstop> <tabstop>cbFast9</tabstop> <tabstop>cbAutoSeq</tabstop> + <tabstop>respondComboBox</tabstop> <tabstop>cbTx6</tabstop> <tabstop>cbSWL</tabstop> <tabstop>pbBestSP</tabstop> <tabstop>measure_check_box</tabstop> <tabstop>tabWidget</tabstop> - <tabstop>genStdMsgsPushButton</tabstop> - <tabstop>tx1</tabstop> <tabstop>txrb1</tabstop> - <tabstop>txb1</tabstop> - <tabstop>tx2</tabstop> <tabstop>txrb2</tabstop> - <tabstop>txb2</tabstop> - <tabstop>tx3</tabstop> <tabstop>txrb3</tabstop> - <tabstop>txb3</tabstop> - <tabstop>tx4</tabstop> <tabstop>txrb4</tabstop> - <tabstop>txb4</tabstop> - <tabstop>tx5</tabstop> <tabstop>txrb5</tabstop> - <tabstop>txb5</tabstop> - <tabstop>tx6</tabstop> <tabstop>txrb6</tabstop> + <tabstop>txb1</tabstop> + <tabstop>txb2</tabstop> + <tabstop>txb3</tabstop> + <tabstop>txb4</tabstop> + <tabstop>txb5</tabstop> <tabstop>txb6</tabstop> + <tabstop>genStdMsgsPushButton</tabstop> + <tabstop>tx1</tabstop> + <tabstop>tx2</tabstop> + <tabstop>tx3</tabstop> + <tabstop>tx4</tabstop> + <tabstop>tx5</tabstop> + <tabstop>tx6</tabstop> + <tabstop>houndQueueTextBrowser</tabstop> + <tabstop>foxTxListTextBrowser</tabstop> + <tabstop>comboBoxHoundSort</tabstop> + <tabstop>sbNlist</tabstop> + <tabstop>sbNslots</tabstop> + <tabstop>comboBoxCQ</tabstop> + <tabstop>cbWorkDupes</tabstop> + <tabstop>cbMoreCQs</tabstop> + <tabstop>pbFoxReset</tabstop> + <tabstop>pbFreeText</tabstop> + <tabstop>cbSendMsg</tabstop> + <tabstop>cb160m</tabstop> + <tabstop>cb80m</tabstop> + <tabstop>cb40m</tabstop> + <tabstop>cb30m</tabstop> + <tabstop>cb20m</tabstop> + <tabstop>cb17m</tabstop> + <tabstop>cb15m</tabstop> + <tabstop>cb12m</tabstop> + <tabstop>cb10m</tabstop> + <tabstop>cb6m</tabstop> + <tabstop>cb4m</tabstop> + <tabstop>cb2m</tabstop> + <tabstop>cb70cm</tabstop> + <tabstop>cb80mFT4</tabstop> + <tabstop>cb40mFT4</tabstop> + <tabstop>cb30mFT4</tabstop> + <tabstop>cb20mFT4</tabstop> + <tabstop>cb17mFT4</tabstop> + <tabstop>cb15mFT4</tabstop> + <tabstop>cb12mFT4</tabstop> + <tabstop>cb10mFT4</tabstop> + <tabstop>cb2mMSK</tabstop> + <tabstop>cbQRG1</tabstop> + <tabstop>sbQRG1</tabstop> + <tabstop>cbQRG2</tabstop> + <tabstop>sbQRG2</tabstop> + <tabstop>cbQRG3</tabstop> + <tabstop>sbQRG3</tabstop> + <tabstop>cbQRG4</tabstop> + <tabstop>sbQRG4</tabstop> + <tabstop>cbQRG5</tabstop> + <tabstop>sbQRG5</tabstop> + <tabstop>cbQRG6</tabstop> + <tabstop>sbQRG6</tabstop> + <tabstop>cbQRG7</tabstop> + <tabstop>sbQRG7</tabstop> + <tabstop>cbQRG8</tabstop> + <tabstop>sbQRG8</tabstop> + <tabstop>pbBandHopping</tabstop> <tabstop>WSPRfreqSpinBox</tabstop> <tabstop>sbFST4W_RxFreq</tabstop> <tabstop>sbFST4W_FTol</tabstop> @@ -6243,8 +6739,6 @@ QPushButton[state="ok"] { <tabstop>pbTxNext</tabstop> <tabstop>TxPowerComboBox</tabstop> <tabstop>outAttenuation</tabstop> - <tabstop>sbSerialNumber</tabstop> - <tabstop>DX_Call_Button</tabstop> </tabstops> <resources/> <connections/> diff --git a/widgets/mainwindow_arrl_digi.cpp b/widgets/mainwindow_arrl_digi.cpp new file mode 100644 index 00000000..616ccdf0 --- /dev/null +++ b/widgets/mainwindow_arrl_digi.cpp @@ -0,0 +1,160 @@ +#include "mainwindow.h" +#include "ui_mainwindow.h" +#include "activeStations.h" +#include "ActiveStationList.hpp" +#include "Decoder/decodedtext.h" +#include "models/Bands.hpp" +#include <QRegularExpression> +#include <QMutableMapIterator> +#include <cmath> +#include "commons.h" + +extern "C" { + void azdist_(char* MyGrid, char* HisGrid, double* utch, int* nAz, int* nEl, + int* nDmiles, int* nDkm, int* nHotAz, int* nHotABetter, fortran_charlen_t n1, fortran_charlen_t n2); +} + +void MainWindow::ARRL_Digi_Update(DecodedText dt) +{ + if(m_mode=="Q65") { + m_fetched=0; + readWidebandDecodes(); + return; + } + + // Extract information relevant for the ARRL Digi contest + QString deCall; + QString deGrid; + dt.deCallAndGrid(/*out*/deCall,deGrid); + ActiveCall ac; + RecentCall rc; + + if(deGrid.contains(MainWindow::grid_regexp)) { + if(!m_activeCall.contains(deCall) or deGrid!=m_activeCall.value(deCall).grid4) { + // Transmitting station's call is not already in QMap "m_activeCall", or grid has changed. + // Insert the call, grid, and associated fixed data into the list. + + double utch=0.0; + int nAz,nEl,nDmiles,nDkm,nHotAz,nHotABetter; + QString my_Grid = m_config.my_grid(); + if (my_Grid.length() < 5) my_Grid = m_config.my_grid().left(4)+"mm"; + QString de_Grid= deGrid.left(4)+"mm"; + azdist_(const_cast <char *> (my_Grid.toLatin1().constData()), + const_cast <char *> (de_Grid.toLatin1().constData()),&utch, + &nAz,&nEl,&nDmiles,&nDkm,&nHotAz,&nHotABetter,(fortran_charlen_t)6,(fortran_charlen_t)6); + int points=nDkm/500; + if(nDkm > 500*points) points += 1; + points += 1; + ac.grid4=deGrid; + ac.bands="......."; + ac.az=nAz; + ac.points=points; + m_activeCall[deCall]=ac; + } + } + + m_points=-1; + if(m_activeCall.contains(deCall)) { + +// Don't display stations we already worked on this band. + QString band=m_config.bands()->find(m_operatingFrequency.rx ()); + if(band=="160m" and m_activeCall[deCall].bands.indexOf("a")>=0) {m_recentCall.remove(deCall); return;} + if(band=="80m" and m_activeCall[deCall].bands.indexOf("b")>=0) {m_recentCall.remove(deCall); return;} + if(band=="40m" and m_activeCall[deCall].bands.indexOf("c")>=0) {m_recentCall.remove(deCall); return;} + if(band=="20m" and m_activeCall[deCall].bands.indexOf("d")>=0) {m_recentCall.remove(deCall); return;} + if(band=="15m" and m_activeCall[deCall].bands.indexOf("e")>=0) {m_recentCall.remove(deCall); return;} + if(band=="10m" and m_activeCall[deCall].bands.indexOf("f")>=0) {m_recentCall.remove(deCall); return;} + if(band=="6m" and m_activeCall[deCall].bands.indexOf("g")>=0) {m_recentCall.remove(deCall); return;} + + // Update the variable data for this deCall + rc.dialFreq=m_operatingFrequency.rx (); + rc.audioFreq=dt.frequencyOffset(); + rc.snr=dt.snr(); + m_latestDecodeTime=dt.timeInSeconds(); + rc.txEven = (m_latestDecodeTime % int(2*m_TRperiod)) > 0; + rc.ready2call=false; + auto const words = dt.messageWords(); + bool bCQ=!words.isEmpty() && words.at(0).left(3)=="CQ "; + if(bCQ or deGrid=="RR73" or deGrid=="73") rc.ready2call=true; + rc.decodeTime=m_latestDecodeTime; + m_recentCall[deCall]=rc; + m_points=m_activeCall.value(deCall).points; + } + updateRate(); +} + +void MainWindow::ARRL_Digi_Display() +{ + if(m_mode=="Q65") { + m_fetched=0; + readWidebandDecodes(); + return; + } + if (m_mode == "FT8" && m_specOp == SpecOp::FOX) { + if (m_ActiveStationsWidget != NULL) { + m_ActiveStationsWidget->setClickOK(true); + } + return; + } + QMutableMapIterator<QString,RecentCall> icall(m_recentCall); + QString deCall,deGrid; + int age=0; + int maxAge=m_ActiveStationsWidget->maxAge(); + int points=0; + QVector<ActiveStationListItem> rows; + + while (icall.hasNext()) { + icall.next(); + deCall=icall.key(); + age=int((m_latestDecodeTime - icall.value().decodeTime)/m_TRperiod + 0.5); + if(age<0) age=age + int(86400/m_TRperiod); + int itx=1; + if(icall.value().txEven) itx=0; + int snr=icall.value().snr; + int freq=icall.value().audioFreq; + if(age>maxAge) { + icall.remove(); + } else { + bool bReady=false; + if(age==0 and m_recentCall.value(deCall).ready2call) bReady=true; + + QString bands=m_activeCall[deCall].bands; + bool bWorkedOnBand=false; + if(m_currentBand=="160m" and bands.mid(0,1)!=".") bWorkedOnBand=true; + if(m_currentBand=="80m" and bands.mid(1,1)!=".") bWorkedOnBand=true; + if(m_currentBand=="40m" and bands.mid(2,1)!=".") bWorkedOnBand=true; + if(m_currentBand=="20m" and bands.mid(3,1)!=".") bWorkedOnBand=true; + if(m_currentBand=="15m" and bands.mid(4,1)!=".") bWorkedOnBand=true; + if(m_currentBand=="10m" and bands.mid(5,1)!=".") bWorkedOnBand=true; + if(m_currentBand=="6m" and bands.mid(6,1)!=".") bWorkedOnBand=true; + + if((bReady or !m_ActiveStationsWidget->readyOnly()) and !bWorkedOnBand) { + int az=m_activeCall[deCall].az; + deGrid=m_activeCall[deCall].grid4; + points=m_activeCall[deCall].points; + float x=float(age)/(maxAge+1); + if(x>1.0) x=0; + QString t1; + if(!bReady) t1 = t1.asprintf(" %3d %+2.2d %4d %1d %2d %4d",az,snr,freq,itx,age,points); + if(bReady) t1 = t1.asprintf(" %3d %+2.2d %4d %1d %2d*%4d",az,snr,freq,itx,age,points); +// t1 = (deCall + " ").left(6) + " " + m_activeCall[deCall].grid4 + t1 + " " + bands; + t1 = (deCall + " ").left(6) + " " + m_activeCall[deCall].grid4 + t1; + rows.append({points - x, t1}); + } + } + } + if(rows.isEmpty()) return; + m_ActiveStationsWidget->setClickOK(false); + int maxRecent=qMin(m_ActiveStationsWidget->maxRecent(), MaxActiveStationRows); + rows=sorted_limited_active_station_items(rows, maxRecent, true); + std::fill(m_ready2call.begin(), m_ready2call.end(), QString {}); + QString t; + for(int i=0; i<rows.size(); i++) { + m_ready2call[i]=rows[i].text; + QString t1=QString::number(i + 1) + ". "; + if(i + 1<10) t1=" " + t1; + t += (t1 + rows[i].text + "\n"); + } + if(m_ActiveStationsWidget!=NULL) m_ActiveStationsWidget->displayRecentStations(ActiveStations::DisplayMode::Standard,t); + m_ActiveStationsWidget->setClickOK(true); +} diff --git a/widgets/mainwindow_bandhopping.cpp b/widgets/mainwindow_bandhopping.cpp new file mode 100644 index 00000000..c04b93cc --- /dev/null +++ b/widgets/mainwindow_bandhopping.cpp @@ -0,0 +1,236 @@ +#include "mainwindow.h" +#include "ui_mainwindow.h" +#include "Configuration.hpp" +#include "models/Bands.hpp" +#include "models/FrequencyList.hpp" +#include "models/Modes.hpp" +#include "widgets/BandHopping.hpp" +#include "widegraph.h" + +#include <cmath> +#include <cstddef> +#include <limits> + +#include <QDateTime> +#include <QTimer> + +extern bool m_displayBand; +extern bool keep_frequency; + +namespace +{ + enum class BandHopMode + { + FT8, + FT4, + MSK144, + CustomQRG + }; + + struct BandHopEntry + { + QAbstractButton * checkbox_; + BandHopMode mode_; + int frequency_; + QSpinBox * custom_frequency_; + }; + + Radio::Frequency resolveBandHopFrequency (FrequencyList_v2_101 const& frequencies, + Bands const& bands, + Radio::Frequency requested, + IARURegions::Region region, + Modes::Mode mode) + { + auto const target_band = bands.find (requested); + if (target_band.isEmpty ()) return 0; + + auto const now = QDateTime::currentDateTimeUtc (); + Radio::Frequency result {0}; + Radio::FrequencyDelta delta {std::numeric_limits<Radio::FrequencyDelta>::max ()}; + for (auto const& candidate : frequencies.frequency_list ()) + { + if (region != IARURegions::ALL + && candidate.region_ != IARURegions::ALL + && candidate.region_ != region) continue; + if (candidate.mode_ != Modes::ALL && candidate.mode_ != mode) continue; + if (candidate.start_time_.isValid () && candidate.start_time_ > now) continue; + if (candidate.end_time_.isValid () && candidate.end_time_ < now) continue; + if (bands.find (candidate.frequency_) != target_band) continue; + if (candidate.preferred_) return candidate.frequency_; + + Radio::FrequencyDelta const candidate_delta = + static_cast<Radio::FrequencyDelta> (requested) + - static_cast<Radio::FrequencyDelta> (candidate.frequency_); + if (std::abs (candidate_delta) < std::abs (delta)) + { + delta = candidate_delta; + result = candidate.frequency_; + } + } + return result; + } +} + +void MainWindow::bandHoppingTimer() +{ + if(ui->pbBandHopping->isChecked()) { + static int startIndex = 0; + int nextStartIndex = startIndex +1; + switch (startIndex){ + case 0: + startIndex = nextStartIndex; // band hopping every other minute + return; + case 1: + bandHopping(); + startIndex = 0; + return; + } + } +} + +void MainWindow::bandHopping(bool user_requested) +{ + if (!ui->pbBandHopping->isChecked()) return; + bool const schedule_blocked = ui->autoButton->isChecked() || ui->tuneButton->isChecked (); + + static int startIndex = 0; + + BandHopEntry entries[] = + { + {ui->cb160m, BandHopMode::FT8, 1840000, nullptr}, + {ui->cb80m, BandHopMode::FT8, 3573000, nullptr}, + {ui->cb60m, BandHopMode::FT8, 5357000, nullptr}, + {ui->cb40m, BandHopMode::FT8, 7074000, nullptr}, + {ui->cb30m, BandHopMode::FT8, 10136000, nullptr}, + {ui->cb20m, BandHopMode::FT8, 14074000, nullptr}, + {ui->cb17m, BandHopMode::FT8, 18100000, nullptr}, + {ui->cb15m, BandHopMode::FT8, 21074000, nullptr}, + {ui->cb12m, BandHopMode::FT8, 24915000, nullptr}, + {ui->cb10m, BandHopMode::FT8, 28074000, nullptr}, + {ui->cb6m, BandHopMode::FT8, 50313000, nullptr}, + {ui->cb4m, BandHopMode::FT8, 70154000, nullptr}, + {ui->cb2m, BandHopMode::FT8, 144174000, nullptr}, + {ui->cb70cm, BandHopMode::FT8, 432174000, nullptr}, + {ui->cb80mFT4, BandHopMode::FT4, 3575000, nullptr}, + {ui->cb40mFT4, BandHopMode::FT4, 7047500, nullptr}, + {ui->cb30mFT4, BandHopMode::FT4, 10140000, nullptr}, + {ui->cb20mFT4, BandHopMode::FT4, 14080000, nullptr}, + {ui->cb17mFT4, BandHopMode::FT4, 18104000, nullptr}, + {ui->cb15mFT4, BandHopMode::FT4, 21140000, nullptr}, + {ui->cb12mFT4, BandHopMode::FT4, 24919000, nullptr}, + {ui->cb10mFT4, BandHopMode::FT4, 28180000, nullptr}, + {ui->cb2mMSK, BandHopMode::MSK144, 144360000, nullptr}, + {ui->cbQRG1, BandHopMode::CustomQRG, 0, ui->sbQRG1}, + {ui->cbQRG2, BandHopMode::CustomQRG, 0, ui->sbQRG2}, + {ui->cbQRG3, BandHopMode::CustomQRG, 0, ui->sbQRG3}, + {ui->cbQRG4, BandHopMode::CustomQRG, 0, ui->sbQRG4}, + {ui->cbQRG5, BandHopMode::CustomQRG, 0, ui->sbQRG5}, + {ui->cbQRG6, BandHopMode::CustomQRG, 0, ui->sbQRG6}, + {ui->cbQRG7, BandHopMode::CustomQRG, 0, ui->sbQRG7}, + {ui->cbQRG8, BandHopMode::CustomQRG, 0, ui->sbQRG8}, + }; + + auto const entry_count = sizeof entries / sizeof entries[0]; + std::vector<bool> selected (entry_count); + for (std::size_t index = 0; index < entry_count; ++index) + { + selected[index] = entries[index].checkbox_->isChecked (); + } + + // Checkboxes are live controls; a user can leave the active set empty while + // band hopping remains on, so the scan must terminate without recursive wrap. + auto const hop_index = next_band_hop_index (selected, startIndex); + if (hop_index < 0) + { + startIndex = 0; + showStatusMessage (tr ("Band hopping has no selected frequencies.")); + return; + } + + auto const& entry = entries[hop_index]; + auto const frequency = BandHopMode::CustomQRG == entry.mode_ + ? entry.custom_frequency_->value () * 1000 + : entry.frequency_; + + auto const origin = user_requested + ? FrequencyRequestOrigin::User + : FrequencyRequestOrigin::Automatic; + auto const skip_hop = [&] { + if (!user_requested) startIndex = hop_index + 1; + }; + if (!nominalFrequencyChangeAllowed (origin)) + { + skip_hop (); + return; + } + if (schedule_blocked) + { + skip_hop (); + return; + } + if (entry.mode_ == BandHopMode::CustomQRG) + { + keep_frequency = true; + if (!RigFrequencyChangePolicy::requestWhileMonitoring ( + m_monitoring, + [this] (bool state) {monitor (state);}, + [this, frequency, origin] { + return requestNominalFrequencyChange (frequency, origin); + })) + { + keep_frequency = false; + skip_hop (); + return; + } + m_displayBand = false; + QTimer::singleShot (250, [=] {keep_frequency = false;}); + setXIT (ui->TxFreqSpinBox->value ()); + on_actionFT8_triggered (); + ui->pbBandHopping->setChecked (true); + startIndex = hop_index + 1; + return; + } + + Modes::Mode mode {Modes::FT8}; + if (entry.mode_ == BandHopMode::FT4) mode = Modes::FT4; + if (entry.mode_ == BandHopMode::MSK144) mode = Modes::MSK144; + auto const requested_frequency = resolveBandHopFrequency ( + *m_config.frequencies (), *m_config.bands (), frequency, m_config.region (), mode); + if (!requested_frequency) + { + skip_hop (); + return; + } + + auto const previous_frequency = m_operatingFrequency.rx (); + if (!RigFrequencyChangePolicy::requestWhileMonitoring ( + m_monitoring, + [this] (bool state) {monitor (state);}, + [this, requested_frequency, origin] { + return requestNominalFrequencyChange (requested_frequency, origin); + })) + { + skip_hop (); + return; + } + + m_displayBand = false; + keep_frequency = true; + switch (entry.mode_) + { + case BandHopMode::FT8: on_actionFT8_triggered (); break; + case BandHopMode::FT4: on_actionFT4_triggered (); break; + case BandHopMode::MSK144: on_actionMSK144_triggered (); break; + case BandHopMode::CustomQRG: Q_UNREACHABLE (); + } + keep_frequency = false; + + auto const& row = m_config.frequencies ()->best_working_frequency (requested_frequency); + if (row >= 0) ui->bandComboBox->setCurrentIndex (row); + m_bandEdited = true; + applyBandChange (requested_frequency, previous_frequency); + setXIT (ui->TxFreqSpinBox->value ()); + m_wideGraph->setRxBand (m_config.bands ()->find (requested_frequency)); + ui->pbBandHopping->setChecked (true); + startIndex = hop_index + 1; +} diff --git a/widgets/mainwindow_jtty.cpp b/widgets/mainwindow_jtty.cpp new file mode 100644 index 00000000..91058f4d --- /dev/null +++ b/widgets/mainwindow_jtty.cpp @@ -0,0 +1,1176 @@ +#include "mainwindow.h" +#include "ui_mainwindow.h" +#include "widegraph.h" +#include "commons.h" +#include "JttyMessages.hpp" +#include "JttyN1mm.hpp" +#include "JttyReplay.hpp" +#include "Logger.hpp" +#include <QByteArray> +#include <QDateTime> +#include "Modulator/Modulator.hpp" +#include <algorithm> +#include <array> +#include <iostream> +#include <vector> +#ifdef WIN32 +#include "MMTTYIF.hpp" +#undef MessageBox +#endif + + +extern dec_data_t& dec_data; +extern qint32 g_iptt; + +namespace +{ + Jtty::NativeExchangeProfile jttyExchangeProfile(Configuration const& configuration) + { + switch (configuration.special_op_id()) { + case Configuration::SpecialOperatingActivity::FIELD_DAY: + return Jtty::NativeExchangeProfile::FieldDay; + case Configuration::SpecialOperatingActivity::RTTY: + return Jtty::NativeExchangeProfile::RttyRoundup; + default: + return Jtty::NativeExchangeProfile::None; + } + } + + Jtty::NativeMacroContext jttyNativeMacroContext( + Configuration const& configuration, QString const& hisCall, int serialNumber) + { + Jtty::NativeMacroContext context; + context.myCall = configuration.my_callsign(); + context.hisCall = hisCall; + context.serialNumber = serialNumber; + context.grid = configuration.my_grid(); + context.exchangeProfile = jttyExchangeProfile(configuration); + + switch (context.exchangeProfile) { + case Jtty::NativeExchangeProfile::FieldDay: + context.configuredExchange = Jtty::normalizedFieldDayExchange( + configuration.Field_Day_Exchange()); + break; + case Jtty::NativeExchangeProfile::RttyRoundup: + context.configuredExchange = configuration.RTTY_Exchange(); + break; + default: + break; + } + return context; + } + + QString jttyNativeEncodeError(int status) + { + if (status == static_cast<int>(Jtty::NativeEncodeStatus::UnknownSection)) { + return QStringLiteral("Field Day section is not registered in the ARRL/RAC table"); + } + return QStringLiteral("native atom encoding failed"); + } +} + +#define FCL fortran_charlen_t + +namespace +{ + constexpr int jttyMaxUpdates = 30; + constexpr int jttyMessageSize = Jtty::maxMessageLength; + constexpr int jttyUpdateBufferSize = jttyMaxUpdates * jttyMessageSize; + + QString formatJttyDecodeLine (float frequency, QString const& message) + { + QString const frequencyText = QStringLiteral("%1").arg(qRound(frequency), 4); + return message.isEmpty() ? frequencyText : frequencyText + QStringLiteral(" ") + message; + } +} + +extern "C" { + void rjtty_sub_(short int d2[], int* k, int* nsps, int* nfa, int*nfb, + float* f0, float* ftol); + + // Bounds the scan to [istart0,istop] (sample indices into d2) instead of + // the whole buffer -- see MainWindow::jtty_decode_windowed(). + void rjtty_sub_windowed_(short int d2[], int* k, int* nsps, int* nfa, int*nfb, + float* f0, float* ftol, int* istart0, int* istop); + + void jtty_get_updates_(char text_blocks[], qint64 message_ids[], + float frequencies[], float start_tsync[], bool eom[], + int* count, fortran_charlen_t); + + void genjtty_profile_(char * msg, int const* exchange_profile, + int itone[], int* nsym, fortran_charlen_t); + void genjtty_atoms_c(Jtty::NativeAtomDescriptor const atoms[], int natoms, + int itone[], int* nsym, int* status); + + void gen_jttywave_(int itone[], int* nsym, int* nsps, float* bt, float* fsample, float* f0, + float xjunk[], float wave[], int* icmplx, int* nwave); +} + +#ifdef WIN32 +static QString append_separator(QString message) { + if (!message.isEmpty()) { + QChar lastChar = message.at(message.length() - 1); + if (lastChar != '\r' && lastChar != '\n' && lastChar != ' ') { + message += "\r\n"; + } + } + return message; +} +#endif + +void MainWindow::jtty_save_wav() +{ + // Reject callers that arrive before a real JTTY capture exists; m_k0 is + // still the initial sentinel, or is stale from an earlier interval. + if (!Jtty::wavCaptureValid (m_k0)) return; + if (m_k0 == m_jttyLastSavedWavK0) return; //Guard against re-saving same audio under a new timestamp + m_jttyLastSavedWavK0 = m_k0; + + //Save JTTY data to a .wav file + QDateTime now {QDateTime::currentDateTimeUtc ()}; + qint64 ms = m_k0/12; + auto const& tstart=now.addMSecs(-ms); + m_fnameWE=m_config.save_directory().absoluteFilePath (tstart.toString("yyMMdd_hhmmss")); + int samples=m_k0; + QString dgrd = "jtty"; + save_wave_file (m_fnameWE, samples, m_freqNominalPeriod, dgrd); + // "Save decoded" keeps the file only if something was decoded; give the + // decoder a further 3 seconds to finish before killWaveFile() decides. + if (m_saveDecoded) killFileTimer.start (3000); +} + +void MainWindow::updateJttyDecodeHeadings() +{ + QString const prefix = ui->cbIncludeTime->isChecked() + ? QStringLiteral(" UTC Freq ") : QStringLiteral("Freq "); + ui->lh_decodes_headings_label->setText(prefix + tr ("Message")); + ui->rh_decodes_headings_label->setText(prefix + tr ("Message")); +} + +void MainWindow::on_cbIncludeTime_toggled(bool) +{ + if (m_mode == "JTTY") { + updateJttyDecodeHeadings(); + renderJttyAllFreqLines(); + renderJttyQsoLines(); + } +} + +void MainWindow::renderJttyAllFreqLines() +{ + if (m_jttyAllFreqLines.isEmpty()) return; + + QStringList displayLines; + for (auto const& line : m_jttyAllFreqLines) { + QString displayLine = formatJttyDecodeLine ( + line.frequency, Jtty::wrapMessage (line.text)); + if (ui->cbLowerCase->isChecked ()) displayLine = displayLine.toLower (); + if (ui->cbIncludeTime->isChecked ()) { + QString const time = Jtty::jttyLineTimeLabel (line.messageStartUtc); + if (!time.isEmpty ()) displayLine = time + " " + displayLine; + } + displayLines.append (displayLine); + } + + QTextCharFormat format; + format.setFont (ui->decodedTextBrowser->contentFont ()); + + QTextCursor cursor = ui->decodedTextBrowser->textCursor (); + if (m_jttyAllFreqsGroupStart.isValid ()) { + cursor.setPosition (m_jttyAllFreqsGroupStart.position ()); + cursor.movePosition (QTextCursor::End, QTextCursor::KeepAnchor); + cursor.removeSelectedText (); + } else { + cursor.movePosition (QTextCursor::End); + if (cursor.position () > 0) cursor.insertBlock (); + } + m_jttyAllFreqsGroupStart = cursor.block (); + cursor.insertText (displayLines.join (QChar {'\n'}), format); + ui->decodedTextBrowser->setTextCursor (cursor); + ui->decodedTextBrowser->ensureCursorVisible (); +} + +void MainWindow::renderJttyQsoLines() +{ + if (m_jttyQsoLines.isEmpty ()) { + m_jttyQsoRenderedLowerCase = ui->cbLowerCase->isChecked (); + m_jttyQsoRenderedIncludeTime = ui->cbIncludeTime->isChecked (); + return; + } + + QTextCursor cursor = ui->decodedTextBrowser2->textCursor (); + if (m_jttyQsoGroupStart.isValid () && m_jttyQsoGroupEnd.isValid () + && m_jttyQsoGroupEndPosition >= m_jttyQsoGroupStart.position ()) { + cursor.setPosition (m_jttyQsoGroupStart.position ()); + cursor.setPosition (m_jttyQsoGroupEndPosition, QTextCursor::KeepAnchor); + cursor.removeSelectedText (); + } else { + cursor.movePosition (QTextCursor::End); + if (cursor.position () > 0) cursor.insertBlock (); + } + + QTextCharFormat format; + format.setFont (ui->decodedTextBrowser2->contentFont ()); + m_jttyQsoGroupStart = cursor.block (); + QStringList renderedLines; + for (auto const& line : m_jttyQsoLines) { + QString display = formatJttyDecodeLine ( + line.frequency, Jtty::wrapMessage (line.text)); + if (ui->cbLowerCase->isChecked ()) display = display.toLower (); + if (ui->cbIncludeTime->isChecked ()) { + QString const time = Jtty::jttyLineTimeLabel (line.messageStartUtc); + if (!time.isEmpty ()) display = time + " " + display; + } + renderedLines.append (display); + } + cursor.insertText (renderedLines.join (QChar {'\n'}), format); + m_jttyQsoGroupEnd = cursor.block (); + m_jttyQsoGroupEndPosition = cursor.position (); + ui->decodedTextBrowser2->setTextCursor (cursor); + m_jttyQsoRenderedLowerCase = ui->cbLowerCase->isChecked (); + m_jttyQsoRenderedIncludeTime = ui->cbIncludeTime->isChecked (); +} + +bool MainWindow::jtty_decode(int k, int istart0, int istop) +{ + auto jttyLineDateTimeUtc = [this, k] (float tsync) -> QDateTime { + if (m_diskData && m_UTCdiskDateTime.isValid()) { + return m_UTCdiskDateTime.addMSecs(qRound64(1000.0 * tsync)).toUTC(); + } + double const elapsed = qMax(0.0, double(k) / 12000.0 - double(tsync)); + return QDateTime::currentDateTimeUtc().addMSecs(-qRound64(1000.0 * elapsed)); + }; + auto jttyLineDisplayDateTimeUtc = [this, &jttyLineDateTimeUtc] (float tsync) -> QDateTime { + if (m_diskData) { + return Jtty::jttyLineStartTimeUtc (m_UTCdiskDateTime, m_UTCdisk, tsync); + } + return jttyLineDateTimeUtc (tsync); + }; + int nsps=384; + // A non-advancing sample position starts a distinct displayed decode session. + bool const newAllFreqsSession = (k <= m_jttyLastAllFreqsK); + m_jttyLastAllFreqsK = k; + if (newAllFreqsSession) { + flushJttyDecodeLines(); + m_jttyAllFreqsGroupStart = QTextBlock(); + m_jttyQsoGroupStart = QTextBlock(); + m_jttyQsoGroupEnd = QTextBlock(); + m_jttyQsoGroupEndPosition = -1; + m_jttyQsoLines.clear(); + m_jttyAllFreqLines.clear(); + m_bDecoded = false; + m_jttyLastSavedWavK0 = -1; + } + float f0 = ui->RxFreqSpinBox_2->value(); + float ftol = ui->sbFtol_2->value(); + int nfa = m_wideGraph->nStartFreq(); + int nfb = m_wideGraph->Fmax(); + + if (istart0 < 0) { + rjtty_sub_(dec_data.d2,&k,&nsps,&nfa,&nfb,&f0,&ftol); + } else { + rjtty_sub_windowed_(dec_data.d2,&k,&nsps,&nfa,&nfb,&f0,&ftol,&istart0,&istop); + } + + QVector<Jtty::MessageUpdate> updates; + int updateCount {0}; + do { + std::array<char, jttyUpdateBufferSize> textBlocks {}; + std::array<qint64, jttyMaxUpdates> messageIds {}; + std::array<float, jttyMaxUpdates> frequencies {}; + std::array<float, jttyMaxUpdates> sequenceStarts {}; + std::array<bool, jttyMaxUpdates> complete {}; + jtty_get_updates_(textBlocks.data(), messageIds.data(), frequencies.data(), + sequenceStarts.data(), complete.data(), &updateCount, + (FCL)jttyUpdateBufferSize); + for (int i = 0; i < updateCount; ++i) { + QString const text = QString::fromLatin1( + textBlocks.data() + i * jttyMessageSize, jttyMessageSize).trimmed(); + if (messageIds[i] <= 0) continue; + updates.append({messageIds[i], frequencies[i], text, + sequenceStarts[i], complete[i]}); + } + } while (updateCount == jttyMaxUpdates); + + bool const allHistoryChanged = Jtty::mergeMessageUpdates( + m_jttyAllFreqLines, updates, + [this, &jttyLineDateTimeUtc, &jttyLineDisplayDateTimeUtc] (Jtty::MessageUpdate const& update) { + JttyDecodeLine decodeLine; + decodeLine.messageId = update.messageId; + decodeLine.frequency = update.frequency; + decodeLine.text = update.text; + decodeLine.sequenceStart = update.sequenceStart; + decodeLine.messageStartUtc = jttyLineDisplayDateTimeUtc (update.sequenceStart); + decodeLine.complete = update.complete; + decodeLine.context = currentDecodeOperatingContext(); + decodeLine.context.sequenceStart = jttyLineDateTimeUtc(update.sequenceStart); + return decodeLine; + }); + + if (allHistoryChanged) renderJttyAllFreqLines (); + + for (auto& known : m_jttyAllFreqLines) { + if (known.complete && !known.written) { + write_all("Rx", formatJttyDecodeLine(known.frequency, known.text), &known.context); + known.written = true; + } + } + + bool const qsoDisplayOptionsChanged = !m_jttyQsoLines.isEmpty() + && (m_jttyQsoRenderedLowerCase != ui->cbLowerCase->isChecked() + || m_jttyQsoRenderedIncludeTime != ui->cbIncludeTime->isChecked()); + bool anyEom {false}; + bool anyLineChanged {false}; + for (auto const& update : updates) { + auto known = std::find_if(m_jttyQsoLines.begin(), m_jttyQsoLines.end(), + [&update] (JttyQsoLine const& line) { + return line.messageId == update.messageId; + }); + bool const alreadyPresent = known != m_jttyQsoLines.end(); + if (!Jtty::shouldApplyToQsoHistory( + alreadyPresent, update.frequency, f0, ftol)) { + continue; + } + if (update.complete) anyEom = true; + + QString delta; +#ifdef WIN32 + bool startNew{false}; //Set to "true" when N1MM should start display of text on a new line +#endif + if (alreadyPresent) { + auto const change = Jtty::compareMessages(known->text, update.text); + bool const frequencyChanged = known->frequency != update.frequency; + if (!change.messageChanged && !frequencyChanged) continue; + if (change.messageChanged) { + if (change.extendsMessage) { + delta = change.appendedText; +#ifdef WIN32 + startNew = change.startsMessage; +#endif + } else { + delta = update.text; +#ifdef WIN32 + startNew = true; +#endif + } + } + known->frequency = update.frequency; + known->text = update.text; + } else { +#ifdef WIN32 + startNew = true; +#endif + delta = update.text; + auto const allLine = std::find_if ( + m_jttyAllFreqLines.cbegin (), m_jttyAllFreqLines.cend (), + [&update] (JttyDecodeLine const& line) { + return line.messageId == update.messageId; + }); + QDateTime const messageStartUtc = allLine != m_jttyAllFreqLines.cend () + ? allLine->messageStartUtc + : jttyLineDisplayDateTimeUtc (update.sequenceStart); + m_jttyQsoLines.append({update.messageId, update.frequency, update.text, + update.sequenceStart, messageStartUtc}); + } + anyLineChanged = true; + m_bDecoded = true; + +#ifdef WIN32 + if (m_mmttyif && !delta.isEmpty()) { +// m_mmttyif->echo_message_to_n1mm(append_separator(delta)); + if(ui->cbLowerCase->isChecked()) delta = delta.toLower(); + if(startNew) delta = "\r\n" + delta; + m_mmttyif->echo_message_to_n1mm(delta); + } +#endif + } + + if (anyLineChanged || qsoDisplayOptionsChanged) renderJttyQsoLines (); + return anyEom; +} + +void MainWindow::jtty_tx(QString message) +{ + // Render and enqueue immediately; the shared transmit buffer chains messages + // gaplessly while playback is underway. + submitJttyText(message); +} + +qint64 MainWindow::submitJttyText(QString message) +{ + qint64 const requestId = ++m_jttyTxRequestId; + execute_jtty_tx(requestId, message); + return requestId; +} + +void MainWindow::submitJttyDraft(QString message) +{ + if (m_jttyDraftAcceptanceTracker.hasPendingSubmissionForCurrentDraft ()) { + ui->Tx_Message->selectAll (); + return; + } + + qint64 const requestId = ++m_jttyTxRequestId; + m_jttyDraftAcceptanceTracker.trackSubmission (requestId); + execute_jtty_tx (requestId, message); + if (m_jttyDraftAcceptanceTracker.isPending (requestId)) { + ui->Tx_Message->selectAll (); + } +} + +void MainWindow::execute_jtty_tx(qint64 requestId, QString message) +{ + int itone[944]; + // Captured before anything below can change m_jttyTxActive: true means + // this message is being queued behind one still transmitting, not + // starting a fresh session. + bool const isChainedMessage = m_jttyTxActive; + if(ui->cbLowerCase->isChecked()) message = message.toLower(); + + auto const preparedMessage = Jtty::prepareTransmitText(message); + if (preparedMessage.changed()) { + LOG_WARN("JTTY transmit message was normalized or shortened before encoding"); + } + message = preparedMessage.text; + if (message.isEmpty()) { + Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::Empty); + return; + } + + // Keep message as the logical text; the chained leading space is only + // transport spacing and must not leak into logging, display, or the contest + // serial check in completeJttyTxEnqueue. + auto transmitFrame = Jtty::transmitFrame(message, isChainedMessage).toLatin1(); + + int nsym=0; + int const exchangeProfile = static_cast<int>(jttyExchangeProfile(m_config)); + genjtty_profile_(transmitFrame.data(), &exchangeProfile, + &itone[0], &nsym, (FCL)80); + if (nsym <= 0) { + LOG_WARN("JTTY transmit message could not be encoded"); + Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::EncodingFailed); + return; + } + + message = QString::fromLatin1(transmitFrame).trimmed(); + execute_jtty_tones(requestId, message, itone, nsym); +} + +void MainWindow::execute_jtty_tones(qint64 requestId, QString const& message, + int const itone[], int nsym) +{ + m_nsym_jtty=nsym; + + int nsps4=4*384; + float bt=2.0; + float fsample=48000.0; + float f0=ui->TxFreqSpinBox_2->value (); + int icmplx=0; + int nwave=nsps4*m_nsym_jtty; + + bool const newSession = !m_jttyTxActive; + if (newSession) { + advanceJttyTxQueueEpoch(); + m_jttyTxUsesTciAudio = m_tci_audio; + } + bool const useTciAudio = m_jttyTxUsesTciAudio; + + std::vector<float> wave(nwave > 0 ? nwave : 1); + gen_jttywave_(const_cast<int *>(itone), &m_nsym_jtty, &nsps4, &bt, &fsample, &f0, + wave.data(), wave.data(), &icmplx, &nwave); + + QVector<qint16> samples; + samples.reserve(nwave); + for(int i=0; i<nwave; ++i) { + float v = wave[i] * 32767.0f; + if(v > 32767.0f) v = 32767.0f; + if(v < -32768.0f) v = -32768.0f; + samples.append(static_cast<qint16>(qRound(v))); + } + if (samples.isEmpty()) { + Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::EncodingFailed); + return; + } + + if (newSession) { + // A fresh JTTY session starts a new FIFO accounting baseline even after a + // natural drain, so drain totals remain session-relative. + if (useTciAudio) { + Q_EMIT m_config.transceiver_clear_jtty_pcm(m_jttyTxQueueEpoch); + } else { + m_jttyTxQueue->clear(m_jttyTxQueueEpoch); + } + } + + bool enqueued {false}; + TxAudioQueueProgress enqueueProgress; + if(useTciAudio) { + // TCI enqueue is asynchronous. MainWindow can reject a message that can + // never fit; backend occupancy failures reject only the submitted enqueue. + if (samples.size () <= TxAudioQueue::defaultCapacity ()) { + QByteArray bytes(reinterpret_cast<char const *> (samples.constData ()), + samples.size () * int (sizeof (qint16))); + qint64 const enqueueId = ++m_jttyTciEnqueueId; + m_pendingJttyTciMessages.append(PendingJttyTciMessage { + m_jttyTxQueueEpoch, + enqueueId, + requestId, + samples.size (), + message, + newSession + }); + m_jttyTxActive = true; + Q_EMIT m_config.transceiver_enqueue_jtty_pcm(bytes, m_jttyTxQueueEpoch, + enqueueId); + return; + } else { + LOG_WARN("JTTY TCI transmit FIFO capacity precheck failed; rejecting PCM enqueue"); + Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::QueueFull); + } + } else { + auto const result = m_jttyTxQueue->enqueue(samples, m_jttyTxQueueEpoch); + enqueued = result.accepted; + enqueueProgress = result.progress; + if (!enqueued) { + LOG_WARN("JTTY transmit FIFO overflow; rejecting PCM enqueue"); + } + } + + if (!enqueued) { + if (!useTciAudio) { + Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::QueueFull); + } + if (newSession) { + advanceJttyTxQueueEpoch(); + } + return; + } + + completeJttyTxEnqueue(requestId, message, enqueueProgress, newSession, useTciAudio); +} + +void MainWindow::advanceJttyTxQueueEpoch() +{ + m_jttyTxQueueEpoch = TxAudioQueueEpoch {m_jttyTxQueueEpoch.value () + 1}; + m_jttyTxQueueProgress = {}; + m_jttyTxQueueProgress.epoch = m_jttyTxQueueEpoch; +} + +qint64 MainWindow::jttyTxCommittedSamples() const +{ + return m_jttyTxQueueProgress.total_samples; +} + +void MainWindow::completeJttyTxEnqueue(qint64 requestId, QString const& message, + TxAudioQueueProgress progress, + bool newSession, bool useTciAudio) +{ + if (newSession) { + beginTxEvidenceSession (); + } + m_currentMessage = message; + qint64 const endSample = progress.total_samples; + recordAcceptedJttyTextRequest(requestId, endSample); + m_jttyTxQueueProgress = progress; + if (m_txEvidenceGeneration.isValid () && + m_txEvidenceSourceSession == m_txEvidenceSession) { + m_txPlaybackDiagnostics.commitTarget (m_txEvidenceSession, + m_txEvidenceGeneration, + progress.total_samples - 1, false); + auto const sessionId = m_txEvidenceSession; + auto const generation = m_txEvidenceGeneration; + auto const totalSamples = progress.total_samples; + QTimer::singleShot (0, this, [this, sessionId, generation, totalSamples] { + LOG_INFO (QString ("TX playout evidence JTTY target commit session=%1 generation=%2 total=%3\n%4") + .arg (sessionId.value ()).arg (generation.value ()) + .arg (totalSamples).arg (m_txPlaybackDiagnostics.diagnosticDump ())); + }); + } + m_jttyTxActive = true; + m_transmitting = true; + write_all("Tx", message); + Q_EMIT jttyTextAccepted(requestId); + + ui->decodedTextBrowser2->insertText(" "); + QTextCursor cursor = ui->decodedTextBrowser2->textCursor(); + QTextCharFormat format = cursor.charFormat(); + format.setBackground(QBrush(QColor(Qt::yellow))); + cursor.setCharFormat(format); + cursor.insertText(Jtty::wrapMessage(message)); + format.setBackground(QBrush(QColor(Qt::white))); + cursor.setCharFormat(format); + + handleJttyContestSerial(message); + + // Fault-detector watchdog: generous margin over all audio still to play (the + // whole queued session, not just this message). The happy path completes via + // the backend drain signal well before this fires. + qint64 const pendingSamples = useTciAudio + ? progress.total_samples : progress.queued_samples; + int pendingMs = int(pendingSamples / 48); + startJttyTxWatchdog(pendingMs + 1000 * m_config.txDelay() + 10000); + + monitor(false); + if(!m_diskData && (m_saveAll || m_saveDecoded) && Jtty::wavCaptureValid (m_k0)) { + jtty_save_wav(); + } + +#ifdef WIN32 + if (m_mmttyif) { + m_mmttyif->report_ptt_state(true); + } +#endif + +#ifdef WIN32 + if (m_mmttyif) { + m_mmttyif->echo_message_to_n1mm(append_separator(message)); + } +#endif + + // Only a new session starts transmit; a message appended to an already-active + // session chains gaplessly (soundcard) via the enqueue above. When PTT is not + // yet up, guiUpdate keys it and ptt1Timer -> startTx2 -> transmit starts the + // stream with the normal lead. + if (newSession && g_iptt == 1 && !m_modulator->isActive()) { + startTx2(); + } +} + +void MainWindow::recordAcceptedJttyTextRequest(qint64 requestId, qint64 endSample) +{ + m_acceptedJttyTxRequests.append(AcceptedJttyTxRequest { + m_jttyTxQueueEpoch, + requestId, + endSample + }); +} + +QVector<qint64> MainWindow::takeCompletedJttyTextRequests( + TxAudioQueueEpoch epoch, qint64 totalAtDrain) +{ + // Backends report only final drain, so per-text completion is observed when + // the accepted text's containing JTTY session has drained. + QVector<qint64> completedRequestIds; + for (int i = 0; i < m_acceptedJttyTxRequests.size ();) { + auto const accepted = m_acceptedJttyTxRequests.at (i); + if (accepted.epoch == epoch && accepted.endSample <= totalAtDrain) { + completedRequestIds.append(accepted.requestId); + m_acceptedJttyTxRequests.remove (i); + } else { + ++i; + } + } + return completedRequestIds; +} + +void MainWindow::clearAcceptedJttyTextRequests(TxAudioQueueEpoch epoch) +{ + for (int i = 0; i < m_acceptedJttyTxRequests.size ();) { + if (m_acceptedJttyTxRequests.at (i).epoch == epoch) { + m_acceptedJttyTxRequests.remove (i); + } else { + ++i; + } + } +} + +void MainWindow::handleJttyContestSerial(QString const& message) +{ + if(message.left(3).compare("TU ", Qt::CaseInsensitive) == 0) { + logQSOTimer.start(0); + int nr = ui->sbSerialNumber_2->value(); + m_xSent = QString::number(nr); + ui->sbSerialNumber_2->setValue(nr+1); + } +} + +void MainWindow::abort_jtty_tx() +{ + noteTxStopReason (TxEvidence::TxStopReason::UserHalt); + interruptJttyTx(); + +#ifdef WIN32 + if (m_mmttyif) { + m_mmttyif->report_ptt_state(false); + } +#endif + + stopTx(); +} + +void MainWindow::interruptJttyTx() +{ + if (m_mode != "JTTY" || !m_jttyTxActive) { + return; + } + + auto const interruptedEpoch = m_jttyTxQueueEpoch; + if (!m_jttyTxUsesTciAudio) { + auto const progress = m_jttyTxQueue->progress (); + captureJttyTxEvidenceTotals (progress.served_samples, + progress.total_samples, + QStringLiteral ("JTTY source totals captured before abort")); + } else { + captureJttyTxEvidenceTotals (-1, m_jttyTxQueueProgress.total_samples, + QStringLiteral ("TCI JTTY committed total captured before abort")); + } + advanceJttyTxQueueEpoch(); + clearAcceptedJttyTextRequests(interruptedEpoch); + rejectPendingJttyTciMessages(JttyTxRejectReason::Aborted); + m_pendingJttyTciMessages.clear(); + if (m_jttyTxUsesTciAudio) { + Q_EMIT m_config.transceiver_clear_jtty_pcm(m_jttyTxQueueEpoch); + } else { + m_jttyTxQueue->clear(m_jttyTxQueueEpoch); + } + resetJttyTxState(); +} + +void MainWindow::onJttyBackendDrained(TxAudioQueueDrainState drain) +{ + if (m_mode != "JTTY" || !m_jttyTxActive) { + return; + } + + if (drain.epoch != m_jttyTxQueueEpoch + || drain.total_at_drain != jttyTxCommittedSamples ()) { + return; + } + + qint64 const servedAtDrain = m_jttyTxUsesTciAudio + ? drain.total_at_drain : m_jttyTxQueue->progress ().served_samples; + captureJttyTxEvidenceTotals (servedAtDrain, drain.total_at_drain, + QStringLiteral ("JTTY source totals captured at drain")); + + auto const completedRequestIds = takeCompletedJttyTextRequests( + drain.epoch, drain.total_at_drain); + resetJttyTxState(); + stopTx(); + for (auto const requestId : completedRequestIds) { + Q_EMIT jttyTextCompleted(requestId); + } + Q_EMIT jttySessionDrained(drain.epoch.value ()); +} + +void MainWindow::onJttyBackendEnqueueAccepted(qint64 enqueueId, qint64 sampleCount, + TxAudioQueueProgress progress) +{ + if (m_mode != "JTTY" || !m_jttyTxActive + || progress.epoch != m_jttyTxQueueEpoch) { + return; + } + + for (int i = 0; i < m_pendingJttyTciMessages.size (); ++i) { + auto const pending = m_pendingJttyTciMessages.at (i); + if (pending.epoch != progress.epoch || pending.enqueueId != enqueueId) { + continue; + } + + m_pendingJttyTciMessages.remove (i); + if (sampleCount != pending.sampleCount) { + LOG_WARN("JTTY transmit backend accepted unexpected PCM sample count"); + } + bool const startsSession = pending.newSession + || m_jttyTxQueueProgress.total_samples <= 0; + completeJttyTxEnqueue(pending.requestId, pending.message, progress, + startsSession, true); + return; + } +} + +void MainWindow::onJttyBackendEnqueueFailed(TxAudioQueueEpoch epoch, + qint64 enqueueId) +{ + if (m_mode != "JTTY" || !m_jttyTxActive + || epoch != m_jttyTxQueueEpoch) { + return; + } + + LOG_WARN("JTTY transmit backend rejected PCM enqueue"); + for (int i = 0; i < m_pendingJttyTciMessages.size (); ++i) { + auto const pending = m_pendingJttyTciMessages.at (i); + if (pending.epoch != epoch || pending.enqueueId != enqueueId) { + continue; + } + m_pendingJttyTciMessages.remove (i); + Q_EMIT jttyTextRejected(pending.requestId, JttyTxRejectReason::QueueFull); + if (pending.newSession && m_jttyTxQueueProgress.total_samples <= 0) { + for (int j = 0; j < m_pendingJttyTciMessages.size (); ++j) { + if (m_pendingJttyTciMessages[j].epoch == epoch) { + m_pendingJttyTciMessages[j].newSession = true; + return; + } + } + resetJttyTxState(); + } + return; + } +} + +void MainWindow::rejectPendingJttyTciMessages(JttyTxRejectReason reason) +{ + for (auto const& pending : m_pendingJttyTciMessages) { + Q_EMIT jttyTextRejected(pending.requestId, reason); + } +} + +void MainWindow::handleJttyTxWatchdog() +{ + if (m_mode != "JTTY" || !m_jttyTxActive) { + return; + } + + LOG_WARN("JTTY transmit completion watchdog expired"); + noteTxStopReason (TxEvidence::TxStopReason::Watchdog); + interruptJttyTx(); +#ifdef WIN32 + if (m_mmttyif) { + m_mmttyif->report_ptt_state(false); + } +#endif + stopTx(); +} + +void MainWindow::resetJttyTxState() +{ + m_jttyTxWatchdog.stop(); + m_jttyTxActive = false; + m_jttyTxQueueProgress = {}; + m_jttyTxQueueProgress.epoch = m_jttyTxQueueEpoch; + m_pendingJttyTciMessages.clear(); + m_acceptedJttyTxRequests.clear(); +} + +void MainWindow::startJttyTxWatchdog(int durationMs) +{ + if (durationMs > 0) { + m_jttyTxWatchdog.start(durationMs); + } +} + +void MainWindow::jtty_again() +{ + ui->DecodeButton->setChecked (true); + qApp->processEvents(); //Update the DecodeButton highlight + replayJttyFrames (dec_data.params.kin, [this] (int k) { + jtty_decode(k); + return false; + }); + flushJttyDecodeLines(); + finishDecodeUi(); +} + +// Triggered by double-clicking WideGraph's waterfall in JTTY mode: starts +// the rescan jttyPickLookbackSecs before the clicked time (a message can +// start just before the click) and stops as soon as jtty_decode reports a +// completed (EOM) message, rather than scanning a fixed window. A safety +// cap (jttyPickSafetyCapSecs forward of istart0) bounds how long it keeps +// looking if nothing ever completes -- e.g. the click landed on noise, or +// sync was lost partway through. secondsAgo is relative to m_k0 (the +// buffer position at the last processed block, i.e. "now"). Calls where k +// hasn't yet reached istart0 are cheap no-ops on the Fortran side, so the +// outer loop doesn't need to special-case its own starting point. +void MainWindow::jttyDecodeAgainAt(float secondsAgo) +{ + constexpr int jttyPickLookbackSecs = 5; + constexpr int jttyPickSafetyCapSecs = 40; + qint64 const center = qint64(m_k0) - qint64(qMax(0.0f, secondsAgo) * 12000.0f); + int const istart0 = int(qMax(qint64(1), center - qint64(jttyPickLookbackSecs) * 12000)); + int const frames = snapshotJttyFrames (dec_data.params.kin); + int const istop = int(qMin(qint64(frames), + qint64(istart0) + qint64(jttyPickSafetyCapSecs) * 12000)); + if (istop < istart0) return; // clicked time is no longer in the buffer at all + + ui->DecodeButton->setChecked (true); + qApp->processEvents(); //Update the DecodeButton highlight + replayJttyFrames (frames, [this, istart0, istop] (int k) { + bool const eom = jtty_decode(k, istart0, istop); + return eom || k >= istop; + }); + flushJttyDecodeLines(); + finishDecodeUi(); +} + +void MainWindow::flushJttyDecodeLines() +{ + // Called at a definite session end (new session starting, or true end of file); unconditional. + for (auto& line : m_jttyAllFreqLines) { + if (line.written) continue; + QString const text = line.text.trimmed(); + if (text.isEmpty()) continue; + write_all("Rx", formatJttyDecodeLine(line.frequency, text), &line.context); + line.written = true; + } +} + +bool MainWindow::jtty_key_struck(QKeyEvent * e) +{ + if(e->key() == Qt::Key_Escape) { + abort_jtty_tx(); + return true; + } + int const functionKey=e->key()-Qt::Key_F1+1; + if(functionKey < 1 || functionKey > 8) return false; + return sendJttyFunctionKey(functionKey); +} + +bool MainWindow::sendJttyFunctionKey(int index) +{ + QString macro; + switch(index) { + case 1: macro=ui->msg1->text(); break; + case 2: macro=ui->msg2->text(); break; + case 3: macro=ui->msg3->text(); break; + case 4: macro=ui->msg4->text(); break; + case 5: macro=ui->msg5->text(); break; + case 6: macro=ui->msg6->text(); break; + case 7: macro=ui->msg7->text(); break; + case 8: macro=ui->msg8->text(); break; + default: return false; + } + if(macro.simplified().isEmpty()) return false; + + auto const context = jttyNativeMacroContext( + m_config, m_hisCall, ui->sbSerialNumber_2->value()); + auto const compiled=Jtty::compileNativeMacro(macro,context); + if(compiled.status == Jtty::NativeMacroStatus::LiteralFallback) { + jtty_tx(compiled.text); + return true; + } + + qint64 const requestId=++m_jttyTxRequestId; + if(compiled.status == Jtty::NativeMacroStatus::InvalidRuntime) { + LOG_WARN(QStringLiteral("JTTY native macro rejected: %1").arg(compiled.error)); + Q_EMIT jttyTextRejected(requestId,JttyTxRejectReason::EncodingFailed); + return true; + } + + int itone[944]; + int nsym=0; + int encodeStatus=static_cast<int>(Jtty::NativeEncodeStatus::InvalidDescriptor); + genjtty_atoms_c(compiled.atoms.constData(),compiled.atoms.size(),itone,&nsym, + &encodeStatus); + if(nsym <= 0) { + LOG_WARN(QStringLiteral("JTTY native macro rejected: %1") + .arg(jttyNativeEncodeError(encodeStatus))); + Q_EMIT jttyTextRejected(requestId,JttyTxRejectReason::EncodingFailed); + return true; + } + execute_jtty_tones(requestId,compiled.text,itone,nsym); + return true; +} + +QString MainWindow::jtty_msg_expand(QString t) +{ + auto const context = jttyNativeMacroContext( + m_config, m_hisCall, ui->sbSerialNumber_2->value()); + return Jtty::expandLiteralMacro(t, context); +} + +void MainWindow::on_RxFreqSpinBox_2_valueChanged(int n) +{ + ui->RxFreqSpinBox->setValue(n); +} + +void MainWindow::on_TxFreqSpinBox_2_valueChanged(int n) +{ + ui->TxFreqSpinBox->setValue(n); +} + +void MainWindow::on_sbFtol_2_valueChanged (int n) +{ + m_wideGraph->setTol(n); +} + +#ifdef WIN32 +void MainWindow::logText(const QString &text) { + LOG_INFO(text); +} + +QString MainWindow::jttyRejectReasonText(JttyTxRejectReason reason) const +{ + switch (reason) { + case JttyTxRejectReason::Empty: return QStringLiteral("empty"); + case JttyTxRejectReason::EncodingFailed: return QStringLiteral("encoding failed"); + case JttyTxRejectReason::QueueFull: return QStringLiteral("queue full"); + case JttyTxRejectReason::BackendRejected: return QStringLiteral("backend rejected"); + case JttyTxRejectReason::Aborted: return QStringLiteral("aborted"); + case JttyTxRejectReason::NotAvailable: return QStringLiteral("not available"); + } + return QStringLiteral("unknown"); +} + +void MainWindow::handleMmttyTxString(QString message) +{ + auto const context = jttyNativeMacroContext( + m_config, m_hisCall, ui->sbSerialNumber_2->value()); + auto const compiled = Jtty::compileN1mmMessage(message, context); + if (m_mode != "JTTY") { + if (compiled.status == Jtty::N1mmCompileStatus::Literal) { + jtty_tx(compiled.literalText); + return; + } + + qint64 const requestId = ++m_jttyTxRequestId; + m_mmttyJttyOutput.submit(requestId); + QString const reason = compiled.status == Jtty::N1mmCompileStatus::Error + ? compiled.error : QStringLiteral("tagged JTTY actions require JTTY mode"); + logText(QStringLiteral("MMTTY/N1MM tagged JTTY request %1 rejected: %2") + .arg(requestId).arg(reason)); + Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::NotAvailable); + return; + } + + if (m_mmttyJttyOutput.finishRequested()) { + logText(QStringLiteral("MMTTY/N1MM JTTY text ignored after graceful OFF")); + return; + } + + qint64 const requestId = ++m_jttyTxRequestId; + m_mmttyJttyOutput.submit(requestId); + if (compiled.status == Jtty::N1mmCompileStatus::Literal) { + execute_jtty_tx(requestId, compiled.literalText); + return; + } + if (compiled.status == Jtty::N1mmCompileStatus::Error) { + logText(QStringLiteral("MMTTY/N1MM tagged JTTY request %1 rejected: %2") + .arg(requestId).arg(compiled.error)); + Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::EncodingFailed); + return; + } + + int itone[944]; + int nsym = 0; + int encodeStatus = static_cast<int>(Jtty::NativeEncodeStatus::InvalidDescriptor); + genjtty_atoms_c(compiled.atoms.constData(), compiled.atoms.size(), itone, &nsym, + &encodeStatus); + if (nsym <= 0) { + logText(QStringLiteral("MMTTY/N1MM tagged JTTY request %1 rejected: %2") + .arg(requestId).arg(jttyNativeEncodeError(encodeStatus))); + Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::EncodingFailed); + return; + } + execute_jtty_tones(requestId, compiled.canonicalText, itone, nsym); +} + +void MainWindow::handleMmttyStartTx() +{ + if (m_mode != "JTTY" && !m_mmttyJttyOutput.pending()) { + startTx2(); + return; + } + + m_mmttyJttyOutput.start(); + startPendingMmttyJttyTx(); +} + +void MainWindow::handleMmttyStopTx() +{ + if (m_mode != "JTTY") { + noteTxStopReason (TxEvidence::TxStopReason::UserHalt); + stopTx(); + if (!m_mmttyJttyOutput.pending()) return; + } + + m_mmttyJttyOutput.finish(); + logText(QStringLiteral("MMTTY/N1MM JTTY OFF requested; waiting for backend drain")); + completeMmttyJttyOutput(); +} + +void MainWindow::handleMmttyAbortTx() +{ + m_mmttyJttyOutput.abort(); + abort_jtty_tx(); +} + +void MainWindow::handleMmttyJttyAccepted(qint64 requestId) +{ + if (!m_mmttyJttyOutput.accept(requestId)) return; + + logText(QStringLiteral("MMTTY/N1MM JTTY request %1 accepted").arg(requestId)); + startPendingMmttyJttyTx(); +} + +void MainWindow::handleMmttyJttyRejected(qint64 requestId, JttyTxRejectReason reason) +{ + if (!m_mmttyJttyOutput.resolve(requestId)) return; + + logText(QStringLiteral("MMTTY/N1MM JTTY request %1 rejected: %2") + .arg(requestId) + .arg(jttyRejectReasonText(reason))); + // Backend rejection may reset the audio session after emitting this signal. + QTimer::singleShot(0, this, [this] { completeMmttyJttyOutput(); }); +} + +void MainWindow::handleMmttyJttyCompleted(qint64 requestId) +{ + if (!m_mmttyJttyOutput.resolve(requestId)) return; + + logText(QStringLiteral("MMTTY/N1MM JTTY request %1 completed").arg(requestId)); +} + +void MainWindow::handleMmttyJttySessionDrained(qint64 sessionId) +{ + Q_UNUSED(sessionId) + completeMmttyJttyOutput(true); +} + +void MainWindow::completeMmttyJttyOutput(bool drained) +{ + if (m_mmttyJttyOutput.takeCompletion(m_jttyTxActive, drained) && m_mmttyif) { + m_mmttyif->report_output_complete(); + } +} + +void MainWindow::startPendingMmttyJttyTx() +{ + if (m_mode != "JTTY" || !m_mmttyJttyOutput.startRequested()) return; + + if (!m_jttyTxActive || jttyTxCommittedSamples () <= 0) { + logText(QStringLiteral("MMTTY/N1MM JTTY start deferred until text is accepted")); + return; + } + + if (g_iptt == 1) { + logText(QStringLiteral("MMTTY/N1MM JTTY start ignored; transmitter is already keyed")); + m_mmttyJttyOutput.started(); + return; + } + + m_mmttyJttyOutput.started(); + startTx2(); +} + +void MainWindow::initMMTTY(quint16 port) { + if (!m_mmttyif) { + m_mmttyif = new MMTTYIF(this); + } + + m_mmttyif->initialize(port); + + connect(m_mmttyif, &MMTTYIF::log_message, this, &MainWindow::logText); + connect(m_mmttyif, &MMTTYIF::app_tx_string, this, &MainWindow::handleMmttyTxString); + connect(m_mmttyif, &MMTTYIF::app_start_tx, this, &MainWindow::handleMmttyStartTx); + connect(m_mmttyif, &MMTTYIF::app_stop_tx, this, &MainWindow::handleMmttyStopTx); + connect(m_mmttyif, &MMTTYIF::app_abort_tx, this, &MainWindow::handleMmttyAbortTx); + connect(this, &MainWindow::jttyTextAccepted, this, &MainWindow::handleMmttyJttyAccepted); + connect(this, &MainWindow::jttyTextRejected, this, &MainWindow::handleMmttyJttyRejected); + connect(this, &MainWindow::jttyTextCompleted, this, &MainWindow::handleMmttyJttyCompleted); + connect(this, &MainWindow::jttySessionDrained, this, &MainWindow::handleMmttyJttySessionDrained); + + connect(m_mmttyif, &MMTTYIF::inactivity_timeout, qApp, &QCoreApplication::quit); + connect(m_mmttyif, &MMTTYIF::app_is_quitting, this, [this]() { + abort_jtty_tx(); + close(); + }); + + // Auto-switch to JTTY mode after MMTTY connects + QTimer::singleShot(3000, this, [this]() { + set_mode("JTTY"); + }); +} + +MMTTYIF *MainWindow::getMmttyIf() const { + return m_mmttyif; +} +#endif diff --git a/widgets/mainwindow_settings.cpp b/widgets/mainwindow_settings.cpp new file mode 100644 index 00000000..f7a99450 --- /dev/null +++ b/widgets/mainwindow_settings.cpp @@ -0,0 +1,637 @@ +#include "mainwindow.h" +#include "RoundRobinSelection.hpp" +#include "ui_mainwindow.h" +#include "widegraph.h" +#include "commons.h" +#include "MessageBox.hpp" +#include "widgets/messageaveraging.h" +#include "widgets/activeStations.h" +#include "widgets/FoxLogWindow.hpp" +#include "widgets/CabrilloLogWindow.hpp" +#include "widgets/QSYMessageCreator.h" +#include "widgets/qsymonitor.h" +#include "validators/CallsignValidator.hpp" +#include "qt_helpers.hpp" +#include "JttyMessages.hpp" + +#include <QSettings> +#include <QVariant> +#include <QThread> +#include <QTimer> +#include <QDebug> +#include <QMessageBox> + +extern dec_data_t& dec_data; +extern int outBufSize; +extern bool blocked; +extern int m_TxFreqFox; +extern bool HoldTxFreqStatus; +extern int m_msk144_tr; +extern int m_msk144_tr2; +extern int m_msk144_tr6; + +namespace { + Radio::Frequency constexpr default_frequency {14074000}; + constexpr int standard_messages_tab_index {0}; + constexpr int fox_queue_tab_index {1}; +} + +void MainWindow::writeSettings() +{ + m_settings->beginGroup("MainWindow"); + if (ui->actionSWL_Mode->isChecked ()) + { + m_settings->setValue ("SWLView", true); + m_settings->setValue ("ShowMenus", ui->cbMenus->isChecked ()); + m_settings->setValue ("geometry", geometries ()[0]); + m_settings->setValue ("SWLModeGeometry", saveGeometry ()); + m_settings->setValue ("geometryNoControls", geometries ()[2]); + } + else + { + if (ui->cbMenus->isChecked()) + { + m_settings->setValue ("SWLView", ui->actionSWL_Mode->isChecked ()); + m_settings->setValue ("ShowMenus", true); + m_settings->setValue ("geometry", saveGeometry ()); + m_settings->setValue ("SWLModeGeometry", geometries ()[1]); + m_settings->setValue ("geometryNoControls", geometries ()[2]); + } + else + { + m_settings->setValue ("SWLView", ui->actionSWL_Mode->isChecked ()); + m_settings->setValue ("ShowMenus", false); + m_settings->setValue ("geometry", geometries ()[0]); + m_settings->setValue ("SWLModeGeometry", geometries ()[1]); + m_settings->setValue ("geometryNoControls", saveGeometry ()); + } + } + m_settings->setValue ("state", saveState ()); + m_settings->setValue("MRUdir", m_path); + m_settings->setValue("TxFirst",m_txFirst); + m_settings->setValue("DXcall",ui->dxCallEntry->text()); + m_settings->setValue("DXgrid",ui->dxGridEntry->text()); + m_settings->setValue("AstroDisplayed", m_astroWidget && m_astroWidget->isVisible()); + m_settings->setValue("MsgAvgDisplayed", m_msgAvgWidget && m_msgAvgWidget->isVisible ()); + m_settings->setValue("FoxLogDisplayed", m_foxLogWindow && m_foxLogWindow->isVisible ()); + m_settings->setValue("ContestLogDisplayed", m_contestLogWindow && m_contestLogWindow->isVisible ()); + m_settings->setValue("ActiveStationsDisplayed", m_ActiveStationsWidget && m_ActiveStationsWidget->isVisible ()); + m_settings->setValue("QSYMessageCreatorDisplayed", m_QSYMessageCreatorWidget && m_QSYMessageCreatorWidget->isVisible ()); + m_settings->setValue("ShowQSYMessages", ui->actionEnable_QSY_Popups->isChecked()); + m_settings->setValue("QSYMonitorDisplayed", m_qsymonitorWidget && m_qsymonitorWidget->isVisible ()); + m_settings->setValue("RespondCQ",static_cast<int> (autoRespondPolicy ())); + m_settings->setValue("HoundSort",ui->comboBoxHoundSort->currentIndex()); + m_settings->setValue("FoxNlist",ui->sbNlist->value()); + m_settings->setValue("FoxNslots",m_Nslots0); + m_settings->setValue("SerialNumber",ui->sbSerialNumber->value ()); + m_settings->setValue("SerialNumberJTTY",ui->sbSerialNumber_2->value ()); + m_settings->setValue("JTTY_msg1",ui->msg1->text()); + m_settings->setValue("JTTY_msg2",ui->msg2->text()); + m_settings->setValue("JTTY_msg3",ui->msg3->text()); + m_settings->setValue("JTTY_msg4",ui->msg4->text()); + m_settings->setValue("JTTY_msg5",ui->msg5->text()); + m_settings->setValue("JTTY_msg6",ui->msg6->text()); + m_settings->setValue("JTTY_msg7",ui->msg7->text()); + m_settings->setValue("JTTY_msg8",ui->msg8->text()); + m_settings->setValue("FoxTextMsg", m_freeTextMsg0); + m_settings->setValue("WorkDupes", ui->cbWorkDupes->isChecked()); + m_settings->setValue("JTTY_LowerCase",ui->cbLowerCase->isChecked()); + m_settings->setValue("JTTY_IncludeTime",ui->cbIncludeTime->isChecked()); + m_settings->endGroup(); + + // do this in the General group because we save the parameters from various places + if(m_mode=="JT9") { + m_settings->setValue("SubMode",ui->sbSubmode->value()); + m_settings->setValue("TRPeriod", ui->sbTR->value()); + } + if(m_mode=="MSK144") m_settings->setValue("ShMsgs_MSK144",m_bShMsgs); + if(m_mode=="Q65") m_settings->setValue("ShMsgs_Q65",m_bShMsgs); + if(m_mode=="JT65") m_settings->setValue("ShMsgs_JT65",m_bShMsgs); + if(m_mode=="JT4") m_settings->setValue("ShMsgs_JT4",m_bShMsgs); + + m_settings->beginGroup("Common"); + m_settings->setValue("Mode",m_mode); + m_settings->setValue("SaveNone",ui->actionNone->isChecked()); + m_settings->setValue("SaveDecoded",ui->actionSave_decoded->isChecked()); + m_settings->setValue("SaveAll",ui->actionSave_all->isChecked()); + m_settings->setValue("RemoveAudioFiles",ui->actionRemove_after_30days->isChecked()); + m_settings->setValue("NDepth",m_ndepth); + + //ft8md + m_settings->setValue ("MultithreadedFT8decoder",ui->actionUse_multithreaded_FT8_decoder->isChecked() ); + m_settings->setValue("NFT8Cycles",m_nFT8Cycles); + m_settings->setValue("NFT8QSORXfreqSensitivity",m_nFT8RXfSens); + m_settings->setValue("FT8threads",m_ft8threads); + m_settings->setValue("FT8Sensitivity",m_ft8Sensitivity); + m_settings->setValue("FT8DecoderStart",m_ft8DecoderStart); + m_settings->setValue("FT8WideDXCallSearch",m_FT8WideDxCallSearch); + m_settings->setValue("HideFT8Dupes",ui->actionHide_FT8_dupe_messages->isChecked()); + //ft8md + + m_settings->setValue("RxFreq",ui->RxFreqSpinBox->value()); + if(m_specOp!=SpecOp::FOX) m_settings->setValue("TxFreq",ui->TxFreqSpinBox->value()); + m_settings->setValue("TxFreqFox",m_TxFreqFox); + m_settings->setValue("WSPRfreq",ui->WSPRfreqSpinBox->value()); + m_settings->setValue("FST4W_RxFreq",ui->sbFST4W_RxFreq->value()); + m_settings->setValue("FST4W_FTol",ui->sbFST4W_FTol->value()); + m_settings->setValue("JTTY_FTol",ui->sbFtol_2->value()); + m_settings->setValue("FST4_FLow",ui->sbF_Low->value()); + m_settings->setValue("FST4_FHigh",ui->sbF_High->value()); + m_settings->setValue("EchoToneSpacing",ui->sbToneSpacing->value()); + m_settings->setValue("EchoFixedTone",ui->rbFixedTone->isChecked()); + m_settings->setValue("EchoMessageRB",ui->rbEchoMessage->isChecked()); + m_settings->setValue("EchoCW",ui->rbEchoCW->isChecked()); + m_settings->setValue("EchoMessage",ui->leEchoMessage->text()); + m_settings->setValue("DTtol",m_DTtol); + m_settings->setValue("MinSync",m_minSync); + m_settings->setValue ("AutoSeq", ui->cbAutoSeq->isChecked ()); + m_settings->setValue ("RxAll", ui->cbRxAll->isChecked ()); +// m_settings->setValue("ShMsgs",m_bShMsgs); + m_settings->setValue("SWL",ui->cbSWL->isChecked()); + if(m_mode=="MSK144" && hasMsk144BaseFrequency ()) { + m_settings->setValue ("DialFreq", QVariant::fromValue(m_msk144basefreq)); // MSK144 QSY + } else { + m_settings->setValue ("DialFreq", QVariant::fromValue(m_operatingFrequency.remembered ())); + } + m_settings->setValue("SkedFreq",m_skedFreq); + m_settings->setValue("OutAttenuation", ui->outAttenuation->value ()); + m_settings->setValue("NoSuffix",m_noSuffix); + m_settings->setValue("GUItab",ui->tabWidget->currentIndex()); + m_settings->setValue("OutBufSize",outBufSize); + m_settings->setValue ("HoldTxFreq", ui->cbHoldTxFreq->isChecked ()); + m_settings->setValue ("CQonly", ui->cbCQonly->isChecked ()); + m_settings->setValue ("BypassFilters", ui->cbBypass->isChecked ()); + m_settings->setValue("PctTx", ui->sbTxPercent->value ()); + m_settings->setValue( + "RoundRobin", QString::fromStdString (BeaconTx::formatRoundRobinPolicy (configuredRoundRobinPolicy ()))); + m_settings->setValue("dBm",m_dBm); + m_settings->setValue("RR73",m_send_RR73); + m_settings->setValue ("WSPRPreferType1", ui->WSPR_prefer_type_1_check_box->isChecked ()); + m_settings->setValue("UploadSpots",m_uploadWSPRSpots); + m_settings->setValue("NoOwnCall",ui->cbNoOwnCall->isChecked()); + m_settings->setValue ("BandHopping", ui->band_hopping_group_box->isChecked ()); + m_settings->setValue ("MaxDrift", ui->sbMaxDrift->value()); + m_settings->setValue ("TRPeriod_FST4W", ui->sbTR_FST4W->value ()); + m_settings->setValue("FastMode",m_bFastMode); + m_settings->setValue("Fast9",m_bFast9); + m_settings->setValue ("CQTxfreq", ui->sbCQTxFreq->value ()); + m_settings->setValue("pwrBandTxMemory",m_pwrBandTxMemory); + m_settings->setValue("pwrBandTuneMemory",m_pwrBandTuneMemory); + m_settings->setValue ("FT8AP", ui->actionEnable_AP_FT8->isChecked ()); + m_settings->setValue ("JT65AP", ui->actionEnable_AP_JT65->isChecked ()); + m_settings->setValue ("AutoClearAvg", ui->actionAuto_Clear_Avg->isChecked ()); + m_settings->setValue ("DisableClicksOnWaterfall", ui->actionDisable_clicks_on_waterfall->isChecked ()); + m_settings->setValue("SplitterState",ui->decodes_splitter->saveState()); + m_settings->setValue("Blanker",ui->sbNB->value()); + m_settings->setValue("Score",m_score); + m_settings->setValue("EchoAvg",ui->sbEchoAvg->value()); + { + QList<QVariant> coeffs; // suitable for QSettings + for (auto const& coeff : m_phaseEqCoefficients) + { + coeffs << coeff; + } + m_settings->setValue ("PhaseEqualizationCoefficients", QVariant {coeffs}); + } + m_settings->setValue ("bh_160m", ui->cb160m->isChecked() ); + m_settings->setValue ("bh_80m", ui->cb80m->isChecked() ); + m_settings->setValue ("bh_60m", ui->cb60m->isChecked() ); + m_settings->setValue ("bh_40m", ui->cb40m->isChecked() ); + m_settings->setValue ("bh_30m", ui->cb30m->isChecked() ); + m_settings->setValue ("bh_20m", ui->cb20m->isChecked() ); + m_settings->setValue ("bh_17m", ui->cb17m->isChecked() ); + m_settings->setValue ("bh_15m", ui->cb15m->isChecked() ); + m_settings->setValue ("bh_12m", ui->cb12m->isChecked() ); + m_settings->setValue ("bh_10m", ui->cb10m->isChecked() ); + m_settings->setValue ("bh_6m", ui->cb6m->isChecked() ); + m_settings->setValue ("bh_4m", ui->cb4m->isChecked() ); + m_settings->setValue ("bh_2m", ui->cb2m->isChecked() ); + m_settings->setValue ("bh_70cm", ui->cb70cm->isChecked() ); + m_settings->setValue ("bh_2mMSK", ui->cb2mMSK->isChecked() ); + m_settings->setValue ("bh_80mFT4", ui->cb80mFT4->isChecked() ); + m_settings->setValue ("bh_40mFT4", ui->cb40mFT4->isChecked() ); + m_settings->setValue ("bh_30mFT4", ui->cb30mFT4->isChecked() ); + m_settings->setValue ("bh_20mFT4", ui->cb20mFT4->isChecked() ); + m_settings->setValue ("bh_17mFT4", ui->cb17mFT4->isChecked() ); + m_settings->setValue ("bh_15mFT4", ui->cb15mFT4->isChecked() ); + m_settings->setValue ("bh_12mFT4", ui->cb12mFT4->isChecked() ); + m_settings->setValue ("bh_10mFT4", ui->cb10mFT4->isChecked() ); + m_settings->setValue ("bh_QRG1", ui->cbQRG1->isChecked() ); + m_settings->setValue ("bh_QRG2", ui->cbQRG2->isChecked() ); + m_settings->setValue ("bh_QRG3", ui->cbQRG3->isChecked() ); + m_settings->setValue ("bh_QRG4", ui->cbQRG4->isChecked() ); + m_settings->setValue ("bh_QRG5", ui->cbQRG5->isChecked() ); + m_settings->setValue ("bh_QRG6", ui->cbQRG6->isChecked() ); + m_settings->setValue ("bh_QRG7", ui->cbQRG7->isChecked() ); + m_settings->setValue ("bh_QRG8", ui->cbQRG8->isChecked() ); + m_settings->setValue ("QRG1", ui->sbQRG1->value ()); + m_settings->setValue ("QRG2", ui->sbQRG2->value ()); + m_settings->setValue ("QRG3", ui->sbQRG3->value ()); + m_settings->setValue ("QRG4", ui->sbQRG4->value ()); + m_settings->setValue ("QRG5", ui->sbQRG5->value ()); + m_settings->setValue ("QRG6", ui->sbQRG6->value ()); + m_settings->setValue ("QRG7", ui->sbQRG7->value ()); + m_settings->setValue ("QRG8", ui->sbQRG8->value ()); + m_settings->setValue ("reduceFalseDecodes", ui->actionReduce_false_decodes->isChecked() ); + m_settings->setValue ("HideAPInfo", ui->actionHide_AP_info->isChecked() ); + m_settings->setValue ("FullDuplexMode", ui->actionFull_Duplex_Mode->isChecked() ); + m_settings->setValue ("actionDontSplitALLTXT", ui->actionDon_t_split_ALL_TXT->isChecked() ); + m_settings->setValue ("splitAllTxtYearly", ui->actionSplit_ALL_TXT_yearly->isChecked() ); + m_settings->setValue ("splitAllTxtMonthly", ui->actionSplit_ALL_TXT_monthly->isChecked() ); + m_settings->setValue ("disableWritingOfAllTxt", ui->actionDisable_writing_of_ALL_TXT->isChecked() ); + m_settings->setValue ("DisableEventLogging", ui->actionDisable_event_logging->isChecked() ); + m_settings->setValue ("DarkStyle", ui->actionUse_Dark_Style->isChecked() ); + m_settings->setValue ("BandButtons", ui->actionBand_Buttons->isChecked() ); + m_settings->setValue ("VHFUHFButtons", ui->actionVHF_UHF_Buttons->isChecked() ); + m_settings->setValue ("tx1State", m_tx1_enabled_preference); + m_settings->setValue ("HighlightB4", ui->actionHighlightB4->isChecked() ); + m_settings->setValue ("HighlightToday", ui->actionHighlightToday->isChecked() ); + m_settings->setValue ("HighlightIgnored", ui->actionHighlightIgnored->isChecked() ); + m_settings->setValue ("HideB4", ui->actionHideB4->isChecked() ); + m_settings->setValue ("HideToday", ui->actionHideToday->isChecked() ); + m_settings->setValue ("HideIgnored", ui->actionHideIgnored->isChecked() ); + m_settings->setValue ("IgnoreB4", ui->actionIgnoreB4->isChecked() ); + m_settings->setValue ("IgnoreToday", ui->actionIgnoreToday->isChecked() ); + m_settings->setValue ("IgnoreIgnored", ui->actionIgnoreIgnored->isChecked() ); + m_settings->setValue ("HideTerritory1", ui->actionHideTerritory1->isChecked() ); + m_settings->setValue ("HideTerritory2", ui->actionHideTerritory2->isChecked() ); + m_settings->setValue ("HideTerritory3", ui->actionHideTerritory3->isChecked() ); + m_settings->setValue ("HideTerritory4", ui->actionHideTerritory4->isChecked() ); + m_settings->setValue ("HighlightTerritory1", ui->actionHighlightTerritory1->isChecked() ); + m_settings->setValue ("HighlightTerritory2", ui->actionHighlightTerritory2->isChecked() ); + m_settings->setValue ("HighlightTerritory3", ui->actionHighlightTerritory3->isChecked() ); + m_settings->setValue ("HighlightTerritory4", ui->actionHighlightTerritory4->isChecked() ); + m_settings->setValue ("HideEU", ui->actionHideEU->isChecked() ); + m_settings->setValue ("HideNA", ui->actionHideNA->isChecked() ); + m_settings->setValue ("HideSA", ui->actionHideSA->isChecked() ); + m_settings->setValue ("HideAS", ui->actionHideAS->isChecked() ); + m_settings->setValue ("HideAF", ui->actionHideAF->isChecked() ); + m_settings->setValue ("HideOC", ui->actionHideOC->isChecked() ); + m_settings->setValue ("HideAN", ui->actionHideAN->isChecked() ); + m_settings->setValue ("HighlightWhitelistEntries", ui->actionHighlight_Whitelist_entries->isChecked() ); + m_settings->endGroup(); +} + +void MainWindow::readSettings() +{ + ui->cbAutoSeq->setVisible(false); + ui->respondComboBox->setVisible(false); + + m_settings->beginGroup("MainWindow"); + std::array<QByteArray, 3> the_geometries; + the_geometries[0] = m_settings->value ("geometry", saveGeometry ()).toByteArray (); + the_geometries[1] = m_settings->value ("SWLModeGeometry", saveGeometry ()).toByteArray (); + the_geometries[2] = m_settings->value ("geometryNoControls", saveGeometry ()).toByteArray (); + auto SWL_mode = m_settings->value ("SWLView", false).toBool (); + auto show_menus = m_settings->value ("ShowMenus", true).toBool (); + ui->actionSWL_Mode->setChecked (SWL_mode); + ui->cbMenus->setChecked (show_menus); + ui->cbLowerCase->setChecked(m_settings->value("JTTY_LowerCase",false).toBool()); + ui->cbIncludeTime->setChecked(m_settings->value("JTTY_IncludeTime",false).toBool()); + auto current_view_mode = SWL_mode ? 1 : show_menus ? 0 : 2; + change_layout (current_view_mode); + geometries (current_view_mode, the_geometries); + restoreState (m_settings->value ("state", saveState ()).toByteArray ()); + setDXInfo(m_settings->value ("DXcall", QString {}).toString (), + m_settings->value ("DXgrid", QString {}).toString ()); + m_path = m_settings->value("MRUdir", m_config.save_directory ().absolutePath ()).toString (); + m_txFirst = m_settings->value("TxFirst",false).toBool(); + auto displayAstro = m_settings->value ("AstroDisplayed", false).toBool (); + auto displayMsgAvg = m_settings->value ("MsgAvgDisplayed", false).toBool (); + auto displayFoxLog = m_settings->value ("FoxLogDisplayed", false).toBool (); + auto displayContestLog = m_settings->value ("ContestLogDisplayed", false).toBool (); + bool displayActiveStations = m_settings->value ("ActiveStationsDisplayed", false).toBool (); + bool displayQSYMessageCreator = m_settings->value ("QSYMessageCreatorDisplayed", false).toBool (); + bool displayQSYMonitor = m_settings->value("QSYMonitorDisplayed", false).toBool (); + bool enableQSYpopups = m_settings->value("ShowQSYMessages", true).toBool (); + auto const respondPolicy = m_settings->value( + "RespondCQ", static_cast<int> (AutoRespondPolicy::None)).toInt(); + auto const respondIndex = ui->respondComboBox->findData (respondPolicy); + ui->respondComboBox->setCurrentIndex (respondIndex >= 0 ? respondIndex : 0); + ui->comboBoxHoundSort->setCurrentIndex(m_settings->value("HoundSort",3).toInt()); + ui->sbNlist->setValue(m_settings->value("FoxNlist",12).toInt()); + m_Nslots=m_settings->value("FoxNslots",3).toInt(); + m_Nslots0=m_Nslots; + if(!m_config.superFox()) ui->sbNslots->setValue(m_Nslots); + ui->sbSerialNumber->setValue (m_settings->value ("SerialNumber", 1).toInt ()); + ui->sbSerialNumber_2->setValue (m_settings->value ("SerialNumberJTTY", 1).toInt ()); + auto const jttyTemplate = [this] (int functionKey) { + QString const key = QStringLiteral("JTTY_msg%1").arg(functionKey); + QString const saved = m_settings->value( + key, Jtty::nativeMacroTemplate(functionKey)).toString(); + QString const migrated = Jtty::migratedNativeMacroTemplate(functionKey, saved); + if (m_settings->contains(key) && migrated != saved) { + m_settings->setValue(key, migrated); + } + return migrated; + }; + ui->msg1->setText(jttyTemplate(1)); + ui->msg2->setText(jttyTemplate(2)); + ui->msg3->setText(jttyTemplate(3)); + ui->msg4->setText(jttyTemplate(4)); + ui->msg5->setText(jttyTemplate(5)); + ui->msg6->setText(jttyTemplate(6)); + ui->msg7->setText(jttyTemplate(7)); + ui->msg8->setText(jttyTemplate(8)); + m_freeTextMsg0=m_settings->value("FoxTextMsg","").toString(); + m_freeTextMsg=m_freeTextMsg0; + ui->cbWorkDupes->setChecked(m_settings->value("WorkDupes",false).toBool()); + m_settings->endGroup(); + + m_settings->beginGroup("Common"); + m_mode=m_settings->value("Mode","FT8").toString(); + m_settings->endGroup(); + + // do this outside of settings group because it uses groups internally + ui->actionAstronomical_data->setChecked (displayAstro); + ui->actionEnable_QSY_Popups->setChecked (enableQSYpopups); + + // do this in the General group because we save the parameters from various places + if(m_mode=="JT9") { + blocked=true; + m_nSubMode=m_settings->value("SubMode",0).toInt(); + ui->sbSubmode->setValue(m_nSubMode); + ui->sbFtol->setValue (m_settings->value("Ftol_JT9", 50).toInt()); + ui->sbTR->setValue (m_settings->value ("TRPeriod", 15).toInt()); + QTimer::singleShot (50, [=] {blocked = false;}); + } + if (m_mode=="FT8") { + ui->sbFtol->setValue (m_settings->value("Ftol_SF", 50).toInt()); + } + if (m_mode=="Q65") { + m_nSubMode=m_settings->value("SubMode_Q65",0).toInt(); + ui->sbSubmode->setValue(m_nSubMode); + ui->sbFtol->setValue (m_settings->value("Ftol_Q65", 50).toInt()); + ui->sbTR->setValue (m_settings->value ("TRPeriod_Q65", 30).toInt()); + } + if (m_mode=="JT65") { + m_nSubMode=m_settings->value("SubMode_JT65",0).toInt(); + ui->sbSubmode->setValue(m_nSubMode); + ui->sbFtol->setValue (m_settings->value("Ftol_JT65", 50).toInt()); + } + if (m_mode=="JT4") { + m_nSubMode=m_settings->value("SubMode_JT4",0).toInt(); + ui->sbSubmode->setValue(m_nSubMode); + ui->sbFtol->setValue (m_settings->value("Ftol_JT4", 50).toInt()); + ui->sbTR->setValue (m_settings->value ("TRPeriod_FST4", 60).toInt()); + } + if (m_mode=="MSK144") { + ui->sbFtol->setValue (m_settings->value("Ftol_MSK144",50).toInt()); + m_msk144_tr2=m_settings->value ("TRPeriod_MSK144_2m", 30).toInt(); + m_msk144_tr6=m_settings->value ("TRPeriod_MSK144_6m", 15).toInt(); + m_msk144_tr=m_settings->value ("TRPeriod_MSK144", 30).toInt(); + QTimer::singleShot (3000, [=] { + if (m_currentBand=="2m") ui->sbTR->setValue (m_msk144_tr2); + else if (m_currentBand=="6m" or m_currentBand=="4m") ui->sbTR->setValue (m_msk144_tr6); + else ui->sbTR->setValue (m_msk144_tr); + }); + } + if (m_mode=="MSK144") m_bShMsgs=m_settings->value("ShMsgs_MSK144",false).toBool(); + if (m_mode=="Q65") m_bShMsgs=m_settings->value("ShMsgs_Q65",false).toBool(); + if (m_mode=="JT65") m_bShMsgs=m_settings->value("ShMsgs_JT65",false).toBool(); + if (m_mode=="JT4") m_bShMsgs=m_settings->value("ShMsgs_JT4",false).toBool(); + + m_settings->beginGroup("Common"); + ui->cb160m->setChecked(m_settings->value("bh_160m", false).toBool()); + ui->cb80m->setChecked(m_settings->value("bh_80m", false).toBool()); + ui->cb60m->setChecked(m_settings->value("bh_60m", false).toBool()); + ui->cb40m->setChecked(m_settings->value("bh_40m", false).toBool()); + ui->cb30m->setChecked(m_settings->value("bh_30m", false).toBool()); + ui->cb20m->setChecked(m_settings->value("bh_20m", false).toBool()); + ui->cb17m->setChecked(m_settings->value("bh_17m", false).toBool()); + ui->cb15m->setChecked(m_settings->value("bh_15m", false).toBool()); + ui->cb12m->setChecked(m_settings->value("bh_12m", false).toBool()); + ui->cb10m->setChecked(m_settings->value("bh_10m", false).toBool()); + ui->cb6m->setChecked(m_settings->value("bh_6m", false).toBool()); + ui->cb4m->setChecked(m_settings->value("bh_4m", false).toBool()); + ui->cb2m->setChecked(m_settings->value("bh_2m", false).toBool()); + ui->cb70cm->setChecked(m_settings->value("bh_70cm", false).toBool()); + ui->cb2mMSK->setChecked(m_settings->value("bh_2mMSK", false).toBool()); + ui->cb80mFT4->setChecked(m_settings->value("bh_80mFT4", false).toBool()); + ui->cb40mFT4->setChecked(m_settings->value("bh_40mFT4", false).toBool()); + ui->cb30mFT4->setChecked(m_settings->value("bh_30mFT4", false).toBool()); + ui->cb20mFT4->setChecked(m_settings->value("bh_20mFT4", false).toBool()); + ui->cb17mFT4->setChecked(m_settings->value("bh_17mFT4", false).toBool()); + ui->cb15mFT4->setChecked(m_settings->value("bh_15mFT4", false).toBool()); + ui->cb12mFT4->setChecked(m_settings->value("bh_12mFT4", false).toBool()); + ui->cb10mFT4->setChecked(m_settings->value("bh_10mFT4", false).toBool()); + ui->cbQRG1->setChecked(m_settings->value("bh_QRG1", false).toBool()); + ui->cbQRG2->setChecked(m_settings->value("bh_QRG2", false).toBool()); + ui->cbQRG3->setChecked(m_settings->value("bh_QRG3", false).toBool()); + ui->cbQRG4->setChecked(m_settings->value("bh_QRG4", false).toBool()); + ui->cbQRG5->setChecked(m_settings->value("bh_QRG5", false).toBool()); + ui->cbQRG6->setChecked(m_settings->value("bh_QRG6", false).toBool()); + ui->cbQRG7->setChecked(m_settings->value("bh_QRG7", false).toBool()); + ui->cbQRG8->setChecked(m_settings->value("bh_QRG8", false).toBool()); + ui->sbQRG1->setValue (m_settings->value ("QRG1", 3567).toInt ()); + ui->sbQRG2->setValue (m_settings->value ("QRG2", 7056).toInt ()); + ui->sbQRG3->setValue (m_settings->value ("QRG3", 10131).toInt ()); + ui->sbQRG4->setValue (m_settings->value ("QRG4", 14090).toInt ()); + ui->sbQRG5->setValue (m_settings->value ("QRG5", 18095).toInt ()); + ui->sbQRG6->setValue (m_settings->value ("QRG6", 21091).toInt ()); + ui->sbQRG7->setValue (m_settings->value ("QRG7", 24911).toInt ()); + ui->sbQRG8->setValue (m_settings->value ("QRG8", 28091).toInt ()); + ui->actionReduce_false_decodes->setChecked(m_settings->value("reduceFalseDecodes", false).toBool()); + ui->actionHide_AP_info->setChecked(m_settings->value("HideAPInfo", false).toBool()); + ui->actionFull_Duplex_Mode->setChecked(m_settings->value("FullDuplexMode", false).toBool()); + ui->actionDon_t_split_ALL_TXT->setChecked(m_settings->value("actionDontSplitALLTXT", true).toBool()); + ui->actionSplit_ALL_TXT_yearly->setChecked(m_settings->value("splitAllTxtYearly", false).toBool()); + ui->actionSplit_ALL_TXT_monthly->setChecked(m_settings->value("splitAllTxtMonthly", false).toBool()); + ui->actionDisable_writing_of_ALL_TXT->setChecked(m_settings->value("disableWritingOfAllTxt", false).toBool()); + ui->actionDisable_event_logging->setChecked(m_settings->value("DisableEventLogging", false).toBool()); + ui->actionUse_Dark_Style->setChecked(m_settings->value("DarkStyle", false).toBool()); + ui->actionBand_Buttons->setChecked(m_settings->value("BandButtons", true).toBool()); + ui->actionVHF_UHF_Buttons->setChecked(m_settings->value("VHFUHFButtons", false).toBool()); + m_tx1_enabled_preference = m_settings->value("tx1State", true).toBool(); + ui->tx1->setEnabled(m_tx1_enabled_preference); + ui->actionHighlightB4->setChecked(m_settings->value("HighlightB4", false).toBool()); + ui->actionHighlightToday->setChecked(m_settings->value("HighlightToday", false).toBool()); + ui->actionHighlightIgnored->setChecked(m_settings->value("HighlightIgnored", false).toBool()); + ui->actionHideB4->setChecked(m_settings->value("HideB4", false).toBool()); + ui->actionHideToday->setChecked(m_settings->value("HideToday", false).toBool()); + ui->actionHideIgnored->setChecked(m_settings->value("HideIgnored", false).toBool()); + ui->actionIgnoreB4->setChecked(m_settings->value("IgnoreB4", false).toBool()); + ui->actionIgnoreToday->setChecked(m_settings->value("IgnoreToday", false).toBool()); + ui->actionIgnoreIgnored->setChecked(m_settings->value("IgnoreIgnored", false).toBool()); + ui->actionHideTerritory1->setChecked(m_settings->value("HideTerritory1", false).toBool()); + ui->actionHideTerritory2->setChecked(m_settings->value("HideTerritory2", false).toBool()); + ui->actionHideTerritory3->setChecked(m_settings->value("HideTerritory3", false).toBool()); + ui->actionHideTerritory4->setChecked(m_settings->value("HideTerritory4", false).toBool()); + ui->actionHighlightTerritory1->setChecked(m_settings->value("HighlightTerritory1", false).toBool()); + ui->actionHighlightTerritory2->setChecked(m_settings->value("HighlightTerritory2", false).toBool()); + ui->actionHighlightTerritory3->setChecked(m_settings->value("HighlightTerritory3", false).toBool()); + ui->actionHighlightTerritory4->setChecked(m_settings->value("HighlightTerritory4", false).toBool()); + ui->actionHideEU->setChecked(m_settings->value("HideEU", false).toBool()); + ui->actionHideNA->setChecked(m_settings->value("HideNA", false).toBool()); + ui->actionHideSA->setChecked(m_settings->value("HideSA", false).toBool()); + ui->actionHideAS->setChecked(m_settings->value("HideAS", false).toBool()); + ui->actionHideAF->setChecked(m_settings->value("HideAF", false).toBool()); + ui->actionHideOC->setChecked(m_settings->value("HideOC", false).toBool()); + ui->actionHideAN->setChecked(m_settings->value("HideAN", false).toBool()); + ui->actionHighlight_Whitelist_entries->setChecked(m_settings->value("HighlightWhitelistEntries", false).toBool()); +// m_mode=m_settings->value("Mode","FT8").toString(); + ui->actionNone->setChecked(m_settings->value("SaveNone",true).toBool()); + ui->actionSave_decoded->setChecked(m_settings->value("SaveDecoded",false).toBool()); + ui->actionSave_all->setChecked(m_settings->value("SaveAll",false).toBool()); + ui->actionRemove_after_30days->setChecked(m_settings->value("RemoveAudioFiles",false).toBool()); + ui->RxFreqSpinBox->setValue(0); // ensure a change is signaled + ui->RxFreqSpinBox->setValue(m_settings->value("RxFreq",1500).toInt()); + ui->sbFST4W_RxFreq->setValue(0); + ui->sbFST4W_RxFreq->setValue(m_settings->value("FST4W_RxFreq",1500).toInt()); + ui->sbF_Low->setValue(m_settings->value("FST4_FLow",600).toInt()); + ui->sbF_High->setValue(m_settings->value("FST4_FHigh",1400).toInt()); + ui->sbFST4W_FTol->setValue(m_settings->value("FST4W_FTol",100).toInt()); + ui->sbFtol_2->setValue(m_settings->value("JTTY_FTol",20).toInt()); + ui->sbToneSpacing->setValue(m_settings->value("EchoToneSpacing",10).toInt()); + ui->rbFixedTone->setChecked(m_settings->value("EchoFixedTone",true).toBool()); + ui->rbEchoMessage->setChecked(m_settings->value("EchoMessageRB",false).toBool()); + ui->rbEchoCW->setChecked(m_settings->value("EchoCW",false).toBool()); + ui->leEchoMessage->setText (CallsignValidator::normalizeStoredInput ( + m_settings->value ("EchoMessage", QString {}).toString (), + ui->leEchoMessage->maxLength (), false)); + m_minSync=m_settings->value("MinSync",0).toInt(); + ui->syncSpinBox->setValue(m_minSync); + ui->cbAutoSeq->setChecked (m_settings->value ("AutoSeq", false).toBool()); + ui->cbRxAll->setChecked (m_settings->value ("RxAll", false).toBool()); +// m_bShMsgs=m_settings->value("ShMsgs",false).toBool(); + m_bSWL=m_settings->value("SWL",false).toBool(); + m_bFast9=m_settings->value("Fast9",false).toBool(); + m_bFastMode=m_settings->value("FastMode",false).toBool(); + ui->sbMaxDrift->setValue (m_settings->value ("MaxDrift",0).toInt()); + ui->sbTR_FST4W->setValue (m_settings->value ("TRPeriod_FST4W", 15).toInt()); + m_operatingFrequency.loadRemembered (m_settings->value ("DialFreq", + QVariant::fromValue<Frequency> (default_frequency)).value<Frequency> ()); + m_skedFreq=m_settings->value("SkedFreq",1296.065).toDouble(); + QTimer::singleShot (1000, [=] {if (m_astroWidget) m_astroWidget->setSkedFreq(m_skedFreq);}); + if(m_mode=="MSK144") m_msk144basefreq = m_operatingFrequency.remembered (); // MSK144 QSY + ui->WSPRfreqSpinBox->setValue(0); // ensure a change is signaled + ui->WSPRfreqSpinBox->setValue(m_settings->value("WSPRfreq",1500).toInt()); + ui->TxFreqSpinBox->setValue(0); // ensure a change is signaled + if(m_specOp!=SpecOp::FOX) ui->TxFreqSpinBox->setValue(m_settings->value("TxFreq",1500).toInt()); + m_TxFreqFox=m_settings->value("TxFreqFox",300).toInt(); + if(m_specOp==SpecOp::FOX && !m_config.superFox()) ui->TxFreqSpinBox->setValue(m_TxFreqFox); + m_ndepth=m_settings->value("NDepth",3).toInt(); + + //ft8md + ui->actionUse_multithreaded_FT8_decoder->setChecked(m_settings->value("MultithreadedFT8decoder", false).toBool()); + m_multithreadFT8 = ui->actionUse_multithreaded_FT8_decoder->isChecked(); + dec_data.params.lmultift8 = m_multithreadFT8; + + m_nFT8Cycles=m_settings->value("NFT8Cycles",3).toInt(); if(!(m_nFT8Cycles>=1 && m_nFT8Cycles<=3)) m_nFT8Cycles=3; + if(m_nFT8Cycles==1) ui->actionDecFT8cycles1->setChecked(true); + else if(m_nFT8Cycles==2) ui->actionDecFT8cycles2->setChecked(true); + else if(m_nFT8Cycles==3) ui->actionDecFT8cycles3->setChecked(true); + + m_nFT8RXfSens=m_settings->value("NFT8QSORXfreqSensitivity",3).toInt(); if(!(m_nFT8RXfSens>=1 && m_nFT8RXfSens<=3)) m_nFT8RXfSens=3; + if(m_nFT8RXfSens==1) ui->actionRXfLow->setChecked(true); + else if(m_nFT8RXfSens==2) ui->actionRXfMedium->setChecked(true); + else if(m_nFT8RXfSens==3) ui->actionRXfHigh->setChecked(true); + + m_ft8threads=m_settings->value("FT8threads",0).toInt(); + if(!(m_ft8threads>=0 && m_ft8threads<25)) m_ft8threads=0; + if(m_ft8threads==0) ui->actionMTAuto->setChecked(true); + else if(m_ft8threads==1) ui->actionMT1->setChecked(true); + else if(m_ft8threads==2) ui->actionMT2->setChecked(true); + else if(m_ft8threads==3) ui->actionMT3->setChecked(true); + else if(m_ft8threads==4) ui->actionMT4->setChecked(true); + else if(m_ft8threads==5) ui->actionMT5->setChecked(true); + else if(m_ft8threads==6) ui->actionMT6->setChecked(true); + else if(m_ft8threads==7) ui->actionMT7->setChecked(true); + else if(m_ft8threads==8) ui->actionMT8->setChecked(true); + else if(m_ft8threads==9) ui->actionMT9->setChecked(true); + else if(m_ft8threads==10) ui->actionMT10->setChecked(true); + else if(m_ft8threads==11) ui->actionMT11->setChecked(true); + else if(m_ft8threads==12) ui->actionMT12->setChecked(true); +// qDebug() << "m_ft8threads is " << m_ft8threads; + dec_data.params.nmt = m_ft8threads; + + ui->actionHide_FT8_dupe_messages->setChecked(m_settings->value("HideFT8Dupes",true).toBool()); + + m_ft8Sensitivity=m_settings->value("FT8Sensitivity",3).toInt(); + if(!(m_ft8Sensitivity>0 && m_ft8Sensitivity<=3)) m_ft8Sensitivity=3; + if(m_ft8Sensitivity==1) ui->actionFT8SensMin->setChecked(true); + else if(m_ft8Sensitivity==2) ui->actionlowFT8thresholds->setChecked(true); + else if(m_ft8Sensitivity==3) ui->actionFT8subpass->setChecked(true); + + m_ft8DecoderStart=m_settings->value("FT8DecoderStart",3).toInt(); + if(!(m_ft8DecoderStart>=0 && m_ft8DecoderStart<=4)) m_ft8DecoderStart=3; + if(m_ft8DecoderStart==0) ui->actionStartTwoStage->setChecked(true); + else if(m_ft8DecoderStart==1) ui->actionStartThreeStage->setChecked(true); + else if(m_ft8DecoderStart==2) ui->actionStartEarly->setChecked(true); + else if(m_ft8DecoderStart==3) ui->actionStartNormal->setChecked(true); + else if(m_ft8DecoderStart==4) ui->actionStartLate->setChecked(true); + + m_FT8WideDxCallSearch=m_settings->value("FT8WideDXCallSearch",true).toBool(); + ui->actionFT8WidebandDXCallSearch->setChecked(m_FT8WideDxCallSearch); + //ft8md + + ui->sbTxPercent->setValue (m_settings->value ("PctTx", 20).toInt ()); + on_sbTxPercent_valueChanged (ui->sbTxPercent->value ()); + auto const roundRobinPolicy = BeaconTx::parseRoundRobinPolicy ( + m_settings->value("RoundRobin", "random").toString ().toStdString ()); + RoundRobinSelection::setPolicy (*ui->RoundRobin, roundRobinPolicy); + m_dBm=m_settings->value("dBm",37).toInt(); + m_send_RR73=m_settings->value("RR73",false).toBool(); + m_score=m_settings->value("Score",0).toInt(); + if (m_send_RR73) genStdMsgs (m_rpt); + ui->WSPR_prefer_type_1_check_box->setChecked (m_settings->value ("WSPRPreferType1", true).toBool ()); + m_uploadWSPRSpots=m_settings->value("UploadSpots",false).toBool(); + ui->cbNoOwnCall->setChecked(m_settings->value("NoOwnCall",false).toBool()); + ui->band_hopping_group_box->setChecked (m_settings->value ("BandHopping", false).toBool()); + // setup initial value of tx attenuator + m_block_pwr_tooltip = true; + ui->outAttenuation->setValue (m_settings->value ("OutAttenuation", 0).toInt ()); + m_block_pwr_tooltip = false; + ui->sbCQTxFreq->setValue (m_settings->value ("CQTxFreq", 260).toInt()); + m_noSuffix=m_settings->value("NoSuffix",false).toBool(); + int n=m_settings->value("GUItab",standard_messages_tab_index).toInt(); + if (SpecOp::FOX==m_specOp) { + ui->tabWidget->setCurrentIndex(n); + } else { + // The Fox queue tab must be shown once so Qt initializes its height. + ui->pbFreeText->setVisible(false); + ui->cbSendMsg->setVisible(false); + ui->tabWidget->setCurrentIndex(fox_queue_tab_index); + ui->tabWidget->setCurrentIndex(n); + } + outBufSize=m_settings->value("OutBufSize",4096).toInt(); + ui->cbHoldTxFreq->setChecked (m_settings->value ("HoldTxFreq", false).toBool ()); + HoldTxFreqStatus = m_settings->value ("HoldTxFreq", false).toBool (); + ui->cbCQonly->setChecked (m_settings->value ("CQonly", false).toBool ()); + ui->cbBypass->setChecked (m_settings->value ("BypassFilters", false).toBool ()); + m_pwrBandTxMemory=m_settings->value("pwrBandTxMemory").toHash(); + m_pwrBandTuneMemory=m_settings->value("pwrBandTuneMemory").toHash(); + ui->actionEnable_AP_FT8->setChecked (m_settings->value ("FT8AP", false).toBool()); + ui->actionEnable_AP_JT65->setChecked (m_settings->value ("JT65AP", false).toBool()); + ui->actionAuto_Clear_Avg->setChecked (m_settings->value ("AutoClearAvg", false).toBool()); + ui->actionDisable_clicks_on_waterfall->setChecked (m_settings->value ("DisableClicksOnWaterfall", false).toBool()); + ui->decodes_splitter->restoreState(m_settings->value("SplitterState").toByteArray()); + ui->sbNB->setValue(m_settings->value("Blanker",0).toInt()); + ui->sbEchoAvg->setValue(m_settings->value("EchoAvg",10).toInt()); + { + auto const& coeffs = m_settings->value ("PhaseEqualizationCoefficients" + , QList<QVariant> {0., 0., 0., 0., 0.}).toList (); + m_phaseEqCoefficients.clear (); + for (auto const& coeff : coeffs) + { + m_phaseEqCoefficients.append (coeff.value<double> ()); + } + } + m_settings->endGroup(); + + // use these initialisation settings to tune the audio o/p buffer + // size and audio thread priority + m_settings->beginGroup ("Tune"); + m_audioThreadPriority = static_cast<QThread::Priority> (m_settings->value ("Audio/ThreadPriority", QThread::TimeCriticalPriority).toInt () % 8); + m_settings->endGroup (); + + m_specOp=m_config.special_op_id(); + checkMSK144ContestType(); + if (displayMsgAvg) on_actionMessage_averaging_triggered(); + if (displayFoxLog) on_fox_log_action_triggered (); + if (displayContestLog) on_contest_log_action_triggered (); + if (displayActiveStations) on_actionActiveStations_triggered(); + if (displayQSYMessageCreator) on_actionQSYMessage_Creator_triggered(); + if (displayQSYMonitor) on_actionQSY_Monitor_triggered(); + +} diff --git a/widgets/mainwindow_show_messages.cpp b/widgets/mainwindow_show_messages.cpp new file mode 100644 index 00000000..6e7236d7 --- /dev/null +++ b/widgets/mainwindow_show_messages.cpp @@ -0,0 +1,67 @@ +#include "mainwindow.h" +#include "MessageBox.hpp" +#include <QProcess> +#include <QStringList> +#include <QSplashScreen> +#include <QStatusBar> +#include <QTimer> + +void MainWindow::showSoundInError(const QString& errorMsg) +{ + if (m_splash && m_splash->isVisible ()) m_splash->hide (); + MessageBox::critical_message (this, tr ("Error in Sound Input"), errorMsg); +} + +void MainWindow::showSoundOutError(const QString& errorMsg) +{ + noteTxStopReason (TxEvidence::TxStopReason::Error); + if (m_splash && m_splash->isVisible ()) m_splash->hide (); + MessageBox::critical_message (this, tr ("Error in Sound Output"), errorMsg); +} + +void MainWindow::showStatusMessage(const QString& statusMsg) +{ + statusBar()->showMessage(statusMsg, 5000); +} + +bool MainWindow::subProcessFailed (QProcess * process, int exit_code, QProcess::ExitStatus status) +{ + if (m_valid && (exit_code || QProcess::NormalExit != status)) + { + QStringList arguments; + for (auto argument: process->arguments ()) + { + if (argument.contains (' ')) argument = '"' + argument + '"'; + arguments << argument; + } + if (m_splash && m_splash->isVisible ()) m_splash->hide (); + MessageBox::critical_message (this, tr ("Subprocess Error") + , tr ("Subprocess failed with exit code %1") + .arg (exit_code) + , tr ("Running: %1\n%2") + .arg (process->program () + ' ' + arguments.join (' ')) + .arg (QString {process->readAllStandardError()})); + return true; + } + return false; +} + +void MainWindow::subProcessError (QProcess * process, QProcess::ProcessError) +{ + if (m_valid) + { + QStringList arguments; + for (auto argument: process->arguments ()) + { + if (argument.contains (' ')) argument = '"' + argument + '"'; + arguments << argument; + } + if (m_splash && m_splash->isVisible ()) m_splash->hide (); + MessageBox::critical_message (this, tr ("Subprocess error") + , tr ("Running: %1\n%2") + .arg (process->program () + ' ' + arguments.join (' ')) + .arg (process->errorString ())); + m_valid = false; // ensures exit if still constructing + QTimer::singleShot (0, this, SLOT (close ())); + } +} diff --git a/widgets/mainwindow_slots.cpp b/widgets/mainwindow_slots.cpp new file mode 100644 index 00000000..2ff97b42 --- /dev/null +++ b/widgets/mainwindow_slots.cpp @@ -0,0 +1,1093 @@ +#include "mainwindow.h" +#include "ui_mainwindow.h" +#include <QDesktopServices> +#include <QUrl> +#include <QDateTime> +#include <QTimer> +#include <QFile> +#include <QTextStream> +#include <QDebug> +#include <QInputDialog> +#include <QColor> +#include <QVector> +#include <QSettings> +#include <QtMath> +#include "MessageBox.hpp" +#include "DecodedMessageReaction.hpp" +#include "WaitFeaturePolicy.hpp" +#include "commons.h" +#include "echograph.h" +#include "widegraph.h" +#include "messageaveraging.h" +#include "logqso.h" + +using SpecOp = Configuration::SpecialOperatingActivity; + +extern dec_data_t& dec_data; +extern int volatile itone[MAX_NUM_SYMBOLS]; +extern int volatile itone0[MAX_NUM_SYMBOLS]; +extern int volatile icw[NUM_CW_SYMBOLS]; +extern int outBufSize; +extern int rc; +extern qint32 g_iptt; +extern QVector<QColor> g_ColorTbl; +extern bool blocked; +extern bool m_displayBand; +extern bool wait_and_call; +extern bool no_wait_and_call; +extern bool no_a7_decodes; +extern bool keep_frequency; +extern bool keep_msk144_frequency; +extern bool msk144qsy; +extern bool keep_last_tx_label; +extern int m_Nslots0; +extern int m_TxFreqFox; +extern bool not_erase; +extern bool first_Fox_alert; +extern bool second_Fox_alert; +extern bool no_Fox_alert; +extern bool pounce; +extern bool filtered; +extern bool ignored; +extern bool keepTx5; +extern bool no_logging; +extern bool BlankLineInserted; +extern bool m_txing; +extern bool HoldTxFreqStatus; +extern bool m_band_changed; +extern bool m_muted; +extern bool no_decodes_to_UDP; +extern bool rigFailed; +extern bool programStart; +extern int m_msk144_tr; +extern int m_msk144_tr2; +extern int m_msk144_tr6; +extern QString txLog; +extern QString ignoreList; +extern QString ALLCALL7; +extern QString m_hisCall0; +extern QString earlyDecodes; + + +extern "C" { + void genjtty_(char const * msg, int itone[], int* nsym, fortran_charlen_t); + void gen_jttywave_(int itone[], int* nsym, int* nsps, float* bt, float* fsample, float* f0, + float xjunk[], float wave[], int* icmplx, int* nwave); +} + +void MainWindow::on_monitorButton_clicked (bool checked) +{ + if (m_wav_load_coordinator.isLoading ()) { + ui->monitorButton->setChecked (false); + return; + } + + if (!m_transmitting) { + if (checked) + { + auto const transition = m_operatingFrequency.enableMonitor ( + operatingFrequencyContext (), [this] (Frequency corrected) { + return dispatchNominalFrequency (corrected, FrequencyRequestOrigin::User, true); + }); + applyOperatingFrequencyTransition (transition); + applyMonitorEffects (true, transition.restorationAccepted); + } + else + { + applyMonitorEffects (false, false); + } + } else { + ui->monitorButton->setChecked (false); // disallow + } + if(m_mode=="Echo") m_echoRunning=false; + check_button_color(); +} + +void MainWindow::applyMonitorEffects (bool checked, bool restored) +{ + auto const prior = m_monitoring; + monitor (checked); + if (restored) setXIT (ui->TxFreqSpinBox->value ()); + if (checked && !prior) + { + if (m_mode == "FST4W") + on_sbFST4W_RxFreq_valueChanged (ui->sbFST4W_RxFreq->value ()); + else + on_RxFreqSpinBox_valueChanged (ui->RxFreqSpinBox->value ()); + } + m_config.sync_transceiver (true, checked); + if (m_mode == "Echo") m_echoRunning = false; + check_button_color (); +} + +void MainWindow::on_autoButton_clicked (bool checked) +{ + if (ui->DX_Call_Button->isChecked() && m_specOp==SpecOp::HOUND && m_config.superFox() && !m_bDoubleClicked) return; // for Wait & Call + m_config.transceiver_tune (false); // reset rig tuning + if (checked && ui->tuneButton->isChecked() && !(m_mode=="WSPR" || m_mode=="FST4W")) return; // not allowed while tuning + stopWRTimer.stop(); // stop any Wait & Reply timeout + if (!checked && ui->DX_Call_Button->isChecked()) { + stopWCTimer.stop(); // stop any Wait & Call timeout + ui->DX_Call_Button->click (); // disable Wait & Call + no_wait_and_call = false; // reset Wait & Call + } + m_specOp=m_config.special_op_id(); + ui->pbBandHopping->setChecked(false); // disable band hopping when Tx is enabled + if (checked) { + m_auto = checked; + QTimer::singleShot (3000, [=] {pounce = false;}); // ensure to select only CQ messages + } else { + pounce = false; + m_auto = false; + m_bCallingCQ = false; + ui->autoButton->setChecked(false); // ensure autoButton is unchecked + filtered = false; + ignored = false; + m_muted = false; + m_autoRespondScores.reset(); + } + if (m_mode=="WSPR" || m_mode=="FST4W") + { + m_beaconTxController.setAutoEnabled (checked); + } + bool const enableTxChanged = m_autoRespondPeriodState.setEnableTx(checked); + if (checked && enableTxChanged && m_autoRespondPeriodState.armCurrentReceivePeriod( + pendingCqAutoRespondIntent(), autoRespondPolicy())) { + m_autoRespondScores.reset(); + } + m_maxPoints=-1; + if (checked && ui->respondComboBox->isVisible() && autoRespondPolicy () != AutoRespondPolicy::None + && CALLING == m_QSOProgress) { + m_bAutoReply = false; // ready for next + } + statusUpdate (); + m_bEchoTxOK=false; + if(m_mode=="Echo" and m_auto) { + m_nclearave=1; + echocom_.nsum=0; + } + m_tAutoOn=QDateTime::currentMSecsSinceEpoch()/1000; + if(m_mode=="Echo") m_echoRunning=false; + check_button_color(); +} + +void MainWindow::on_stopButton_clicked() //stopButton +{ + ui->pbBandHopping->setChecked(false); // disable band hopping + monitor (false); + if(m_mode=="JTTY" and m_saveAll and !m_diskData) { + jtty_save_wav(); + } + m_loopall=false; + finishReferenceSpectrumMeasurement(true); + if (ui->DX_Call_Button->isChecked()) ui->DX_Call_Button->click (); + stopWRTimer.stop(); // Stop any Wait & Reply timeout + stopWCTimer.stop(); // Stop any Wait & Call timeout + no_wait_and_call = false; + m_specOp=m_config.special_op_id(); + if (ui->respondComboBox->isVisible() and autoRespondPolicy () != AutoRespondPolicy::None and !m_diskData) { + m_autoRespondScores.reset(); + if (!(m_mode=="Q65" or m_mode=="JT65")) { + clearDX(); // clear dxCallEntry + ui->dxGridEntry->clear (); // clear dxGridEntry + if (!keepTx5) ui->tx5->setCurrentText(""); // clear tx5 + } + } + pounce = false; + ui->autoButton->setChecked(false); // ensure auoButton is unchecked + filtered = false; + ignored = false; + m_muted = false; + check_button_color(); +} + +void MainWindow::on_pbBandHopping_clicked() +{ + if (m_auto) ui->pbBandHopping->setChecked(false); // don't allow band hopping when in QSO +} + +void MainWindow::on_DecodeButton_clicked (bool /* checked */) //Decode request +{ + if (m_wav_load_coordinator.isLoading ()) { + ui->DecodeButton->setChecked (false); + return; + } + + if(m_mode=="MSK144") { + ui->DecodeButton->setChecked(false); + } else if(m_mode=="JTTY") { + jtty_again(); + } else { + if(m_mode!="WSPR" && !decoderBusy ()) { + if (usesJt9Process () + && (Jt9ProcessPhase::Ready != m_jt9ProcessPhase + || QProcess::Running != proc_jt9.state ())) + { + ui->DecodeButton->setChecked (false); + showStatusMessage (tr ("Decoder is starting; decode request skipped.")); + return; + } + m_manualDecode=true; + dec_data.params.newdat=0; + dec_data.params.nagain=1; + decode(); + } + } +} + +void MainWindow::on_ClrAvgButton_clicked() +{ + m_nclearave=1; + if(m_mode=="Echo") { + echocom_.nsum=0; + m_echoGraph->clearAvg(); + m_wideGraph->restartTotalPower(); + } else { + if(m_msgAvgWidget != NULL) { + if(m_msgAvgWidget->isVisible()) m_msgAvgWidget->displayAvg(""); + } + if(m_mode=="Q65") ndecodes_label.setText("0 0"); + } +} + +void MainWindow::on_EraseButton_clicked () +{ + qint64 ms=QDateTime::currentMSecsSinceEpoch(); + if (m_config.alternate_erase_button()) { + ui->decodedTextBrowser->erase (); + if((ms-m_msErase)<500) { + ui->decodedTextBrowser2->erase (); + } + } else { + ui->decodedTextBrowser2->erase (); + if(m_mode=="WSPR" or m_mode=="Echo" or m_mode=="FST4W") { + ui->decodedTextBrowser->erase (); + } else { + if((ms-m_msErase)<500) { + ui->decodedTextBrowser->erase (); + } + } + } + m_msErase=ms; +} + +void MainWindow::on_txb1_clicked() +{ + m_autoRespondPeriodState.disarm(); + if (ui->tx1->isEnabled ()) { + m_ntx=1; + m_QSOProgress = REPLYING; + ui->txrb1->setChecked(true); + if(m_transmitting) m_restart=true; + } + else { + on_txb2_clicked (); + } +} + +void MainWindow::on_txb2_clicked() +{ + m_autoRespondPeriodState.disarm(); + m_ntx=2; + m_QSOProgress = REPORT; + ui->txrb2->setChecked(true); + if(m_transmitting) m_restart=true; +} + +void MainWindow::on_txb3_clicked() +{ + m_autoRespondPeriodState.disarm(); + m_ntx=3; + m_QSOProgress = ROGER_REPORT; + ui->txrb3->setChecked(true); + if(m_transmitting) m_restart=true; +} + +void MainWindow::on_txb4_clicked() +{ + m_autoRespondPeriodState.disarm(); + m_ntx=4; + m_QSOProgress = ROGERS; + ui->txrb4->setChecked(true); + if(m_transmitting) m_restart=true; +} + +void MainWindow::on_txb5_clicked() +{ + m_autoRespondPeriodState.disarm(); + m_ntx=5; + m_QSOProgress = SIGNOFF; + ui->txrb5->setChecked(true); + if(m_transmitting) m_restart=true; +} + +void MainWindow::on_txb6_clicked() +{ + m_autoRespondPeriodState.disarm(); + m_ntx=6; + m_QSOProgress = CALLING; + set_dateTimeQSO(-1); + ui->txrb6->setChecked(true); + if(m_transmitting) m_restart=true; + if(m_mode=="MSK144" && !programStart && !m_band_changed && !keep_msk144_frequency + && hasMsk144BaseFrequency ()) { + if (requestNominalFrequencyChange (m_msk144basefreq, FrequencyRequestOrigin::User)) + { + msk144qsy = false; + } + } +} + +void MainWindow::on_lookupButton_clicked() //Lookup button +{ + qint64 ms=QDateTime::currentMSecsSinceEpoch(); + lookup(); + if((ms-m_msErase)<500) { + QString hisCall=ui->dxCallEntry->text(); + if (hisCall !="") QDesktopServices::openUrl (QUrl {"https://www.qrz.com/db/" + hisCall}); + } + m_msErase=ms; +} + +void MainWindow::on_addButton_clicked() //Add button +{ + if(!ui->dxGridEntry->text ().size ()) { + MessageBox::warning_message (this, tr ("Add to CALL3.TXT") + , tr ("Please enter a valid grid locator")); + return; + } + m_call3Modified=false; + QString hisCall=ui->dxCallEntry->text(); + QString hisgrid=ui->dxGridEntry->text(); + QString newEntry=hisCall + "," + hisgrid; + + // int ret = MessageBox::query_message(this, tr ("Add to CALL3.TXT"), + // tr ("Is %1 known to be active on EME?").arg (newEntry)); + // if(ret==MessageBox::Yes) { + // newEntry += ",EME,,"; + // } else { + newEntry += ",,,"; + // } + + QFile f1 {m_config.writeable_data_dir ().absoluteFilePath ("CALL3.TXT")}; + if(!f1.open(QIODevice::ReadWrite | QIODevice::Text)) { + MessageBox::warning_message (this, tr ("Add to CALL3.TXT") + , tr ("Cannot open \"%1\" for read/write: %2") + .arg (f1.fileName ()).arg (f1.errorString ())); + return; + } + if(f1.size()==0) { + QTextStream out(&f1); + out << "ZZZZZZ" +#if QT_VERSION >= QT_VERSION_CHECK (5, 15, 0) + << Qt::endl +#else + << endl +#endif + ; + f1.seek (0); + } + QFile f2 {m_config.writeable_data_dir ().absoluteFilePath ("CALL3.TMP")}; + if(!f2.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text)) { + MessageBox::warning_message (this, tr ("Add to CALL3.TXT") + , tr ("Cannot open \"%1\" for writing: %2") + .arg (f2.fileName ()).arg (f2.errorString ())); + return; + } + { + QTextStream in(&f1); //Read from CALL3.TXT + QTextStream out(&f2); //Copy into CALL3.TMP + QString hc=hisCall; + QString hc1=""; + QString hc2="000000"; + QString s; + do { + s=in.readLine(); + hc1=hc2; + if(s.mid(0,2)=="//") { + out << s + QChar::LineFeed; //Copy all comment lines + } else { + int i1=s.indexOf(","); + hc2=s.mid(0,i1); + if(hc>hc1 && hc<hc2) { + out << newEntry + QChar::LineFeed; + out << s + QChar::LineFeed; + m_call3Modified=true; + } else if(hc==hc2) { + QString t {tr ("%1\nis already in CALL3.TXT" + ", do you wish to replace it?").arg (s)}; + int ret = MessageBox::query_message (this, tr ("Add to CALL3.TXT"), t); + if(ret==MessageBox::Yes) { + out << newEntry + QChar::LineFeed; + m_call3Modified=true; + } + } else { + if(s!="") out << s + QChar::LineFeed; + } + } + } while(!s.isNull()); + if(hc>hc1 && !m_call3Modified) out << newEntry + QChar::LineFeed; + } + + if(m_call3Modified) { + auto const& old_path = m_config.writeable_data_dir ().absoluteFilePath ("CALL3.OLD"); + QFile f0 {old_path}; + if (f0.exists ()) f0.remove (); + f1.copy (old_path); // copying as we want to + // preserve symlinks + f1.open (QFile::WriteOnly | QFile::Text); // truncates + f2.seek (0); + QByteArray tmp = f2.readAll(); + if (tmp != (const char*)NULL) f1.write (tmp); // copy contents + else qDebug() << "tmp==NULL at f1.write"; + f2.remove (); + } +} + +void MainWindow::on_ignoreButton_clicked() //Ignore button +{ + addCallsignToignoreList(); +} + +void MainWindow::on_DX_Call_Button_clicked (bool checked) +{ + WaitFeatureContext const waitContext { + m_mode, + m_specOp, + m_config.Wait_features_enabled(), + ui->cbAutoSeq->isChecked(), + !m_hisCall.isEmpty(), + m_config.NCCC_Sprint() + }; + if (checked && wait_and_call_arming_eligible (waitContext)) { + wait_and_call = true; // toggle Wait & Call on when allowed + } else { + wait_and_call = false; // toggle Wait & Call off in any other case + ui->DX_Call_Button->setChecked (false); + if (m_specOp==SpecOp::HOUND && m_config.superFox() && !m_auto) clearDX(); + } + check_button_color(); +} + +void MainWindow::on_genStdMsgsPushButton_clicked() //genStdMsgs button +{ + ui->pbBandHopping->setChecked(false); // disable band hopping + genStdMsgs(m_rpt); + if (!m_bDoubleClicked && m_hisCall!="") { + if (ui->tx1->isEnabled ()) { + QTimer::singleShot (0, ui->txrb1, SLOT (click ())); // Go to Tx1 + } else { + QTimer::singleShot (0, ui->txrb2, SLOT (click ())); // Go to Tx2 if Tx1 is disabled + } + m_bMyCallStd=stdCall(m_config.my_callsign()); //ft8md + m_bHisCallStd=stdCall(m_hisCall); //ft8md + + } +} + +void MainWindow::on_logQSOButton_clicked() //Log QSO button +{ + auto stopAutoTx = [this] { + if (SpecOp::NA_VHF==m_specOp && m_mode=="FT4" && m_config.NCCC_Sprint()) { + QTimer::singleShot (int(850.0*m_TRperiod), [this] {cease_auto_Tx_after_QSO ();}); + } else { + cease_auto_Tx_after_QSO (); + } + }; + DecodedMessageReaction::applyAutoTxStopAfterLogging( + m_mode, m_config.repeat_Tx(), send_rr73_for_tx4 (), stopAutoTx); + + if (!m_hisCall.size ()) { + MessageBox::warning_message (this, tr ("Warning: DX Call field is empty.")); + if ((SpecOp::NA_VHF == m_specOp or SpecOp::WW_DIGI == m_specOp) && m_config.autoLog()) return; // prevent program crash + } + // m_dateTimeQSOOn should really already be set but we'll ensure it gets set to something just in case + if (!m_dateTimeQSOOn.isValid ()) { + auto now = QDateTime::currentDateTimeUtc(); + m_dateTimeQSOOn = now.addSecs (-(m_ntx - 2) * int(m_TRperiod) - + int(fmod(double(now.time().second()),m_TRperiod))); + } + auto dateTimeQSOOff = QDateTime::currentDateTimeUtc(); + if (dateTimeQSOOff < m_dateTimeQSOOn) dateTimeQSOOff = m_dateTimeQSOOn; + QString grid=m_hisGrid; + if(grid=="....") grid=""; + + // Optionally replace empty grids by "ZZ00" + if(m_config.ZZ00() && m_hisGrid=="" && m_specOp!=SpecOp::NONE && m_specOp!=SpecOp::FOX && m_specOp!=SpecOp::HOUND) m_hisGrid = "ZZ00"; + + switch( m_specOp ) + { + case SpecOp::NA_VHF: + m_xSent=m_config.my_grid().left(4); + m_xRcvd=m_hisGrid.left(4); + break; + case SpecOp::EU_VHF: + m_rptSent=m_xSent.split(" ").at(0).left(2); + m_rptRcvd=m_xRcvd.split(" ").at(0).left(2); + if(m_xRcvd.split(" ").size()>=2) m_hisGrid=m_xRcvd.split(" ").at(1); + grid=m_hisGrid; + ui->dxGridEntry->setText(grid); + break; + case SpecOp::FIELD_DAY: + m_rptSent=m_xSent.split(" ").at(0); + m_rptRcvd=m_xRcvd.split(" ").at(0); + break; + case SpecOp::RTTY: + m_rptSent=m_xSent.split(" ").at(0); + m_rptRcvd=m_xRcvd.split(" ").at(0); + break; + case SpecOp::WW_DIGI: + m_xSent=m_config.my_grid().left(4); + m_xRcvd=m_hisGrid.left(4); + break; + case SpecOp::ARRL_DIGI: + m_xSent=m_config.my_grid().left(4); + m_xRcvd=m_hisGrid.left(4); + break; + case SpecOp::Q65_PILEUP: + m_xSent=m_config.my_grid().left(4); + m_xRcvd=m_hisGrid; + break; + default: break; + } + + m_logDlg->initLogQSO (m_hisCall, grid, m_mode, m_rptSent, m_rptRcvd, + m_dateTimeQSOOn, dateTimeQSOOff, m_operatingFrequency.rx () + + ui->TxFreqSpinBox->value(), m_noSuffix, m_xSent, m_xRcvd); + m_inQSOwith=""; + if (ui->respondComboBox->isVisible() && autoRespondPolicy () != AutoRespondPolicy::None) { + m_autoRespondScores.reset(); + } + QTimer::singleShot (2000, [=] { + pounce = false; + filtered = false; + read_txLog(); + check_button_color(); + }); + QTimer::singleShot (7000, [=] { + read_txLog(); + }); + stopWRTimer.stop(); // Stop any Wait & Reply timeout + stopWCTimer.stop(); // Stop any Wait & Call timeout +} + +void MainWindow::on_tuneButton_clicked (bool checked) +{ + if (checked) m_autoRespondPeriodState.disarm(); + rigTuneTimer.stop (); + ui->pbBandHopping->setChecked(false); // disable band hopping + // prevent tuning on top of a SuperFox message + if (SpecOp::HOUND==m_specOp && m_config.superFox() && !m_tune) { + QDateTime now = QDateTime::currentDateTimeUtc(); + int s = now.time().toString("ss").toInt(); + if ((s >= 0 && s < 15) || (s >= 30 && s < 45)) { + ui->tuneButton->setChecked (false); + m_config.transceiver_tune (false); // reset rig tuning + return; + } + } + m_config.transceiver_tune (false); // reset rig tuning + if (blocked) return; + if (checked && (m_mode=="WSPR" || m_mode=="FST4W") + && m_beaconTxController.tuneKind () == BeaconTx::TuneKind::None) + { + processBeaconActions (m_beaconTxController.tuneStarted (BeaconTx::TuneKind::Manual)); + } + if (m_auto && !(m_mode=="WSPR" || m_mode=="FST4W")) ui->autoButton->click(); // stop any other transmission + stopWRTimer.stop(); // stop any Wait & Reply timeout + stopWCTimer.stop(); // stop any Wait & Call timeout + if (checked && m_config.tune_watchdog() && !(m_mode=="WSPR" || m_mode=="FST4W")) { + tuneATU_Timer.start (m_config.tune_watchdog_time()*1000); // tune watchdog + } + if (!checked) { + tuneATU_Timer.stop (); // stop tune watchdog when stopping Tune manually + ui->tuneButton->setText("Tune"); + } + static bool lastChecked = false; + if (lastChecked == checked) return; + lastChecked = checked; + if (checked && m_tune==false) { // we're starting tuning so remember Tx and change pwr to Tune value + if (m_config.pwrBandTuneMemory ()) { + auto const& curBand = ui->bandComboBox->currentText(); + m_pwrBandTxMemory[curBand] = ui->outAttenuation->value(); // remember our Tx pwr + m_PwrBandSetOK = false; + if (m_pwrBandTuneMemory.contains(curBand)) { + ui->outAttenuation->setValue(m_pwrBandTuneMemory[curBand].toInt()); // set to Tune pwr + } + m_PwrBandSetOK = true; + } + } + if (m_tune) { + tuneButtonTimer.start(250); + } else { + m_sentFirst73=false; + itone[0]=0; + on_monitorButton_clicked (true); + m_tune=true; + } + if (m_tci_audio) Q_EMIT m_config.transceiver_tune(checked); + else Q_EMIT tune (checked); +} + +void MainWindow::reset_transmit_controls_after_stop () +{ + m_autoRespondPeriodState.setEnableTx(false); + ui->pbBandHopping->setChecked(false); // disable band hopping + m_btxok=false; + m_bCallingCQ = false; + m_bAutoReply = false; // ready for next + m_maxPoints=-1; + if (ui->DX_Call_Button->isChecked()) ui->DX_Call_Button->click (); + stopWRTimer.stop(); // Stop any Wait & Reply timeout + stopWCTimer.stop(); // Stop any Wait & Call timeout + tuneATU_Timer.stop (); // stop tune watchdog when stopping Tune manually + no_wait_and_call = false; + m_specOp=m_config.special_op_id(); + if (ui->respondComboBox->isVisible() && autoRespondPolicy () != AutoRespondPolicy::None) { + m_autoRespondScores.reset(); + } + pounce = false; + ui->autoButton->setChecked(false); // ensure autoButton is unchecked + ui->tuneButton->setChecked (false); + ui->tuneButton->setText("Tune"); + m_tune=false; + m_bTxTime=false; + filtered = false; + ignored = false; + m_muted = false; + check_button_color(); +} + +void MainWindow::on_stopTxButton_clicked() // Stop Tx +{ + noteTxStopReason (TxEvidence::TxStopReason::UserHalt); + if (m_beaconTxController.txLifecycle () == BeaconTx::TxLifecycle::Decided + || m_beaconTxController.txLifecycle () == BeaconTx::TxLifecycle::StartRequested) + { + m_tx_when_ready = false; + ptt1Timer.stop (); + processBeaconActions (m_beaconTxController.transmitWindowEnded ()); + if (g_iptt == 1 || m_transmitting) stopTx (); + else g_iptt = 0; + } + if (m_beaconTxController.active ()) + { + m_beaconTxController.setAutoEnabled (false); + } + if (m_tune) stop_tuning (); + if (m_auto) auto_tx_mode (false); + reset_transmit_controls_after_stop (); +} + +void MainWindow::on_pbR2T_clicked() +{ + ui->TxFreqSpinBox->setValue(ui->RxFreqSpinBox->value ()); +} + +void MainWindow::on_pbT2R_clicked() +{ + if (ui->RxFreqSpinBox->isEnabled ()) + { + ui->RxFreqSpinBox->setValue (ui->TxFreqSpinBox->value ()); + } +} + +void MainWindow::on_pbR2T_2_clicked() +{ + ui->TxFreqSpinBox_2->setValue(ui->RxFreqSpinBox_2->value ()); +} + +void MainWindow::on_pbT2R_2_clicked() +{ + ui->RxFreqSpinBox_2->setValue (ui->TxFreqSpinBox_2->value ()); +} + +void MainWindow::on_readFreq_clicked() +{ + if (m_transmitting) return; + + if (m_config.transceiver_online ()) + { + m_config.sync_transceiver (true, true); + } +} + +void MainWindow::on_cbFast9_clicked(bool b) +{ + if(m_mode=="JT9") { + m_bFast9=b; +// ui->cbAutoSeq->setVisible(b); + blocked=true; // needed to prevent a loop + on_actionJT9_triggered(); + QTimer::singleShot (50, [=] {blocked = false;}); // needed to prevent a loop + QTimer::singleShot (200, [=] { + if(m_mode=="JT9") m_settings->setValue("JT9_Fast",m_bFast9); + }); + } + + if(b) { + m_TRperiod = ui->sbTR->value (); + } else { + m_TRperiod=60.0; + } + progressBar.setMaximum(int(m_TRperiod)); + m_wideGraph->setPeriod(m_TRperiod,m_nsps); + fast_config(b); + statusChanged (); +} + +void MainWindow::on_pbTxNext_clicked(bool b) +{ + if (m_mode=="WSPR" || m_mode=="FST4W") + { + auto const pendingStart = m_beaconTxController.txLifecycle () + == BeaconTx::TxLifecycle::StartRequested; + auto const planId = m_beaconTxController.txPlanId (); + processBeaconActions (m_beaconTxController.setTxNext (b)); + if (!b && pendingStart && !m_beaconTxController.transmitWindow ()) + { + m_tx_when_ready = false; + ptt1Timer.stop (); + if (m_transmitting) stopTx (); + else + { + g_iptt = 0; + processBeaconActions (m_beaconTxController.txStopped (planId)); + } + } + } + if (b && !ui->autoButton->isChecked ()) + { + ui->autoButton->click (); // make sure Tx is possible + } +} + +void MainWindow::on_pbFoxReset_clicked() +{ + if(m_specOp!=SpecOp::FOX) return; + auto button = MessageBox::query_message (this, tr ("Confirm Reset"), + tr ("Are you sure you want to clear the QSO queues?")); + if(button == MessageBox::Yes) { + FoxReset("Manual Reset"); + } +} + +void MainWindow::on_pbFreeText_clicked() +{ + bool ok; + QString freeTextMsg; + if(m_config.superFox()) { + freeTextMsg = QInputDialog::getText (this, tr("Free Text Message"), + tr("Message:"), QLineEdit::Normal, m_freeTextMsg0, &ok).left(26); + } else { + freeTextMsg = QInputDialog::getText (this, tr("Free Text Message"), + tr("Message:"), QLineEdit::Normal, m_freeTextMsg0, &ok).left(13); + } + if(!ok) return; + + freeTextMsg=freeTextMsg.toUpper(); + if(m_config.superFox()) { + // Mirrors valid_sfox_free_text in lib/superfox/sfox_pack.f90. + QString const validChars {" 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ+-./?"}; + for(QChar const ch: freeTextMsg) { + if(!validChars.contains(ch)) { + QString const message = tr ("SuperFox free text may only contain " + "spaces, digits, uppercase letters, and + - . / ?."); + MessageBox::warning_message (this, tr ("Free Text Message"), message); + return; + } + } + } + + m_freeTextMsg=freeTextMsg; + m_freeTextMsg0=m_freeTextMsg; +} + +void MainWindow::on_pbBestSP_clicked() +{ + m_bBestSPArmed = !m_bBestSPArmed; + if(m_bBestSPArmed and !m_transmitting) ui->pbBestSP->setStyleSheet ("QPushButton{color:red}"); + if(!m_bBestSPArmed) ui->pbBestSP->setStyleSheet (""); + if(m_bBestSPArmed) m_dateTimeBestSP=QDateTime::currentDateTimeUtc(); +} + +void MainWindow::on_houndButton_clicked (bool checked) +{ + if (checked) { + HoldTxFreqStatus = ui->cbHoldTxFreq->isChecked(); // save state of the Hold Tx Freq checkbox + m_config.setSpecial_Hound(); + ui->tx1->setVisible(true); + ui->tx1->setEnabled(true); + ui->txb1->setEnabled(true); + } else { + m_config.setSpecial_None(); + keep_frequency = true; + QTimer::singleShot (250, [=] {keep_frequency = false;}); + } + m_specOp=m_config.special_op_id(); + on_actionFT8_triggered(); + check_button_color(); +} + +void MainWindow::on_cbHoldTxFreq_clicked (bool) +{ + HoldTxFreqStatus = ui->cbHoldTxFreq->isChecked(); // save state of the Hold Tx Freq checkbox +} + +void MainWindow::on_ft8Button_clicked() +{ + if (m_specOp==SpecOp::HOUND or m_specOp==SpecOp::FOX) { + m_config.setSpecial_None(); + m_specOp=m_config.special_op_id(); + } + on_actionFT8_triggered(); +} + +void MainWindow::on_ft4Button_clicked() +{ + on_actionFT4_triggered(); +} + +void MainWindow::on_msk144Button_clicked() +{ + on_actionMSK144_triggered(); +} + +void MainWindow::on_q65Button_clicked() +{ + if (m_specOp==SpecOp::Q65_PILEUP) { + m_q65PileupCopiedLastRxCall.clear(); + m_q65PileupCopiedCallers.clear(); + m_config.setSpecial_None(); + m_specOp=m_config.special_op_id(); + } + on_actionQ65_triggered(); +} + +void MainWindow::on_jt65Button_clicked() +{ + on_actionJT65_triggered(); +} + +void MainWindow::on_echoButton_clicked() +{ + on_actionEcho_triggered(); +} + +void MainWindow::on_pb15A_clicked() +{ + ui->sbTR->setValue(15); + ui->sbSubmode->setValue(0); +} + +void MainWindow::on_pb15C_clicked() +{ + ui->sbTR->setValue(15); + ui->sbSubmode->setValue(2); + ui->TxFreqSpinBox->setValue(700); +} + +void MainWindow::on_pb30B_clicked() +{ + ui->sbTR->setValue(30); + ui->sbSubmode->setValue(1); +} + +void MainWindow::on_pb60C_clicked() +{ + ui->sbTR->setValue(60); + ui->sbSubmode->setValue(2); +} + +void MainWindow::on_pb60D_clicked() +{ + ui->sbTR->setValue(60); + ui->sbSubmode->setValue(3); +} + +void MainWindow::on_pb60E_clicked() +{ + ui->sbTR->setValue(60); + ui->sbSubmode->setValue(4); + ui->TxFreqSpinBox->setValue(700); +} + +void MainWindow::on_pb160_clicked() +{ + requestBandButtonFrequency (1840000, 1837000, m_msk144_tr); +} + +void MainWindow::on_pb80_clicked() +{ + requestBandButtonFrequency (3573000, 3576000, m_msk144_tr); +} + +void MainWindow::on_pb60_clicked() +{ + requestBandButtonFrequency (5357000, 5357000, m_msk144_tr); +} + +void MainWindow::on_pb40_clicked() +{ + requestBandButtonFrequency (7074000, 7077000, m_msk144_tr); +} + +void MainWindow::on_pb30_clicked() +{ + requestBandButtonFrequency (10136000, 10139000, m_msk144_tr); +} + +void MainWindow::on_pb20_clicked() +{ + requestBandButtonFrequency (14074000, 14077000, m_msk144_tr); +} + +void MainWindow::on_pb17_clicked() +{ + requestBandButtonFrequency (18100000, 18103000, m_msk144_tr); +} + +void MainWindow::on_pb15_clicked() +{ + requestBandButtonFrequency (21074000, 21077000, m_msk144_tr); +} + +void MainWindow::on_pb12_clicked() +{ + requestBandButtonFrequency (24915000, 24918000, m_msk144_tr); +} + +void MainWindow::on_pb10_clicked() +{ + requestBandButtonFrequency (28074000, 28077000, m_msk144_tr); +} + +void MainWindow::on_pb6_clicked() +{ + requestBandButtonFrequency (50313000, 50316000, m_msk144_tr6); +} + +void MainWindow::on_pb2_clicked() +{ + requestBandButtonFrequency (144074000, 144077000, m_msk144_tr2); +} + +void MainWindow::on_pb70_clicked() +{ + requestBandButtonFrequency (432074000, 432077000, m_msk144_tr); +} + +void MainWindow::on_pb8_clicked() +{ + requestBandButtonFrequency (40680000, 40680000, m_msk144_tr); +} + +void MainWindow::on_pb50_clicked() +{ + requestBandButtonFrequency (50313000, 50316000, m_msk144_tr6); +} + +void MainWindow::on_pb4_clicked() +{ + requestBandButtonFrequency (70154000, 70154000, m_msk144_tr6); +} + +void MainWindow::on_pb144_clicked() +{ + requestBandButtonFrequency (144074000, 144077000, m_msk144_tr2); +} + +void MainWindow::on_pb220_clicked() +{ + requestBandButtonFrequency (222174000, 222177000, m_msk144_tr); +} + +void MainWindow::on_pb432_clicked() +{ + requestBandButtonFrequency (432174000, 432177000, m_msk144_tr); +} + +void MainWindow::on_pb902_clicked() +{ + requestBandButtonFrequency (902174000, 902177000, m_msk144_tr); +} + +void MainWindow::on_pb23_clicked() +{ + requestBandButtonFrequency (1296065000, 1296065000, m_msk144_tr); +} + +void MainWindow::on_pb13_clicked() +{ + requestBandButtonFrequency (2304065000, 2304065000, m_msk144_tr); +} + +void MainWindow::on_pb9_clicked() +{ + requestBandButtonFrequency (3400065000, 3400065000, m_msk144_tr); +} + +void MainWindow::on_pb5G_clicked() +{ + requestBandButtonFrequency (5760200000, 5760200000, m_msk144_tr); +} + +void MainWindow::on_pb10G_clicked() +{ + requestBandButtonFrequency (10368200000, 10368200000, m_msk144_tr); +} + +void MainWindow::on_pb24G_clicked() +{ + requestBandButtonFrequency (24048200000, 24048200000, m_msk144_tr); +} + +void MainWindow::on_pbSendMessage_clicked() +{ + submitJttyDraft (ui->Tx_Message->text ().toUpper ()); +} + +void MainWindow::on_Tx_Message_returnPressed() +{ + on_pbSendMessage_clicked(); +} + +void MainWindow::on_pbF1_clicked() +{ + sendJttyFunctionKey(1); +} + +void MainWindow::on_pbF2_clicked() +{ + sendJttyFunctionKey(2); +} + +void MainWindow::on_pbF3_clicked() +{ + sendJttyFunctionKey(3); +} + +void MainWindow::on_pbF4_clicked() +{ + sendJttyFunctionKey(4); +} + +void MainWindow::on_pbF5_clicked() +{ + sendJttyFunctionKey(5); +} + +void MainWindow::on_pbF6_clicked() +{ + sendJttyFunctionKey(6); +} + +void MainWindow::on_pbF7_clicked() +{ + sendJttyFunctionKey(7); +} + +void MainWindow::on_pbF8_clicked() +{ + sendJttyFunctionKey(8); +} diff --git a/widgets/plotter.cpp b/widgets/plotter.cpp index 263566d4..aaef1384 100644 --- a/widgets/plotter.cpp +++ b/widgets/plotter.cpp @@ -10,17 +10,31 @@ #include "qt_helpers.hpp" #include "commons.h" #include "moc_plotter.cpp" +#include <algorithm> #include <fstream> #include <iostream> #define MAX_SCREENSIZE 8192 +namespace +{ + // Matches WideGraph's m_swide capacity and dialog width limit. + constexpr int kWaterfallStorageWidth = 2048; + + int drawablePixel(int x, int extent) + { + if(extent <= 1) return 0; + if(x < 0) return 0; + if(x >= extent) return extent - 1; + return x; + } +} extern "C" { void flat4_(float swide[], int* iz, int* nflatten); void plotsave_(float swide[], int* m_w , int* m_h1, int* irow); } -extern dec_data dec_data; +extern dec_data_t& dec_data; CPlotter::CPlotter(QWidget *parent) : //CPlotter Constructor QFrame {parent}, @@ -28,7 +42,6 @@ CPlotter::CPlotter(QWidget *parent) : //CPlotter Constructor m_bScaleOK {false}, m_bReference {false}, m_bReference0 {false}, - m_fSpan {2000.0}, m_plotZero {0}, m_plotGain {0}, m_plot2dGain {0}, @@ -36,12 +49,9 @@ CPlotter::CPlotter(QWidget *parent) : //CPlotter Constructor m_nSubMode {0}, m_Running {false}, m_paintEventBusy {false}, - m_fftBinWidth {1500.0/2048.0}, m_dialFreq {0.}, m_sum {}, m_dBStepSize {10}, - m_FreqUnits {1}, - m_hdivs {HORZ_DIVS}, m_line {0}, m_fSample {12000}, m_nsps {6912}, @@ -49,7 +59,6 @@ CPlotter::CPlotter(QWidget *parent) : //CPlotter Constructor m_Percent2DScreen0 {0}, m_rxFreq {1020}, m_txFreq {0}, - m_startFreq {0}, m_lastMouseX {-1}, m_lastPaintedX {-1} // m_tol {100} @@ -95,7 +104,7 @@ void CPlotter::resizeEvent(QResizeEvent* ) //resizeEvent() if( m_Size != size() or (m_bReference != m_bReference0) or m_Percent2DScreen != m_Percent2DScreen0) { m_Size = size(); - m_w = m_Size.width(); + m_scale.setWidth(m_Size.width()); m_h = m_Size.height(); m_h2 = m_Percent2DScreen*m_h/100.0; if(m_h2>m_h-30) m_h2=m_h-30; @@ -109,12 +118,11 @@ void CPlotter::resizeEvent(QResizeEvent* ) //resizeEvent() m_HoverOverlayPixmap.fill(Qt::transparent); m_2DPixmap = QPixmap(m_Size.width(), m_h2); m_2DPixmap.fill(Qt::black); - m_WaterfallPixmap = QPixmap(m_Size.width(), m_h1); + m_WaterfallPixmap = QPixmap(kWaterfallStorageWidth, m_h1); + m_WaterfallPixmap.fill(Qt::black); m_OverlayPixmap = QPixmap(m_Size.width(), m_h2); m_OverlayPixmap.fill(Qt::black); - m_WaterfallPixmap.fill(Qt::black); - m_2DPixmap.fill(Qt::black); - m_ScalePixmap = QPixmap(m_w,30); + m_ScalePixmap = QPixmap(m_scale.width(),30); m_ScalePixmap.fill(Qt::white); m_Percent2DScreen0 = m_Percent2DScreen; m_bResized = true; @@ -122,6 +130,7 @@ void CPlotter::resizeEvent(QResizeEvent* ) //resizeEvent() m_x=0; } DrawOverlay(); + if(m_bScaleOK) drawSavedWaterfall(); } void CPlotter::paintEvent(QPaintEvent *) // paintEvent() @@ -130,7 +139,7 @@ void CPlotter::paintEvent(QPaintEvent *) // paint m_paintEventBusy=true; QPainter painter(this); painter.drawPixmap(0,0,m_ScalePixmap); - painter.drawPixmap(0,30,m_WaterfallPixmap); + painter.drawPixmap(0,30,m_WaterfallPixmap,0,0,m_scale.width(),m_h1); painter.drawPixmap(0,m_h1,m_2DPixmap); int x = XfromFreq(m_rxFreq); if (m_bars) { @@ -148,19 +157,26 @@ void CPlotter::draw(float swide[], bool bScroll, bool bRed) if (!m_TRperiod) return; // not ready to plot yet int j,j0; float y,y2,ymin; - double fac = sqrt(m_binsPerPixel*m_waterfallAvg/15.0); + bool const drawWaterfall = bScroll or bRed or m_bReplot; + double fac = sqrt(m_scale.binsPerPixel()*m_waterfallAvg/15.0); double gain = fac*pow(10.0,0.015*m_plotGain); double gain2d = pow(10.0,0.02*(m_plot2dGain)); - if(m_bReference != m_bReference0) resizeEvent(NULL); - m_bReference0=m_bReference; + if(m_bReference != m_bReference0) { + m_bReference0=m_bReference; + resizeEvent(NULL); + } //move current data down one line (must do this before attaching a QPainter object) - if(bScroll and !m_bReplot) m_WaterfallPixmap.scroll(0,1,0,0,m_w,m_h1); + int waterfallWidth = m_WaterfallPixmap.width(); + if(waterfallWidth<1) return; + if(bScroll and !m_bReplot) { + m_WaterfallPixmap.scroll(0,1,0,0,waterfallWidth,m_h1); + } QPainter painter1(&m_WaterfallPixmap); if(m_bFirst or bRed or !m_bQ65_Sync or m_mode!=m_mode0 or m_bResized or m_rxFreq!=m_rxFreq0) { - m_2DPixmap = m_OverlayPixmap.copy(0,0,m_w,m_h2); + m_2DPixmap = m_OverlayPixmap.copy(0,0,m_scale.width(),m_h2); m_bFirst=false; m_bResized=false; m_rxFreq0=m_rxFreq; @@ -185,59 +201,84 @@ void CPlotter::draw(float swide[], bool bScroll, bool bRed) static QPoint LineBuf3[MAX_SCREENSIZE]; static QPoint LineBuf4[MAX_SCREENSIZE]; j=0; - j0=int(m_startFreq/m_fftBinWidth + 0.5); - int iz=XfromFreq(5000.0); - int jz=iz*m_binsPerPixel; - m_fMax=FreqfromX(iz); - if(bScroll and swide[0]<1.e29) { - flat4_(swide,&iz,&m_Flatten); - if(!m_bReplot) flat4_(&dec_data.savg[j0],&jz,&m_Flatten); - } + j0=int(m_scale.startHz()/m_scale.fftBinWidthHz() + 0.5); + int izVisible=XfromFreq(5000.0); + if(izVisible>waterfallWidth) izVisible=waterfallWidth; + if(izVisible<0) izVisible=0; + int jz=izVisible*m_scale.binsPerPixel(); - ymin=1.e30; - if(swide[0]>1.e29 and swide[0]< 1.5e30) painter1.setPen(Qt::green); - if(swide[0]>1.4e30) painter1.setPen(Qt::red); - if(!m_bReplot) { + if(bScroll and !m_bReplot) { m_j=0; int irow=-1; - plotsave_(swide,&m_w,&m_h1,&irow); + plotsave_(swide,&waterfallWidth,&m_h1,&irow); } + + m_swideDisplay.resize(waterfallWidth); + std::copy(swide, swide + waterfallWidth, m_swideDisplay.data()); + float *swidePlot = m_swideDisplay.data(); + if(swidePlot[0]<1.e29 and izVisible>0) { + flat4_(swidePlot,&izVisible,&m_Flatten); + } + + m_savgDisplay.clear(); + if(bScroll and !m_bReplot) { + int savgBins = jz; + int availableBins = NSMAX - j0; + if(savgBins > availableBins) savgBins = availableBins; + if(savgBins > 0) { + m_savgDisplay.resize(savgBins); + std::copy(&dec_data.savg[j0], &dec_data.savg[j0] + savgBins, m_savgDisplay.data()); + flat4_(m_savgDisplay.data(),&savgBins,&m_Flatten); + } + } + + ymin=1.e30; + if(swidePlot[0]>1.e29 and swidePlot[0]< 1.5e30) painter1.setPen(Qt::green); + if(swidePlot[0]>1.4e30) painter1.setPen(Qt::red); ymin = 0; - for(int i=0; i<iz; i++) { - y=swide[i]; - int y1 = 10.0*gain*y + m_plotZero; - if (y1<0) y1=0; - if (y1>254) y1=254; - if (swide[i]<1.e29) painter1.setPen(g_ColorTbl[y1]); - painter1.drawPoint(i,m_j); + if(drawWaterfall) { + for(int i=0; i<izVisible; i++) { + y=swidePlot[i]; + if( y != y ) y=0.0; // check for nan - a nan is not equal to itself + y = 10.0*gain*y + m_plotZero; + if (y<0.0) y=0.0; + if (y>254.0) y=254.0; + int y1 = y; + if (swidePlot[i]<1.e29) painter1.setPen(g_ColorTbl[y1]); + painter1.drawPoint(i,m_j); + } } - m_line++; + if(drawWaterfall) m_line++; + + if(m_bReplot and m_mode!="Q65") return; float y2min=1.e30; float y2max=-1.e30; - for(int i=0; i<iz; i++) { - y=swide[i] - ymin; + for(int i=0; i<izVisible; i++) { + y=swidePlot[i] - ymin; y2=0; if(m_bCurrent) y2 = gain2d*y + m_plot2dZero; //Current if(bScroll) { float sum=0.0; - int j=j0+m_binsPerPixel*i; - for(int k=0; k<m_binsPerPixel; k++) { - sum+=dec_data.savg[j++]; + int j=m_scale.binsPerPixel()*i; + for(int k=0; k<m_scale.binsPerPixel() && j<m_savgDisplay.size(); k++) { + sum+=m_savgDisplay[j++]; } m_sum[i]=sum; } - if(m_bCumulative) y2=gain2d*(m_sum[i]/m_binsPerPixel + m_plot2dZero); + if(m_bCumulative) y2=gain2d*(m_sum[i]/m_scale.binsPerPixel() + m_plot2dZero); if(m_Flatten==0) y2 += 15; //### could do better! ### if(m_bLinearAvg) { //Linear Avg (yellow) float sum=0.0; - int j=j0+m_binsPerPixel*i; - for(int k=0; k<m_binsPerPixel; k++) { + int j=j0+m_scale.binsPerPixel()*i; + int n=0; + for(int k=0; k<m_scale.binsPerPixel() and j<NSMAX; k++) { sum+=spectra_.syellow[j++]; + n++; } - y2=2.0*gain2d*sum/m_binsPerPixel + m_plot2dZero; + if(n>0) y2=2.0*gain2d*sum/n + m_plot2dZero; } if(m_bReference) { //Reference (red) @@ -248,7 +289,7 @@ void CPlotter::draw(float swide[], bool bScroll, bool bRed) } - if(i==iz-1 and !m_bQ65_Sync and !m_bTotalPower) { + if(i==izVisible-1 and !m_bQ65_Sync and !m_bTotalPower) { painter2D.drawPolyline(LineBuf,j); } LineBuf[j].setX(i); @@ -257,9 +298,14 @@ void CPlotter::draw(float swide[], bool bScroll, bool bRed) if(y2>y2max) y2max=y2; j++; } - if(m_bReplot and m_mode!="Q65") return; - if(swide[0]>1.0e29) m_line=0; + if(!drawWaterfall) { + update(); + m_bScaleOK=true; + return; + } + + if(swidePlot[0]>1.0e29) m_line=0; if(m_mode=="FT4" and m_line==34) m_line=0; if(m_line == painter1.fontMetrics ().height () && m_timestamp!=0) { painter1.setPen(Qt::white); @@ -271,10 +317,10 @@ void CPlotter::draw(float swide[], bool bScroll, bool bRed) } else { auto hr = m_nUTC / 10000; auto start = QTime {hr, (m_nUTC - 10000 * hr) / 100, m_nUTC % 100} - .toString (m_TRperiod < 60. ? "hh:mm:ss" : "hh:mm"); + .toString ((m_TRperiod < 60.0) or (m_mode=="JTTY") ? "hh:mm:ss" : "hh:mm"); t = QString {"%1 %2"}.arg (start).arg (m_rxBand); } - QRect rect{5, -2, m_w-10, painter1.fontMetrics().ascent()}; + QRect rect{5, -2, m_scale.width()-10, painter1.fontMetrics().ascent()}; QRect boundingRect; painter1.drawText(rect, m_timestamp==2?0x0082:0x0081,t, &boundingRect); } @@ -337,23 +383,23 @@ void CPlotter::draw(float swide[], bool bScroll, bool bRed) painter2D.setPen(Qt::white); Font.setWeight(QFont::Bold); painter2D.setFont(Font); - painter2D.drawText(m_w-100,m_h2/2,t); + painter2D.drawText(m_scale.width()-100,m_h2/2,t); } } if(m_bTotalPower and m_pdB>1.0) { painter2D.setPen(Qt::green); - if(m_x==m_w-1) { - for (int i=0; i<m_w-1; i++) { + if(m_x==m_scale.width()-1) { + for (int i=0; i<m_scale.width()-1; i++) { LineBuf4[i].setY(LineBuf4[i+1].y()); } } int yy=m_h2 - 0.1*m_vpixperdiv*(m_pdB-20.0); LineBuf4[m_x].setX(m_x); LineBuf4[m_x].setY(yy); - if(LineBuf4[m_w-1].y()==0) LineBuf4[m_w-1].setY(yy); + if(LineBuf4[m_scale.width()-1].y()==0) LineBuf4[m_scale.width()-1].setY(yy); painter2D.drawPolyline(LineBuf4,m_x); - if(m_x < m_w-1) m_x++; + if(m_x < m_scale.width()-1) m_x++; } update(); //trigger a new paintEvent @@ -370,15 +416,22 @@ void CPlotter::drawRed(int ia, int ib, float swide[]) void CPlotter::replot() { resizeEvent(NULL); - float swide[m_w]; +} + +void CPlotter::drawSavedWaterfall() +{ + if(m_bReplot) return; + int waterfallWidth = m_WaterfallPixmap.width(); + if(waterfallWidth<1) return; + m_replotRow.resize(waterfallWidth); m_bReplot=true; for(int irow=0; irow<m_h1; irow++) { m_j=irow; - plotsave_(swide,&m_w,&m_h1,&irow); - draw(swide,false,false); + plotsave_(m_replotRow.data(),&waterfallWidth,&m_h1,&irow); + draw(m_replotRow.data(),false,false); } if(m_mode=="Q65" and m_bQ65_Sync) { - draw(swide,false,true); + draw(m_replotRow.data(),false,true); } update(); //trigger a new paintEvent m_bReplot=false; @@ -388,44 +441,31 @@ void CPlotter::DrawOverlay() //DrawOverlay() { if(m_OverlayPixmap.isNull()) return; if(m_WaterfallPixmap.isNull()) return; - int w = m_WaterfallPixmap.width(); + auto const grid = m_scale.gridLayout(); int x,y,x1,x2,x3,x4,x5,x6; - float pixperdiv; - double df = m_binsPerPixel*m_fftBinWidth; QPen penOrange(QColor(255,165,0),3); QPen penGreen(QColor(15,153,105), 3); //Mark Tol range or BW with dark green line if(m_useDarkStyle) penGreen.setBrush(Qt::green); // lighter green for dark style QPen penRed(Qt::red, 3); //Mark Tx freq with red QPainter painter(&m_OverlayPixmap); painter.setBackground (palette ().brush (backgroundRole ())); + int const overlayRight = drawablePixel(m_OverlayPixmap.width(), m_OverlayPixmap.width()); + int const overlayBottom = drawablePixel(m_OverlayPixmap.height(), m_OverlayPixmap.height()); QLinearGradient gradient(0, 0, 0 ,m_h2); //fill background with gradient gradient.setColorAt(1, Qt::black); gradient.setColorAt(0, Qt::darkBlue); painter.setBrush(gradient); - painter.drawRect(0, 0, m_w, m_h2); + painter.drawRect(0, 0, overlayRight, overlayBottom); painter.setBrush(Qt::SolidPattern); - m_fSpan = w*df; -// int n=m_fSpan/10; - m_freqPerDiv=10; - if(m_fSpan>100) m_freqPerDiv=20; - if(m_fSpan>250) m_freqPerDiv=50; - if(m_fSpan>500) m_freqPerDiv=100; - if(m_fSpan>1000) m_freqPerDiv=200; - if(m_fSpan>2500) m_freqPerDiv=500; - if(!m_bTotalPower) { - pixperdiv = m_freqPerDiv/df; - m_hdivs = w*df/m_freqPerDiv + 1.9999; - float xx0=float(m_startFreq)/float(m_freqPerDiv); - xx0=xx0-int(xx0); - int x0=xx0*pixperdiv+0.5; - for( int i=1; i<m_hdivs; i++) { //draw vertical grids - x = (int)((float)i*pixperdiv ) - x0; - if(x >= 0 and x<=m_w) { + for( int i=1; i<grid.overlayDivisionCount; i++) { //draw vertical grids + x = int(i*grid.pixelsPerDivision) - grid.verticalGridOffsetPixels; + if(x >= 0 and x<=m_scale.width()) { painter.setPen(QPen(Qt::white, 1,Qt::DotLine)); - painter.drawLine(x, 0, x , m_h2); + x = drawablePixel(x, m_OverlayPixmap.width()); + painter.drawLine(x, 0, x , overlayBottom); } } } @@ -435,9 +475,9 @@ void CPlotter::DrawOverlay() //DrawOverlay() for( int i=1; i<VERT_DIVS; i++) { //draw horizontal grids y = int(i*m_vpixperdiv); if(m_bTotalPower) { - painter.drawLine(15, y, w, y); + painter.drawLine(15, y, overlayRight, y); } else { - painter.drawLine(0, y, w, y); + painter.drawLine(0, y, overlayRight, y); } } @@ -454,7 +494,7 @@ void CPlotter::DrawOverlay() //DrawOverlay() for( int i=1; i<5*VERT_DIVS; i++) { //draw horizontal 2 dB grids if(i%5 > 0) { y = int(0.2*i*m_vpixperdiv); - painter.drawLine(0, y, w, y); + painter.drawLine(0, y, overlayRight, y); } } } @@ -462,6 +502,8 @@ void CPlotter::DrawOverlay() //DrawOverlay() QRect rect0; QPainter painter0(&m_ScalePixmap); painter0.setBackground (palette ().brush (backgroundRole ())); + int const scaleRight = drawablePixel(m_scale.width(), m_ScalePixmap.width()); + int const scaleBottom = drawablePixel(m_ScalePixmap.height(), m_ScalePixmap.height()); //create Font to use for scales QFont Font("Arial"); @@ -474,42 +516,38 @@ void CPlotter::DrawOverlay() //DrawOverlay() painter0.setPen(Qt::black); } - if(m_binsPerPixel < 1) m_binsPerPixel=1; - m_hdivs = w*df/m_freqPerDiv + 0.9999; - if (m_useDarkStyle) { m_ScalePixmap.fill(Qt::black); } else { m_ScalePixmap.fill(Qt::white); } - painter0.drawRect(0, 0, w, 30); - MakeFrequencyStrs(); - + painter0.drawRect(0, 0, scaleRight, scaleBottom); //draw tick marks on upper scale - pixperdiv = m_freqPerDiv/df; - for( int i=0; i<m_hdivs; i++) { //major ticks - x = (int)((m_xOffset+i)*pixperdiv ); - painter0.drawLine(x,18,x,30); + for( int i=0; i<grid.scaleDivisionCount; i++) { //major ticks + x = (int)((grid.firstMajorDivisionOffset+i)*grid.pixelsPerDivision); + painter0.drawLine(drawablePixel(x, m_ScalePixmap.width()), 18, + drawablePixel(x, m_ScalePixmap.width()), scaleBottom); } - int minor=5; - if(m_freqPerDiv==200) minor=4; - for( int i=1; i<minor*m_hdivs; i++) { //minor ticks - x = i*pixperdiv/minor; - painter0.drawLine(x,24,x,30); + for( int i=1; i<grid.minorDivisionCount*grid.scaleDivisionCount; i++) { //minor ticks + x = i*grid.pixelsPerDivision/grid.minorDivisionCount; + painter0.drawLine(drawablePixel(x, m_ScalePixmap.width()), 24, + drawablePixel(x, m_ScalePixmap.width()), scaleBottom); } //draw frequency values - for( int i=0; i<=m_hdivs; i++) { - x = (int)((m_xOffset+i)*pixperdiv - pixperdiv/2); - if(int(x+pixperdiv/2) > 70) { - rect0.setRect(x,0, (int)pixperdiv, 20); - painter0.drawText(rect0, Qt::AlignHCenter|Qt::AlignVCenter,m_HDivText[i]); + for( int i=0; i<=grid.scaleDivisionCount; i++) { + x = (int)((grid.firstMajorDivisionOffset+i)*grid.pixelsPerDivision + - grid.pixelsPerDivision/2); + if(int(x+grid.pixelsPerDivision/2) > 70) { + rect0.setRect(x,0, (int)grid.pixelsPerDivision, 20); + painter0.drawText(rect0, Qt::AlignHCenter|Qt::AlignVCenter,grid.labels[i]); } } float bw=9.0*12000.0/m_nsps; //JT9 if(m_mode=="FT4") bw=3*12000.0/576.0; //FT4 ### (3x, or 4x???) ### if(m_mode=="FT8") bw=7*12000.0/1920.0; //FT8 + if(m_mode=="JTTY") bw=3*12000.0/384.0; //JTTY if(m_mode.startsWith("FST4")) { int h=int(pow(2.0,m_nSubMode)); int nsps=800; @@ -534,17 +572,20 @@ void CPlotter::DrawOverlay() //DrawOverlay() painter0.setPen(penGreen); x1=XfromFreq(m_rxFreq-m_tol); x2=XfromFreq(m_rxFreq+m_tol); - painter0.drawLine(x1,29,x2,29); + painter0.drawLine(drawablePixel(x1, m_ScalePixmap.width()), scaleBottom, + drawablePixel(x2, m_ScalePixmap.width()), scaleBottom); for(int i=0; i<4; i++) { x1=XfromFreq(m_rxFreq+bw*i/3.0); int j=24; if(i==0) j=18; - painter0.drawLine(x1,j,x1,30); + painter0.drawLine(drawablePixel(x1, m_ScalePixmap.width()), j, + drawablePixel(x1, m_ScalePixmap.width()), scaleBottom); } painter0.setPen(penRed); for(int i=0; i<4; i++) { x1=XfromFreq(m_txFreq+bw*i/3.0); - painter0.drawLine(x1,12,x1,18); + painter0.drawLine(drawablePixel(x1, m_ScalePixmap.width()), 12, + drawablePixel(x1, m_ScalePixmap.width()), 18); } } @@ -579,72 +620,91 @@ void CPlotter::DrawOverlay() //DrawOverlay() if(m_mode=="WSPR") { x1=XfromFreq(1400); x2=XfromFreq(1600); - painter0.drawLine(x1,26,x2,26); + painter0.drawLine(drawablePixel(x1, m_ScalePixmap.width()), 26, + drawablePixel(x2, m_ScalePixmap.width()), 26); } if(m_mode=="FST4W") { x1=XfromFreq(m_rxFreq-m_tol); x2=XfromFreq(m_rxFreq+m_tol); - painter0.drawLine(x1,26,x2,26); + painter0.drawLine(drawablePixel(x1, m_ScalePixmap.width()), 26, + drawablePixel(x2, m_ScalePixmap.width()), 26); } if(m_mode=="FreqCal") { //FreqCal x1=XfromFreq(m_rxFreq-m_tol); x2=XfromFreq(m_rxFreq+m_tol); - painter0.drawLine(x1,29,x2,29); + painter0.drawLine(drawablePixel(x1, m_ScalePixmap.width()), scaleBottom, + drawablePixel(x2, m_ScalePixmap.width()), scaleBottom); x1=XfromFreq(m_rxFreq); - painter0.drawLine(x1,24,x1,30); + painter0.drawLine(drawablePixel(x1, m_ScalePixmap.width()), 24, + drawablePixel(x1, m_ScalePixmap.width()), scaleBottom); } int yh=5; int yTxTop=12; int yRxBottom=yTxTop + 2*yh + 4; if(m_mode=="JT9" or m_mode=="JT65" or m_mode=="Q65" or m_mode=="FT8" - or m_mode=="FT4" or m_mode.startsWith("FST4")) { + or m_mode=="FT4" or m_mode.startsWith("FST4") or m_mode=="JTTY") { if(m_mode=="FST4" and !m_bSingleDecode) { x1=XfromFreq(m_nfa); x2=XfromFreq(m_nfb); - painter0.drawLine(x1,25,x1+5,30); // Mark FST4 F_Low - painter0.drawLine(x1,25,x1+5,20); - painter0.drawLine(x2,25,x2-5,30); // Mark FST4 F_High - painter0.drawLine(x2,25,x2-5,20); + painter0.drawLine(drawablePixel(x1, m_ScalePixmap.width()), 25, + drawablePixel(x1 + 5, m_ScalePixmap.width()), scaleBottom); + painter0.drawLine(drawablePixel(x1, m_ScalePixmap.width()), 25, + drawablePixel(x1 + 5, m_ScalePixmap.width()), 20); + painter0.drawLine(drawablePixel(x2, m_ScalePixmap.width()), 25, + drawablePixel(x2 - 5, m_ScalePixmap.width()), scaleBottom); + painter0.drawLine(drawablePixel(x2, m_ScalePixmap.width()), 25, + drawablePixel(x2 - 5, m_ScalePixmap.width()), 20); } - if(m_mode=="Q65" or (m_mode=="JT65" and m_bVHF) or (m_mode=="FT8" and m_bSuperHound)) { + if(m_mode=="Q65" or m_mode=="JTTY" or (m_mode=="JT65" and m_bVHF) or + (m_mode=="FT8" and m_bSuperHound)) { painter0.setPen(penGreen); x1=XfromFreq(m_rxFreq-m_tol); x2=XfromFreq(m_rxFreq+m_tol); - painter0.drawLine(x1,26,x2,26); + painter0.drawLine(drawablePixel(x1, m_ScalePixmap.width()), 26, + drawablePixel(x2, m_ScalePixmap.width()), 26); x1=XfromFreq(m_rxFreq); - painter0.drawLine(x1,20,x1,26); + painter0.drawLine(drawablePixel(x1, m_ScalePixmap.width()), 20, + drawablePixel(x1, m_ScalePixmap.width()), 26); if(m_mode=="JT65") { painter0.setPen(penOrange); x3=XfromFreq(m_rxFreq+20.0*bw/65.0); //RO - painter0.drawLine(x3,20,x3,26); + painter0.drawLine(drawablePixel(x3, m_ScalePixmap.width()), 20, + drawablePixel(x3, m_ScalePixmap.width()), 26); x4=XfromFreq(m_rxFreq+30.0*bw/65.0); //RRR - painter0.drawLine(x4,20,x4,26); + painter0.drawLine(drawablePixel(x4, m_ScalePixmap.width()), 20, + drawablePixel(x4, m_ScalePixmap.width()), 26); x5=XfromFreq(m_rxFreq+40.0*bw/65.0); //73 - painter0.drawLine(x5,20,x5,26); + painter0.drawLine(drawablePixel(x5, m_ScalePixmap.width()), 20, + drawablePixel(x5, m_ScalePixmap.width()), 26); } painter0.setPen(penGreen); x6=XfromFreq(m_rxFreq+bw); //Highest tone if(m_mode=="FT8" and m_bSuperHound) x6=XfromFreq(m_rxFreq+1500.0); - painter0.drawLine(x6,20,x6,26); + painter0.drawLine(drawablePixel(x6, m_ScalePixmap.width()), 20, + drawablePixel(x6, m_ScalePixmap.width()), 26); } else { // Draw the green goal post painter0.setPen(penGreen); x1=XfromFreq(m_rxFreq); x2=XfromFreq(m_rxFreq+bw); - painter0.drawLine(x1,yRxBottom-yh,x1,yRxBottom); - painter0.drawLine(x1,yRxBottom,x2,yRxBottom); - painter0.drawLine(x2,yRxBottom-yh,x2,yRxBottom); + painter0.drawLine(drawablePixel(x1, m_ScalePixmap.width()), yRxBottom-yh, + drawablePixel(x1, m_ScalePixmap.width()), yRxBottom); + painter0.drawLine(drawablePixel(x1, m_ScalePixmap.width()), yRxBottom, + drawablePixel(x2, m_ScalePixmap.width()), yRxBottom); + painter0.drawLine(drawablePixel(x2, m_ScalePixmap.width()), yRxBottom-yh, + drawablePixel(x2, m_ScalePixmap.width()), yRxBottom); if(m_mode.startsWith("FST4")) { x1=XfromFreq(m_rxFreq-m_tol); x2=XfromFreq(m_rxFreq+m_tol); - painter0.drawLine(x1,26,x2,26); // Mark the Tol range + painter0.drawLine(drawablePixel(x1, m_ScalePixmap.width()), 26, + drawablePixel(x2, m_ScalePixmap.width()), 26); } } } @@ -665,14 +725,19 @@ void CPlotter::DrawOverlay() //DrawOverlay() } if (m_bars) { overPainter.setPen(Qt::green); // Rx bars - overPainter.drawLine(x1,0,x1,m_h); overPainter.drawLine(x2,0,x2,m_h); + int const overlayBottom = drawablePixel(m_h, m_h); + overPainter.drawLine(drawablePixel(x1, m_DialOverlayPixmap.width()), 0, + drawablePixel(x1, m_DialOverlayPixmap.width()), overlayBottom); + overPainter.drawLine(drawablePixel(x2, m_DialOverlayPixmap.width()), 0, + drawablePixel(x2, m_DialOverlayPixmap.width()), overlayBottom); } } // red bars if(m_mode.startsWith("FT") or m_mode.startsWith("JT") or m_mode=="Q65" or m_mode.startsWith("FST4") or m_mode.mid(0,4)=="WSPR") { - x1=XfromFreq(m_txFreq); x2=XfromFreq(m_txFreq+bw); + x1=XfromFreq(m_txFreq); + x2=XfromFreq(m_txFreq+bw); if(m_mode=="FT8" and m_bSuperFox) x2=XfromFreq(m_txFreq+1500.0); if(m_mode=="WSPR") { bw=4*12000.0/8192.0; //WSPR @@ -680,13 +745,17 @@ void CPlotter::DrawOverlay() //DrawOverlay() } if (m_bars) { overPainter.setPen(Qt::red); // Tx bars - overPainter.drawLine(x1,0,x1,m_h); overPainter.drawLine(x2,0,x2,m_h); + int const overlayBottom = drawablePixel(m_h, m_h); + overPainter.drawLine(drawablePixel(x1, m_DialOverlayPixmap.width()), 0, + drawablePixel(x1, m_DialOverlayPixmap.width()), overlayBottom); + overPainter.drawLine(drawablePixel(x2, m_DialOverlayPixmap.width()), 0, + drawablePixel(x2, m_DialOverlayPixmap.width()), overlayBottom); } } // red goal post if(m_mode=="JT9" or m_mode=="JT65" or m_mode.mid(0,4)=="WSPR" or m_mode=="Q65" - or m_mode=="FT8" or m_mode=="FT4" or m_mode.startsWith("FST4")) { + or m_mode=="FT8" or m_mode=="FT4" or m_mode.startsWith("FST4") or m_mode=="JTTY") { painter0.setPen(penRed); x1=XfromFreq(m_txFreq); if(m_mode=="FT8" and m_bSuperFox) { @@ -700,6 +769,8 @@ void CPlotter::DrawOverlay() //DrawOverlay() x2=XfromFreq(m_txFreq+0.5*bw); } // Draw the red goal post + x1 = drawablePixel(x1, m_ScalePixmap.width()); + x2 = drawablePixel(x2, m_ScalePixmap.width()); painter0.drawLine(x1,yTxTop,x1,yTxTop+yh); painter0.drawLine(x1,yTxTop,x2,yTxTop); painter0.drawLine(x2,yTxTop,x2,yTxTop+yh); @@ -713,8 +784,10 @@ void CPlotter::DrawOverlay() //DrawOverlay() hoverPainter.setCompositionMode(QPainter::CompositionMode_Source); hoverPainter.fillRect(0, 0, m_Size.width(), m_h, Qt::transparent); hoverPainter.setPen(QPen(Qt::white)); // white bars - hoverPainter.drawLine(0, 30, 0, m_h); // first slot, left line hover - hoverPainter.drawLine(fwidth, 30, fwidth, m_h); // first slot, right line hover + int const hoverBottom = drawablePixel(m_h, m_HoverOverlayPixmap.height()); + hoverPainter.drawLine(0, 30, 0, hoverBottom); // first slot, left line hover + hoverPainter.drawLine(drawablePixel(fwidth, m_HoverOverlayPixmap.width()), 30, + drawablePixel(fwidth, m_HoverOverlayPixmap.width()), hoverBottom); } if(m_dialFreq>10.13 and m_dialFreq< 10.15 and m_mode.mid(0,4)!="WSPR" and m_mode!="FST4W") { @@ -722,35 +795,22 @@ void CPlotter::DrawOverlay() //DrawOverlay() float f2=f1+200.0; x1=XfromFreq(f1); x2=XfromFreq(f2); - if(x1<=m_w and x2>=0) { + if(x1<=m_scale.width() and x2>=0) { painter0.setPen(penOrange); //Mark WSPR sub-band orange - painter0.drawLine(x1,9,x2,9); + painter0.drawLine(drawablePixel(x1, m_ScalePixmap.width()), 9, + drawablePixel(x2, m_ScalePixmap.width()), 9); } } } -void CPlotter::MakeFrequencyStrs() //MakeFrequencyStrs -{ - int f=(m_startFreq+m_freqPerDiv-1)/m_freqPerDiv; - f*=m_freqPerDiv; - m_xOffset=float(f-m_startFreq)/m_freqPerDiv; - for(int i=0; i<=m_hdivs; i++) { - m_HDivText[i].setNum(f); - f+=m_freqPerDiv; - } -} - int CPlotter::XfromFreq(float f) //XfromFreq() { - int x = int(m_w * (f - m_startFreq)/m_fSpan + 0.5); - if(x<0 ) return 0; - if(x>m_w) return m_w; - return x; + return m_scale.xFromFreqHz(f); } float CPlotter::FreqfromX(int x) //FreqfromX() { - return float(m_startFreq + x*m_binsPerPixel*m_fftBinWidth); + return m_scale.freqHzFromX(x); } void CPlotter::SetRunningState(bool running) //SetRunningState() @@ -801,8 +861,7 @@ void CPlotter::setPlot2dZero(int plot2dZero) //setPlot2dZero void CPlotter::setStartFreq(int f) //SetStartFreq() { - m_startFreq=f; - m_fMax=FreqfromX(XfromFreq(5000.0)); + m_scale.setStartHz(f); resizeEvent(NULL); DrawOverlay(); update(); @@ -810,29 +869,23 @@ void CPlotter::setStartFreq(int f) //SetStartFreq() int CPlotter::startFreq() //startFreq() { - return m_startFreq; + return m_scale.startHz(); } -int CPlotter::plotWidth(){return m_WaterfallPixmap.width();} //plotWidth +int CPlotter::plotWidth(){return m_scale.width();} //plotWidth void CPlotter::UpdateOverlay() {DrawOverlay();} //UpdateOverlay void CPlotter::setDataFromDisk(bool b) {m_dataFromDisk=b;} //setDataFromDisk -void CPlotter::setRxRange(int fMin) //setRxRange -{ - m_fMin=fMin; -} - void CPlotter::setBinsPerPixel(int n) //setBinsPerPixel { - m_binsPerPixel = n; - m_fMax=FreqfromX(XfromFreq(5000.0)); + m_scale.setBinsPerPixel(n); DrawOverlay(); //Redraw scales and ticks update(); //trigger a new paintEvent} } int CPlotter::binsPerPixel() //binsPerPixel { - return m_binsPerPixel; + return m_scale.binsPerPixel(); } void CPlotter::setWaterfallAvg(int n) //setNavg @@ -868,16 +921,16 @@ void CPlotter::mouseMoveEvent (QMouseEvent * event) event->ignore(); if(m_freq) { if (!m_bTotalPower){ - QToolTip::showText(event->globalPos(),QString::number(int(FreqfromX(x)))); + QToolTip::showText(event->globalPos(),QString::number(int(FreqfromX(x))),this); } else { int y=event->y(); float pdB=10.0*(m_h-y)/m_vpixperdiv + 20.0; if(y<(m_h-m_h2)) { - QToolTip::showText(event->globalPos(),QString::number(int(FreqfromX(x)))); + QToolTip::showText(event->globalPos(),QString::number(int(FreqfromX(x))),this); } else { QString t; t=t.asprintf("%4.1f dB",pdB); - QToolTip::showText(event->globalPos(),t); + QToolTip::showText(event->globalPos(),t,this); } } } @@ -925,7 +978,17 @@ void CPlotter::mouseDoubleClickEvent (QMouseEvent * event) bool rightbutton = (event->button() & Qt::RightButton); bool leftbutton = (event->button() & Qt::LeftButton); bool ctrl = (event->modifiers() & Qt::ControlModifier); - if (leftbutton) { + if (leftbutton and m_mode=="JTTY" and !ctrl) { + // Waterfall region is screen y in [30,30+m_h1); row 0 (newest) is at + // the top, growing downward -- see the m_j=0 draw + scroll(0,1,...) in + // draw(). Ctrl+double-click still falls through below for the old, + // unbounded full-buffer rescan. + int const row = event->y() - 30; + if (row >= 0 and row < m_h1) { + float const secondsAgo = row * m_waterfallAvg * 3456.0f/12000.0f; + emit jttyDecodeAgainAt(secondsAgo); + } + } else if (leftbutton) { int n=2; if(ctrl) n+=100; emit freezeDecode1(n); @@ -947,11 +1010,12 @@ void CPlotter::setNsps(double trperiod, int nsps) //setNsps { m_TRperiod=trperiod; m_nsps=nsps; - m_fftBinWidth=1500.0/2048.0; - if(m_nsps==15360) m_fftBinWidth=1500.0/2048.0; - if(m_nsps==40960) m_fftBinWidth=1500.0/6144.0; - if(m_nsps==82944) m_fftBinWidth=1500.0/12288.0; - if(m_nsps==252000) m_fftBinWidth=1500.0/32768.0; + double fftBinWidth=1500.0/2048.0; + if(m_nsps==15360) fftBinWidth=1500.0/2048.0; + if(m_nsps==40960) fftBinWidth=1500.0/6144.0; + if(m_nsps==82944) fftBinWidth=1500.0/12288.0; + if(m_nsps==252000) fftBinWidth=1500.0/32768.0; + m_scale.setFftBinWidthHz(fftBinWidth); DrawOverlay(); //Redraw scales and ticks update(); //trigger a new paintEvent} } @@ -975,7 +1039,7 @@ void CPlotter::setSubMode(int n) //setSubMode int CPlotter::Fmax() { - return m_fMax; + return m_scale.maxFreqHz(); } void CPlotter::setDialFreq(double d) diff --git a/widgets/plotter.h b/widgets/plotter.h index 1f3b8c42..af2ec36c 100644 --- a/widgets/plotter.h +++ b/widgets/plotter.h @@ -15,8 +15,9 @@ #include <QColor> #include <QToolTip> +#include "WaterfallScale.hpp" + #define VERT_DIVS 7 //specify grid screen divisions -#define HORZ_DIVS 20 extern bool g_single_decode; @@ -50,7 +51,6 @@ public: int plotWidth(); void UpdateOverlay(); void setDataFromDisk(bool b); - void setRxRange(int fMin); void setBinsPerPixel(int n); int binsPerPixel(); void setWaterfallAvg(int n); @@ -71,9 +71,9 @@ public: bool cumulative() const {return m_bCumulative;} void setLinearAvg(bool b) {m_bLinearAvg = b;} bool linearAvg() const {return m_bLinearAvg;} - void setBreadth(qint32 w) {m_w = w;} - qint32 breadth() const {return m_w;} - float fSpan() const {return m_fSpan;} + void setBreadth(qint32 w) {m_scale.setWidth(w);} + qint32 breadth() const {return m_scale.width();} + float fSpan() const {return m_scale.spanHz();} void setColours(QVector<QColor> const& cl); void setTimestamp(int n); void setBars(bool b); @@ -102,6 +102,7 @@ public: signals: void freezeDecode1(int n); void setFreq1(int rxFreq, int txFreq); + void jttyDecodeAgainAt(float secondsAgo); protected: //re-implemented widget event handlers @@ -113,9 +114,9 @@ protected: private: - void MakeFrequencyStrs(); int XfromFreq(float f); float FreqfromX(int x); + void drawSavedWaterfall(); QAction * m_set_freq_action; @@ -126,7 +127,7 @@ private: bool m_bReference; bool m_bReference0; bool m_bQ65_Sync; - bool m_bTotalPower; + bool m_bTotalPower=false; bool m_bVHF; bool m_bSingleDecode; bool m_bFirst=true; @@ -134,8 +135,7 @@ private: bool m_bSuperFox=false; bool m_bSuperHound=false; bool m_bars; - bool m_freq; - float m_fSpan; + bool m_freq=false; float m_pdB=0.0; float m_vpixperdiv; bool m_useDarkStyle=false; @@ -144,9 +144,7 @@ private: qint32 m_plotGain; qint32 m_plot2dGain; qint32 m_plot2dZero; - qint32 m_binsPerPixel; qint32 m_waterfallAvg; - qint32 m_w; qint32 m_Flatten; qint32 m_nSubMode; qint32 m_ia; @@ -166,7 +164,9 @@ private: QPoint m_pos; QSize m_Size; QString m_Str; - QString m_HDivText[483]; + QVector<float> m_swideDisplay; + QVector<float> m_savgDisplay; + QVector<float> m_replotRow; QString m_mode; QString m_mode0; QString m_rxBand; @@ -177,20 +177,15 @@ private: bool m_dataFromDisk; bool m_bReplot; - double m_fftBinWidth; double m_dialFreq; - double m_xOffset; double m_TRperiod; float m_sum[2048]; qint32 m_dBStepSize; - qint32 m_FreqUnits; - qint32 m_hdivs; qint32 m_line; qint32 m_fSample; qint32 m_xClick; - qint32 m_freqPerDiv; qint32 m_nsps; qint32 m_Percent2DScreen; qint32 m_Percent2DScreen0; @@ -200,15 +195,14 @@ private: qint32 m_rxFreq; qint32 m_rxFreq0=0; qint32 m_txFreq; - qint32 m_fMin; - qint32 m_fMax; - qint32 m_startFreq; qint32 m_tol; qint32 m_lastMouseX; qint32 m_lastPaintedX; qint32 m_j; char m_sutc[6]; + WaterfallScale m_scale; + private slots: void leaveEvent(QEvent *event) override; diff --git a/widgets/qsymonitor.cpp b/widgets/qsymonitor.cpp index efe9181a..0d04e766 100644 --- a/widgets/qsymonitor.cpp +++ b/widgets/qsymonitor.cpp @@ -2,6 +2,7 @@ #include "ui_qsymonitor.h" #include "SettingsGroup.hpp" #include "Configuration.hpp" +#include "widgets/QSYMessageParser.h" #include "qt_helpers.hpp" #include "commons.h" #include <QSettings> @@ -71,7 +72,7 @@ void QSYMonitor::on_clearButton_clicked() void QSYMonitor::createQSYLine(QString value) { - QStringList qsySpot = value.split(' '); + QStringList qsySpot = value.split(' ', SkipEmptyParts); if(qsySpot.length() == 3) { QString theTime = qsySpot[0]; QString theCall = qsySpot[1]; @@ -81,267 +82,16 @@ void QSYMonitor::createQSYLine(QString value) void QSYMonitor::getBandModeFreq(QString theTime, QString theCall, QString value) { - if(value.at(0).isLetter() || value.at(0) == '9' || value.at(0) == '4' || value.at(0) == '7') { - QString bandParam = ""; - QString modeParam = value.at(0); - QString freqParam = ""; - bandParam = value.mid(0,1); - modeParam = value.at(1); - freqParam = value.mid(2, 3); - QString band = ""; - QString mode = ""; - QString freq = ""; + QSYMessageParser::Message const message = + QSYMessageParser::decode (value, configuration_->region ()); + if (message.type != QSYMessageParser::Type::Frequency) return; - if (bandParam == "A") { - if (modeParam.at(0).isLetter()) { - freq = "50."; - } else { - if (modeParam =="0") { - freq = "50."; - } else if (modeParam =="1") { - freq = "51."; - } else if (modeParam =="2") { - freq = "52."; - } else if (modeParam =="3") { - freq = "53."; - } - } - } - else if (bandParam == "B") { - if (modeParam.at(0).isLetter()) { - freq = "144."; - } else { - if (modeParam =="4") { - freq = "144."; - } else if (modeParam =="5") { - freq = "145."; - } else if (modeParam =="6") { - freq = "146."; - } else if (modeParam =="7") { - freq = "147."; - } - } - } - else if (bandParam == "C") { - if (modeParam.at(0).isLetter()) { - freq = "222."; - } else { - if (modeParam =="2") { - freq = "222."; - } else if (modeParam =="3") { - freq = "223."; - } - } - } - else if (bandParam == "D") { - if (modeParam.at(0).isLetter()) { - freq = "432."; - } else { - if (configuration_->region()==2) { - if (modeParam =="0") { - freq = "440."; - } else if (modeParam =="1") { - freq = "441."; - } else if (modeParam =="2") { - freq = "442."; - } else if (modeParam =="3") { - freq = "443."; - } else if (modeParam =="4") { - freq = "444."; - } else if (modeParam =="5") { - freq = "445."; - } else if (modeParam =="6") { - freq = "446."; - } else if (modeParam =="7") { - freq = "447."; - } else if (modeParam =="8") { - freq = "448."; - } else if (modeParam =="9") { - freq = "449."; - } - } - else { //not region 2 - if (modeParam =="0") { - freq = "430."; - } else if (modeParam =="1") { - freq = "431."; - } else if (modeParam =="2") { - freq = "432."; - } else if (modeParam =="3") { - freq = "433."; - } else if (modeParam =="4") { - freq = "434."; - } else if (modeParam =="5") { - freq = "435."; - } else if (modeParam =="6") { - freq = "436."; - } else if (modeParam =="7") { - freq = "437."; - } else if (modeParam =="8") { - freq = "438."; - } else if (modeParam =="9") { - freq = "439."; - } - } - } - } - else if (bandParam == "E") { - if (modeParam.at(0).isLetter()) { - freq = "1296."; - } else { - if (modeParam =="0") { - freq = "1290."; - } else if (modeParam =="1") { - freq = "1291."; - } else if (modeParam =="2") { - freq = "1292."; - } else if (modeParam =="3") { - freq = "1293."; - } else if (modeParam =="4") { - freq = "1294."; - } else if (modeParam =="5") { - freq = "1295."; - } else if (modeParam =="6") { - freq = "1296."; - } else if (modeParam =="7") { - freq = "1297."; - } else if (modeParam =="8") { - freq = "1298."; - } else if (modeParam =="9") { - freq = "1299."; - } - } - } - else if (bandParam == "F") { - freq = "2304."; - } - else if (bandParam == "G") { - freq = "3400."; - } - else if (bandParam == "H") { - freq = "5760."; - } - else if (bandParam == "I") { - freq = "10368."; - } - else if (bandParam == "J") { - if (configuration_->region()==2) { - freq = "24192."; - } else { - freq = "24048."; - } - } - else if (bandParam == "9") { - freq = "902."; - } - else if (bandParam == "K") { - freq = "903."; - } - else if (bandParam == "J") { - freq = "24192."; - } - else if (bandParam == "X") { - freq = "24048."; - } - else if (bandParam == "4") { - freq = "40."; - } - else if (bandParam == "7") { - freq = "70."; - } - else if (bandParam == "L") { - freq = "0."; - } - else if (bandParam == "M") { - freq = "1."; - } - else if (bandParam == "N") { - freq = "3."; - } - else if (bandParam == "O") { - freq = "5."; - } - else if (bandParam == "P") { - freq = "7."; - } - else if (bandParam == "Q") { - freq = "10."; - } - else if (bandParam == "R") { - freq = "14."; - } - else if (bandParam == "S") { - freq = "18."; - } - else if (bandParam == "T") { - freq = "21."; - } - else if (bandParam == "U") { - freq = "24."; - } - else if (bandParam == "V") { - freq = "28."; - } - else if (bandParam == "W") { - freq = "29."; - } else { - freq = ""; - } - - freq = freq + freqParam; - if(!modeParam.at(0).isLetter()) { - mode = "FM"; - } - else if (modeParam == 'V') { - mode = "SSB"; - } - else if (modeParam == 'J') { - mode = "FT4"; - } - else if (modeParam == 'L') { - mode = "FT8"; - } - else if (modeParam == 'K') { - mode = "MSK144"; - } - else if (modeParam == 'W') { - mode = "CW"; - } - else if (modeParam == 'A') { - mode = "JT9"; - } - else if (modeParam == 'B') { - mode = "JT65"; - } - else if (modeParam == 'C') { - mode = "FST4"; - } - else if (modeParam == 'D') { - mode = "Q65-30B"; - } - else if (modeParam == 'E') { - mode = "Q65-60C"; - } - else if (modeParam == 'F') { - mode = "Q65-60D"; - } - else if (modeParam == 'G') { - mode = "Q65-60E"; - } - else if (modeParam == 'H') { - mode = "Q65-120D"; - } - else { - mode = ""; - } - int numSpaces1 = 2; - int numSpaces2 = 10 - theCall.length(); - int numSpaces3 = 11 - freq.length(); - QString spaces1_theCall = QString(numSpaces1, ' ').append(theCall); - QString spaces2_theFreq = QString(numSpaces2, ' ').append(freq); - QString spaces3_theMode = QString(numSpaces3, ' ').append(mode); - QString qsyMessageString = theTime + spaces1_theCall + spaces2_theFreq + spaces3_theMode; - ui->QSYMonitorTextBrowser->append(qsyMessageString); - } + int numSpaces1 = 2; + int numSpaces2 = 10 - theCall.length(); + int numSpaces3 = 11 - message.frequency_mhz.length(); + QString spaces1_theCall = QString(numSpaces1, ' ').append(theCall); + QString spaces2_theFreq = QString(numSpaces2, ' ').append(message.frequency_mhz); + QString spaces3_theMode = QString(numSpaces3, ' ').append(message.mode); + QString qsyMessageString = theTime + spaces1_theCall + spaces2_theFreq + spaces3_theMode; + ui->QSYMonitorTextBrowser->append(qsyMessageString); } - diff --git a/widgets/widegraph.cpp b/widgets/widegraph.cpp index 2bdef6bd..f33b570c 100644 --- a/widgets/widegraph.cpp +++ b/widgets/widegraph.cpp @@ -11,6 +11,7 @@ #include "Configuration.hpp" #include "MessageBox.hpp" #include "SettingsGroup.hpp" +#include "PerformanceTrace.hpp" #include "moc_widegraph.cpp" WideGraph::WideGraph(QSettings * settings, QWidget *parent) : @@ -23,6 +24,7 @@ WideGraph::WideGraph(QSettings * settings, QWidget *parent) : m_bHaveTransmitted {false}, m_user_defined {tr ("User Defined")} { + PerformanceTrace::Phase construction {"widegraph.construct"}; ui->setupUi(this); setWindowTitle (QApplication::applicationName () + " - " + tr ("Wide Graph")); @@ -42,6 +44,9 @@ WideGraph::WideGraph(QSettings * settings, QWidget *parent) : connect(ui->widePlot, SIGNAL(setFreq1(int,int)),this, SLOT(setFreq2(int,int))); + connect(ui->widePlot, SIGNAL(jttyDecodeAgainAt(float)),this, + SLOT(wideJttyDecodeAgainAt(float))); + { //Restore user's settings SettingsGroup g {m_settings, "WideGraph"}; @@ -98,7 +103,6 @@ WideGraph::WideGraph(QSettings * settings, QWidget *parent) : m_waterfallPalette=m_settings->value("WaterfallPalette","Default").toString(); m_userPalette = WFPalette {m_settings->value("UserPalette").value<WFPalette::Colours> ()}; m_fMinPerBand = m_settings->value ("FminPerBand").toHash (); - setRxRange (); ui->controls_widget->setVisible(!m_settings->value("HideControls",false).toBool()); ui->cbControls->setChecked(!m_settings->value("HideControls",false).toBool()); } @@ -193,7 +197,7 @@ void WideGraph::dataSink2(float s[], float df3, int ihsym, int ndiskdata, float for (int j=0; j<jz; j++) { float ss=0.0; float smax=0; - for (int k=0; k<nbpp; k++) { + for (int k=0; (k<nbpp && i<NSMAX-1); k++) { float sp=splot[i++]; ss += sp; smax=qMax(smax,sp); @@ -273,11 +277,9 @@ void WideGraph::wideFreezeDecode(int n) //wideFreez emit freezeDecode2(n); } -void WideGraph::setRxRange () +void WideGraph::wideJttyDecodeAgainAt(float secondsAgo) //wideJttyDecodeAgainAt { - ui->widePlot->setRxRange (Fmin ()); - ui->widePlot->DrawOverlay(); - ui->widePlot->update(); + emit jttyDecodeAgainAt2(secondsAgo); } int WideGraph::Fmin() //Fmin @@ -295,6 +297,17 @@ int WideGraph::fSpan() return ui->widePlot->fSpan (); } +#if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) +void WideGraph::setFrequencyScale(int startFrequency, int binsPerPixel, int plotWidth) +{ + ui->widePlot->setFixedWidth(plotWidth); + ui->widePlot->setStartFreq(startFrequency); + ui->widePlot->setBinsPerPixel(binsPerPixel); + ui->fStartSpinBox->setValue(startFrequency); + ui->bppSpinBox->setValue(binsPerPixel); +} +#endif + void WideGraph::setPeriod(double trperiod, int nsps) //SetPeriod { m_TRperiod=trperiod; @@ -365,7 +378,6 @@ void WideGraph::on_spec2dComboBox_currentIndexChanged(int index) void WideGraph::on_fSplitSpinBox_valueChanged(int n) //fSplit { if (m_rxBand != "60m") m_fMinPerBand[m_rxBand] = n; - setRxRange (); } void WideGraph::setFreq2(int rxFreq, int txFreq) //setFreq2 @@ -392,7 +404,6 @@ void WideGraph::setRxBand (QString const& band) ui->fSplitSpinBox->setEnabled (m_mode.startsWith("FST4")); } ui->widePlot->setRxBand(band); - setRxRange (); } @@ -497,9 +508,31 @@ bool WideGraph::useRef() //Flatten return m_bRef; } +void WideGraph::setReferenceSpectrumAvailable(bool available) +{ + if(!available) { + m_bRef=false; + ui->cbRef->setChecked(false); + ui->widePlot->setFlatten(m_bFlatten,m_bRef); + } + ui->cbRef->setEnabled(available); +} + +void WideGraph::clearReferenceSpectrum(bool reference_spectrum_available) +{ + m_bRef=false; + ui->cbRef->setChecked(false); + ui->widePlot->setFlatten(m_bFlatten,m_bRef); + setReferenceSpectrumAvailable(reference_spectrum_available); + m_n=0; +} + void WideGraph::replot() { - if(ui->widePlot->scaleOK()) ui->widePlot->replot(); + if(ui->widePlot->scaleOK()) { + ui->widePlot->replot(); + ui->widePlot->draw(m_swide,false,false); + } } void WideGraph::on_gainSlider_valueChanged(int value) //Gain diff --git a/widgets/widegraph.h b/widgets/widegraph.h index 2b19dc98..d4d2d839 100644 --- a/widgets/widegraph.h +++ b/widgets/widegraph.h @@ -33,6 +33,9 @@ public: int Fmin(); int Fmax(); int fSpan(); +#if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) + void setFrequencyScale(int startFrequency, int binsPerPixel, int plotWidth); +#endif void saveSettings(); void setFsample(int n); void setPeriod(double trperiod, int nsps); @@ -41,6 +44,8 @@ public: void setSubMode(int n); bool flatten(); bool useRef(); + void setReferenceSpectrumAvailable(bool available); + void clearReferenceSpectrum(bool reference_spectrum_available); void setTol(int n); void setSuperFox(bool b); void setSuperHound(bool b); @@ -61,11 +66,13 @@ signals: void f11f12(int n); void setXIT2(int n); void setFreq3(int rxFreq, int txFreq); + void jttyDecodeAgainAt2(float secondsAgo); public slots: void wideFreezeDecode(int n); void setFreq2(int rxFreq, int txFreq); void setDialFreq(double d); + void wideJttyDecodeAgainAt(float secondsAgo); protected: void keyPressEvent (QKeyEvent *e) override; @@ -94,7 +101,6 @@ private slots: private: void readPalette (); - void setRxRange (); void replot(); QScopedPointer<Ui::WideGraph> ui; diff --git a/widgets/widegraph.ui b/widgets/widegraph.ui index 0f8b374e..5eaf8b39 100644 --- a/widgets/widegraph.ui +++ b/widgets/widegraph.ui @@ -42,7 +42,7 @@ </property> <property name="minimumSize"> <size> - <width>400</width> + <width>200</width> <height>100</height> </size> </property> @@ -408,7 +408,7 @@ <item> <widget class="QCheckBox" name="cbRef"> <property name="toolTip"> - <string><html><head/><body><p>Compute and save a reference spectrum. (Not yet fully implemented.)</p></body></html></string> + <string><html><head/><body><p>Apply a saved reference spectrum to flatten the received passband. Available after a reference spectrum has been measured. (Not yet fully implemented.)</p></body></html></string> </property> <property name="text"> <string>Ref Spec</string> diff --git a/widgets/widgets.pri b/widgets/widgets.pri deleted file mode 100644 index e82bfbbe..00000000 --- a/widgets/widgets.pri +++ /dev/null @@ -1,48 +0,0 @@ -SOURCES += \ - widgets/astro.cpp widgets/LettersSpinBox.cpp \ - widgets/logqso.cpp widgets/displaytext.cpp \ - widgets/meterwidget.cpp widgets/signalmeter.cpp \ - widgets/plotter.cpp widgets/widegraph.cpp widgets/about.cpp \ - widgets/mainwindow.cpp widgets/messageaveraging.cpp \ - widgets/activeStations.cpp \ - widgets/echoplot.cpp widgets/echograph.cpp widgets/fastgraph.cpp \ - widgets/fastplot.cpp widgets/MessageBox.cpp \ - widgets/colorhighlighting.cpp widgets/ExportCabrillo.cpp \ - widgets/AbstractLogWindow.cpp \ - widgets/FrequencyLineEdit.cpp widgets/FrequencyDeltaLineEdit.cpp \ - widgets/FoxLogWindow.cpp widgets/CabrilloLogWindow.cpp \ - widgets/HelpTextWindow.cpp widgets/RestrictedSpinBox.cpp \ - widgets/LazyFillComboBox.cpp widgets/CheckableItemComboBox.cpp \ - widgets/QSYMessage.cpp \ - widgets/QSYMessageCreator.cpp \ - widgets/qsymonitor.cpp - -HEADERS += \ - widgets/mainwindow.h widgets/plotter.h \ - widgets/about.h widgets/widegraph.h \ - widgets/displaytext.h widgets/logqso.h widgets/LettersSpinBox.hpp \ - widgets/FrequencyLineEdit.hpp widgets/FrequencyDeltaLineEdit.hpp widgets/signalmeter.h \ - widgets/meterwidget.h widgets/messageaveraging.h \ - widgets/activeStations.h \ - widgets/echoplot.h widgets/echograph.h widgets/fastgraph.h \ - widgets/fastplot.h widgets/MessageBox.hpp widgets/colorhighlighting.h \ - widgets/ExportCabrillo.h widgets/AbstractLogWindow.hpp \ - widgets/FoxLogWindow.hpp widgets/CabrilloLogWindow.hpp \ - widgets/DateTimeEdit.hpp widgets/HelpTextWindow.hpp \ - widgets/RestrictedSpinBox.hpp \ - widgets/LazyFillComboBox.hpp widgets/CheckableItemComboBox.hpp \ - widgets/QSYMessage.h \ - widgets/QSYMessageCreator.h \ - widgets/qsymonitor.h - -FORMS += \ - widgets/mainwindow.ui widgets/about.ui \ - widgets/widegraph.ui widgets/astro.ui \ - widgets/logqso.ui widgets/messageaveraging.ui \ - widgets/activeStations.ui \ - widgets/echograph.ui widgets/fastgraph.ui \ - widgets/colorhighlighting.ui widgets/ExportCabrillo.ui \ - widgets/FoxLogWindow.ui widgets/CabrilloLogWindow.ui \ - widgets/QSYMessage.ui \ - widgets/QSYMessageCreator.ui \ - widgets/qsymonitor.ui |
