diff options
| author | Christoph Berg <myon@debian.org> | 2026-10-09 14:12:49 +0200 |
|---|---|---|
| committer | Christoph Berg <myon@debian.org> | 2026-10-09 14:12:49 +0200 |
| commit | 76956486fa7ef52a51d4e56df1e13a9f19a6c93c (patch) | |
| tree | fe0c394439fdc167d1970372e8998874090854dd /widgets/mainwindow.cpp | |
| parent | 0685fcada9f95fe90f70b387cd7d757da8209624 (diff) | |
| parent | ffc62c792c9a5196cb4ce7a353287dfe20db6524 (diff) | |
Update upstream source from tag 'upstream/3.3.0_beta1+dfsg'
Update to upstream version '3.3.0~beta1+dfsg'
with Debian dir 85037bbb9376721108594b59b54ead82ac6924a3
Diffstat (limited to 'widgets/mainwindow.cpp')
| -rw-r--r-- | widgets/mainwindow.cpp | 976 |
1 files changed, 665 insertions, 311 deletions
diff --git a/widgets/mainwindow.cpp b/widgets/mainwindow.cpp index 596cb0e0..9c9031fb 100644 --- a/widgets/mainwindow.cpp +++ b/widgets/mainwindow.cpp @@ -405,9 +405,9 @@ extern "C" { void chk_samples_(int* m_ihsym,int* k, int* m_hsymStop); - void get_q3list_(char* fname, bool* bDiskData, int* nlist, char* list, FCL len1, FCL len2); + void get_q3list_(char* fname, bool* bDiskData, int* capacity, int* nlist, char* list, FCL len1, FCL len2); - void rm_q3list_(char* callsign, FCL len); + void rm_q3list_(char* fname, char* callsign, FCL len1, FCL len2); void jpl_setup_(char* fname, FCL len); } @@ -506,14 +506,14 @@ 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::grid_regexp {Radio::decoded_grid_pattern()}; 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, + MultiSettings * multi_settings, DecoderIpc::Session& decoderSession, unsigned downSampleFactor, QSplashScreen * splash, QProcessEnvironment const& env, bool automated_test, @@ -669,7 +669,7 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, m_rpt {"-15"}, m_pfx {Radio::PrefixSuffix::type1Prefixes()}, m_sfx {Radio::PrefixSuffix::type1Suffixes()}, - mem_jt9 {shdmem}, + m_decoderSession {decoderSession}, m_downSampleFactor (downSampleFactor), m_audioThreadPriority (QThread::HighPriority), m_bandEdited {false}, @@ -679,12 +679,8 @@ 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_jttyEnqueueId {0}, m_block_pwr_tooltip {false}, m_PwrBandSetOK {true}, m_toneSpacing {0.}, @@ -703,18 +699,59 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, programStart = true; qApp->setFont (m_config.text_font ()); ui->setupUi(this); + updateJttySendButton (); + ui->Tx_Message->setToolTip (tr ("Ctrl+K sends now (one-shot). Alt+J starts a live session that keeps sending as you type, until Alt+K signs off. Ctrl+Shift+K clears the box. Ctrl+H inserts a chat opener.")); + ui->Tx_Message->installEventFilter (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 (); + // A non-editable QComboBox always left-aligns its closed-box text, so fake a + // centered "label" via a read-only editable line edit; the dropdown list's + // own item text needs its alignment set separately (item textAlignment isn't + // a supported .ui property for QComboBox the way it is for list/table items). + ui->comboBoxJttyStyle->setEditable (true); + ui->comboBoxJttyStyle->lineEdit ()->setReadOnly (true); + ui->comboBoxJttyStyle->lineEdit ()->setAlignment (Qt::AlignCenter); + for (int i = 0; i < ui->comboBoxJttyStyle->count (); ++i) { + ui->comboBoxJttyStyle->setItemData (i, Qt::AlignCenter, Qt::TextAlignmentRole); + } + connect (ui->Tx_Message, &QPlainTextEdit::textChanged, this, + &MainWindow::guardJttyLiveEntryLock); + connect (ui->Tx_Message, &QPlainTextEdit::textChanged, this, + &MainWindow::autoAdvanceJttyLiveEntry); + connect (ui->Tx_Message, &QPlainTextEdit::textChanged, this, + &MainWindow::updateJttyLiveEntryFrameLabel); + m_jttyAutoAdvanceIdleTimer.setSingleShot (true); + connect (&m_jttyAutoAdvanceIdleTimer, &QTimer::timeout, this, + &MainWindow::idleFlushJttyLiveEntry); + // Acceptance leaves the span in m_jttyLiveEntryPending; only jttyTextCompleted (below) removes it. + connect (this, &MainWindow::jttyTextCompleted, this, [this] (qint64 requestId) { + for (int i = 0; i < m_jttyLiveEntryPending.size (); ++i) { + if (m_jttyLiveEntryPending[i].requestId == requestId) { + m_jttyLiveEntryFramesSent += m_jttyLiveEntryPending[i].totalFrames; + m_jttyLiveEntryPending.remove (i); + m_guardingJttyLiveEntryLock = true; + applyJttyLiveEntryFormatting (); + m_guardingJttyLiveEntryLock = false; + updateJttyLiveEntryFrameLabel (); + break; + } } }); connect (this, &MainWindow::jttyTextRejected, this, [this] (qint64 requestId, JttyTxRejectReason) { - m_jttyDraftAcceptanceTracker.reject (requestId); - }); + for (int i = 0; i < m_jttyLiveEntryPending.size (); ++i) { + if (m_jttyLiveEntryPending[i].requestId != requestId) continue; + auto const entry = m_jttyLiveEntryPending[i]; + m_jttyLiveEntryPending.remove (i); + // Only the most recently committed span can be cleanly reopened for editing. + if (entry.end == m_jttyLiveEntryCommitted) { + m_guardingJttyLiveEntryLock = true; + m_jttyLiveEntryCommitted = entry.start; + applyJttyLiveEntryFormatting (); + m_guardingJttyLiveEntryLock = false; + } + break; + } + }); 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); @@ -829,7 +866,16 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, connect (m_jttyTxStream, &JttyTxStream::txSourceCommitted, this, &MainWindow::recordTxSourceCommit, Qt::QueuedConnection); connect (this, &MainWindow::endJttyStream, m_jttyTxStream, &JttyTxStream::stop); + connect (this, &MainWindow::clearJttyStream, m_jttyTxStream, + &JttyTxStream::clearQueue, Qt::QueuedConnection); + connect (this, &MainWindow::enqueueJttyStream, m_jttyTxStream, + &JttyTxStream::queuePcm, Qt::DirectConnection); + connect (m_jttyTxStream, &JttyTxStream::enqueueAccepted, this, + &MainWindow::onJttyBackendEnqueueAccepted, Qt::QueuedConnection); + connect (m_jttyTxStream, &JttyTxStream::enqueueFailed, this, + &MainWindow::onJttyBackendEnqueueFailed, Qt::QueuedConnection); connect (m_jttyTxStream, &JttyTxStream::drained, this, &MainWindow::onJttyBackendDrained); + connect (m_jttyTxStream, &JttyTxStream::progress, this, &MainWindow::onJttyBackendProgress); connect (&m_audioThread, &QThread::finished, m_jttyTxStream, &QObject::deleteLater); // hook up the audio input stream signals, slots and disposal @@ -890,7 +936,11 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, #endif continue; } - if (previousEpoch != m_receiveConsumer.epoch ()) m_referenceInput.reset (); + if (previousEpoch != m_receiveConsumer.epoch ()) + { + m_referenceInput.reset (); + beginDecoderInput (); + } auto const frames = block->end (); #if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) if (m_automated_test) @@ -917,12 +967,17 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, if (!m_tci_audio) live_data_sink (std::move (audio)); }); connect (&m_audioThread, &QThread::finished, m_detector, &QObject::deleteLater); + connect(m_detector, &Detector::continuousAudioAvailable, this, + [this](JttyReceiveMailboxPtr mailbox) { + consumeJttyAudio(std::move(mailbox)); + }); // 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))); + connect(m_wideGraph.data(), &WideGraph::jttyDecodeAgainAtSample, + this, &MainWindow::jttyDecodeAgainAtSample); m_wideGraph->setReferenceSpectrumAvailable( QFile::exists(m_config.writeable_data_dir ().absoluteFilePath ("refspec.dat"))); @@ -1170,28 +1225,18 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, 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 (m_closing || !m_valid) return; + if (Jt9ProcessPhase::InitialStarting == m_jt9ProcessPhase + || Jt9ProcessPhase::ReplacementStarting == m_jt9ProcessPhase) + { + failDecoderStartup (proc_jt9.errorString ()); + return; + } if ((Jt9ProcessPhase::StopRequested == m_jt9ProcessPhase || Jt9ProcessPhase::Terminating == m_jt9ProcessPhase || Jt9ProcessPhase::Killing == m_jt9ProcessPhase) @@ -1201,6 +1246,13 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, }); #else connect(&proc_jt9, &QProcess::errorOccurred, [this] (QProcess::ProcessError error) { + if (m_closing || !m_valid) return; + if (Jt9ProcessPhase::InitialStarting == m_jt9ProcessPhase + || Jt9ProcessPhase::ReplacementStarting == m_jt9ProcessPhase) + { + failDecoderStartup (proc_jt9.errorString ()); + return; + } if ((Jt9ProcessPhase::StopRequested == m_jt9ProcessPhase || Jt9ProcessPhase::Terminating == m_jt9ProcessPhase || Jt9ProcessPhase::Killing == m_jt9ProcessPhase) @@ -1211,7 +1263,15 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, #endif connect(&proc_jt9, static_cast<void (QProcess::*) (int, QProcess::ExitStatus)> (&QProcess::finished), [this] (int exitCode, QProcess::ExitStatus status) { - if (m_closing) return; + if (m_closing || !m_valid) return; + if (Jt9ProcessPhase::InitialStarting == m_jt9ProcessPhase + || Jt9ProcessPhase::ReplacementStarting == m_jt9ProcessPhase) + { + readFromStdout (); + failDecoderStartup (tr ("The decoder exited before completing its startup handshake (code %1).") + .arg (exitCode)); + return; + } if (decoderRestartInProgress ()) { m_decoderShutdownTimer.stop (); @@ -1226,7 +1286,6 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, QTimer::singleShot (0, this, SLOT (close ())); return; } - m_jt9PayloadValid = false; m_activeJt9Decode = {}; m_decoderOutputFramer.reset (); startDecoderProcess (); @@ -1346,11 +1405,16 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, 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::continuousAudioAvailable, this, + [this](JttyReceiveMailboxPtr mailbox) { + consumeJttyAudio(std::move(mailbox)); + }); 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_progress, this, &MainWindow::onJttyBackendProgress); 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); @@ -1433,12 +1497,14 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, }); 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 ())); + if (Jt9ProcessPhase::InitialStarting != m_jt9ProcessPhase + && Jt9ProcessPhase::ReplacementStarting != m_jt9ProcessPhase) return; + // A GUI stall can delay stdout notification past the handshake deadline. + proc_jt9.waitForReadyRead (0); + if (proc_jt9.bytesAvailable ()) readFromStdout (); + if (Jt9ProcessPhase::InitialStarting != m_jt9ProcessPhase + && Jt9ProcessPhase::ReplacementStarting != m_jt9ProcessPhase) return; + failDecoderStartup (tr ("The decoder did not complete its startup handshake within five seconds.")); }); stopWRTimer.setSingleShot(true); @@ -1455,6 +1521,14 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, m_jttyTxWatchdog.setSingleShot(true); connect(&m_jttyTxWatchdog, &QTimer::timeout, this, &MainWindow::handleJttyTxWatchdog); + m_jttyEnqueueWatchdog.setSingleShot (true); + connect (&m_jttyEnqueueWatchdog, &QTimer::timeout, + this, &MainWindow::handleJttyEnqueueTimeout); +#ifdef WIN32 + m_mmttyHandoffWatchdog.setSingleShot (true); + connect (&m_mmttyHandoffWatchdog, &QTimer::timeout, + this, &MainWindow::handleMmttyHandoffTimeout); +#endif m_refSpecTimer.setInterval(1000); connect(&m_refSpecTimer, &QTimer::timeout, this, &MainWindow::updateReferenceSpectrumCountdown); @@ -2475,6 +2549,10 @@ void MainWindow::fixStop() //-------------------------------------------------------------- dataSink() void MainWindow::dataSink(qint64 frames) { + if (m_mode == "JTTY") { + if (m_diskData) decodeJttyDisk(int(frames)); + return; + } static float s[NSMAX]; char line[80]; int k(frames); @@ -2508,7 +2586,6 @@ void MainWindow::dataSink(qint64 frames) if(m_bFastMode) return; } - if(m_mode=="JTTY") fastSink(frames); // Get power, spectrum, and ihsym dec_data.params.nfa=m_wideGraph->nStartFreq(); @@ -2532,14 +2609,6 @@ 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" @@ -2909,24 +2978,6 @@ 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)}; @@ -3502,6 +3553,15 @@ void MainWindow::on_actionSettings_triggered() // Setup Dialog (Settin void MainWindow::monitor (bool state) { + if (state && jttyDrainInProgress()) return; + bool const leavingDiskData = state && m_diskData; + if (state && !m_monitoring && m_mode == "JTTY") updateJttyReceiveContext(); + if (!state && m_mode == "JTTY") { + auto const reason = m_jttyTxLifecycle.active () ? JttyReceiveReason::Transmission + : JttyReceiveReason::MonitorStopped; + m_detector->setInputStopReason(reason); + m_config.transceiver_receive_stop_reason(reason); + } ui->monitorButton->setChecked (state); if (state) { m_diskData = false; // no longer reading WAV files @@ -3547,6 +3607,7 @@ void MainWindow::monitor (bool state) } m_monitoring = state; if (!state) cancelPendingFt8Decode ("monitoring stopped"); + if (leavingDiskData) updateDecodeControls (); check_button_color(); } @@ -4127,6 +4188,50 @@ bool MainWindow::eventFilter (QObject * object, QEvent * event) } auto const key_event = static_cast<QKeyEvent *> (event); + if (object == ui->Tx_Message && !key_event->isAutoRepeat () + && key_event->key () == Qt::Key_K + && key_event->modifiers () == (Qt::ControlModifier | Qt::ShiftModifier)) + { + clearJttyLiveEntry (); + return true; + } + if (object == ui->Tx_Message && !key_event->isAutoRepeat () + && key_event->key () == Qt::Key_K + && key_event->modifiers () == Qt::ControlModifier) + { + commitJttyLiveEntry (); + return true; + } + // Alt+J: start/continue the live session (pairs with Alt+K to end it, Alt+H/Esc to stop immediately). + if (object == ui->Tx_Message && !key_event->isAutoRepeat () + && key_event->key () == Qt::Key_J + && key_event->modifiers () == Qt::AltModifier) + { + startJttyLiveStream (); + return true; + } + if (object == ui->Tx_Message && !key_event->isAutoRepeat () + && key_event->key () == Qt::Key_K + && key_event->modifiers () == Qt::AltModifier) + { + insertJttyChatSignoff (); + return true; + } + if (object == ui->Tx_Message && !key_event->isAutoRepeat () + && key_event->key () == Qt::Key_H + && key_event->modifiers () == Qt::ControlModifier) + { + insertJttyChatOpener (); + return true; + } + // An undo reaching into locked text can't be fixed by guardJttyLiveEntryLock's own undo() (wrong direction), so block the shortcuts outright while anything is locked. + if (object == ui->Tx_Message && !key_event->isAutoRepeat () + && m_jttyLiveEntryCommitted > 0 + && (key_event->matches (QKeySequence::Undo) + || key_event->matches (QKeySequence::Redo))) + { + return true; + } auto const handled = switchMainWindowTab (key_event) || switchTxNextMessage (key_event); tx_watchdog (false); if (handled) return true; @@ -4209,10 +4314,17 @@ void MainWindow::createStatusBar() //createStatusBar last_tx_label.setFrameStyle (QFrame::Panel | QFrame::Sunken); statusBar()->addWidget (&last_tx_label); - if (m_config.PWR_and_SWR()) statusBar ()->addPermanentWidget (&band_hopping_label); band_hopping_label.setAlignment (Qt::AlignHCenter); band_hopping_label.setMinimumSize (QSize {80, 18}); band_hopping_label.setFrameStyle (QFrame::Panel | QFrame::Sunken); + statusBar ()->addWidget (&band_hopping_label); + band_hopping_label.setVisible (m_mode == "WSPR"); + + swr_label.setAlignment (Qt::AlignHCenter); + swr_label.setMinimumSize (QSize {80, 18}); + swr_label.setFrameStyle (QFrame::Panel | QFrame::Sunken); + statusBar ()->addPermanentWidget (&swr_label); + swr_label.setVisible (m_config.PWR_and_SWR () && m_mode != "Echo"); statusBar()->addPermanentWidget(&progressBar); progressBar.setMinimumSize (QSize {150, 18}); @@ -4228,7 +4340,8 @@ void MainWindow::createStatusBar() //createStatusBar 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")); + band_hopping_label.setAccessibleName (tr ("WSPR band-hopping period")); + swr_label.setAccessibleName (tr ("SWR status")); progressBar.setAccessibleName (tr ("Decode progress")); progressBar.setAccessibleDescription (tr ("Progress for the current decode operation.")); watchdog_label.setAccessibleName (tr ("Transmit watchdog")); @@ -4341,18 +4454,11 @@ void MainWindow::setup_status_bar (bool vhf) } keep_last_tx_label = true; last_tx_label.setText (QString {}); - if (m_mode.contains (QRegularExpression {R"(^(Echo))"})) { - if (band_hopping_label.isVisible ()) statusBar ()->removeWidget (&band_hopping_label); - } else if (m_mode=="WSPR") { + if (m_mode == "WSPR") { mode_label.setStyleSheet ("QLabel{color: #000000; background-color: #ff66ff}"); - if (!band_hopping_label.isVisible ()) { - statusBar ()->addWidget (&band_hopping_label); - band_hopping_label.show (); - band_hopping_label.setMinimumSize (QSize {80, 18}); - } - } else { - if (!m_config.PWR_and_SWR () && band_hopping_label.isVisible ()) statusBar ()->removeWidget (&band_hopping_label); } + band_hopping_label.setVisible (m_mode == "WSPR"); + updateRigMeters (m_rigState); } @@ -4368,6 +4474,10 @@ void MainWindow::paintEvent (QPaintEvent * event) void MainWindow::closeEvent(QCloseEvent * e) { + if (jttyDrainInProgress()) { closeAfterJttyDrain(); e->ignore(); return; } + if (m_closing) { e->accept(); return; } + m_closing = true; + drainJttyReceive(); auto const active_run = PerformanceTrace::current_run (); if (active_run == m_startup_trace_run) { @@ -4412,7 +4522,7 @@ void MainWindow::closeEvent(QCloseEvent * e) m_shortcuts.reset (); m_mouseCmnds.reset (); m_colorHighlighting.reset (); - if(m_mode!="MSK144" and m_mode!="FT8") killWaveFile(); + if(m_mode!="MSK144" and m_mode!="FT8" and m_mode!="JTTY") killWaveFile(); float sw=0.0; int nw=400; int nh=100; @@ -4420,12 +4530,7 @@ void MainWindow::closeEvent(QCloseEvent * e) plotsave_(&sw,&nw,&nh,&irow); { 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); - } + m_decoderSession.shutdown (); if (proc_jt9.state() != QProcess::NotRunning) { if (!proc_jt9.waitForFinished(5000)) { proc_jt9.terminate(); @@ -4437,7 +4542,7 @@ void MainWindow::closeEvent(QCloseEvent * e) } proc_jt9.close(); } - mem_jt9->detach(); + m_decoderSession.detach (); Q_EMIT finished (); QMainWindow::closeEvent (e); close.finish (); @@ -4447,7 +4552,7 @@ void MainWindow::closeEvent(QCloseEvent * e) void MainWindow::on_actionRelease_Notes_triggered () { - QDesktopServices::openUrl (QUrl {"https://wsjt.sourceforge.io/Release_Notes.txt"}); + QDesktopServices::openUrl (QUrl {"https://wsjtx.github.io/wsjtx/Release_Notes.txt"}); } void MainWindow::on_actionFT8_DXpedition_Mode_User_Guide_triggered() @@ -4861,6 +4966,7 @@ void MainWindow::on_actionOpen_triggered() //Open File void MainWindow::read_wav_file (QString const& fname) { + if (jttyDrainInProgress()) return; if (m_wav_load_coordinator.isLoading ()) return; if (m_mode=="FT8" && (m_multithreadFT8 or m_operatingFrequency.rx ()>45000000)) { @@ -4920,6 +5026,7 @@ void MainWindow::read_wav_file (QString const& fname) void MainWindow::wav_file_loaded () { + if (m_discardJttyWavLoad || jttyDrainInProgress()) { m_discardJttyWavLoad = false; return; } if (!m_valid) return; auto const result=m_wav_load_coordinator.result (); @@ -4940,7 +5047,17 @@ void MainWindow::wav_file_loaded () dec_data.params.newdat=0; } } + m_dataAvailable = result->valid && result->frames > 0; + if (result->valid) { + beginDecoderInput (); + // Opening another file supersedes retained audio even if monitoring resumes before decoding. + if (!decoderBusy ()) m_decoderSession.abort (); + } m_fileDateTime=result->fileDateTime; + if (m_mode == "JTTY") { + if (result->firstSampleUtc.isValid()) m_UTCdiskDateTime = result->firstSampleUtc; + beginJttyDisk(); + } diskDat (); if (!m_valid) return; } @@ -5005,6 +5122,16 @@ void MainWindow::diskDat() //diskDat() float db=m_config.degrade(); float bw=m_config.RxBandwidth(); if(db > 0.0) degrade_snr_(dec_data.d2,&dec_data.params.kin,&db,&bw); + if (m_mode == "JTTY") { + for (int first = 0; first < dec_data.params.kin; first += kstep) { + dataSink(std::min(first + kstep, dec_data.params.kin)); + qApp->processEvents(QEventLoop::ExcludeUserInputEvents); + if (!m_valid || m_mode != "JTTY" || !m_diskData || !jttyDiskActive()) { finishJttyDisk(); return; } + } + finishJttyDisk(); + finishDecodeUi(); + return; + } for(int n=1; n<=m_hsymStop; n++) { // Do the waterfall spectra k=n*kstep; if(k > dec_data.params.kin) break; @@ -5049,6 +5176,7 @@ void MainWindow::on_actionNone_triggered() //Save None m_saveDecoded=false; m_saveAll=false; ui->actionNone->setChecked(true); + updateJttySavePolicy(); } void MainWindow::on_actionSave_decoded_triggered() @@ -5056,6 +5184,7 @@ void MainWindow::on_actionSave_decoded_triggered() m_saveDecoded=true; m_saveAll=false; ui->actionSave_decoded->setChecked(true); + updateJttySavePolicy(); } void MainWindow::on_actionSave_all_triggered() //Save All @@ -5063,6 +5192,7 @@ void MainWindow::on_actionSave_all_triggered() //Save All m_saveDecoded=false; m_saveAll=true; ui->actionSave_all->setChecked(true); + updateJttySavePolicy(); } void MainWindow::on_actionKeyboard_shortcuts_triggered() @@ -5148,7 +5278,33 @@ void MainWindow::decode (Ft8MtdDecodeCoordinator::Stage ft8Stage, showStatusMessage (tr ("Decoder is starting; decode request skipped.")); return; } - if (usesJt9Process () && !dec_data.params.newdat && !m_jt9PayloadValid) + if (!m_dataAvailable || m_TRperiod == 0.0) + { + ui->DecodeButton->setChecked (false); + return; + } + if (usesJt9Process () && m_diskData + && m_decoderInput.inputId () != m_decoderSession.completedSnapshot ().metadata.input_id) + { + dec_data.params.newdat = true; + dec_data.params.nagain = false; + } + if (m_mode == "FST4W" && !m_diskData && !dec_data.params.newdat) + { + ui->DecodeButton->setChecked (false); + showStatusMessage (tr ("FST4W manual decoding is available only for WAV files.")); + return; + } + int const retainedMode = m_mode == "Q65" ? 66 : m_mode == "FST4" ? 240 + : m_mode == "FST4W" ? 241 : 0; + if (retainedMode && !dec_data.params.newdat + && !m_decoderSession.canReuseSamples (retainedMode, int (m_TRperiod))) + { + ui->DecodeButton->setChecked (false); + showStatusMessage (tr ("No completed %1 reception is available to decode again.").arg (m_mode)); + return; + } + if (usesJt9Process () && !dec_data.params.newdat && !m_decoderSession.samples ()) { dec_data.params.newdat = true; dec_data.params.nagain = false; @@ -5167,9 +5323,9 @@ void MainWindow::decode (Ft8MtdDecodeCoordinator::Stage ft8Stage, } else { dec_data.params.yymmdd=-1; } - if(!m_dataAvailable or m_TRperiod==0.0) return; ui->DecodeButton->setChecked (true); - if(!dec_data.params.nagain && m_diskData && m_TRperiod >= 60.) { + if(!dec_data.params.nagain && m_diskData && m_TRperiod >= 60. && m_mode != "Q65" + && m_mode != "FST4" && m_mode != "FST4W") { dec_data.params.nutc=dec_data.params.nutc/100; } if(dec_data.params.nagain==0 && dec_data.params.newdat==1 && (!m_diskData)) { @@ -5179,7 +5335,7 @@ void MainWindow::decode (Ft8MtdDecodeCoordinator::Stage ft8Stage, 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 (); - if (m_TRperiod < 60.) + if (m_TRperiod < 60. || m_mode == "Q65" || m_mode == "FST4" || m_mode == "FST4W") { dec_data.params.nutc = dec_data.params.nutc * 100 + t.second (); } @@ -5262,7 +5418,11 @@ void MainWindow::decode (Ft8MtdDecodeCoordinator::Stage ft8Stage, dec_data.params.nsubmode=m_nSubMode; dec_data.params.minw=0; dec_data.params.nclearave=m_nclearave; - if(m_nclearave!=0) { + if (m_mode == "JT65" && m_jt65ClearAveragesPending) dec_data.params.nclearave=1; + if (m_mode == "Q65") { + dec_data.params.nclearave = m_q65ClearAveragesPending ? 1 : 0; + } + if(dec_data.params.nclearave!=0 && m_mode != "Q65") { QFile f(m_config.temp_dir ().absoluteFilePath ("avemsg.txt")); f.remove(); } @@ -5358,7 +5518,8 @@ void MainWindow::decode (Ft8MtdDecodeCoordinator::Stage ft8Stage, dec_data.params.ntrperiod=int(m_TRperiod); dec_data.params.lwidedxcsearch=m_FT8WideDxCallSearch ? 1 : 0; } - ::memcpy(dec_data.params.datetime, m_dateTime.toLatin1()+" ", sizeof dec_data.params.datetime); + auto const dateTime = m_dateTime.toLatin1().leftJustified (sizeof dec_data.params.datetime, ' ', true); + ::memcpy(dec_data.params.datetime, dateTime.constData (), sizeof dec_data.params.datetime); ::memcpy(dec_data.params.mycall, (m_config.my_callsign()+" ").toLatin1(),12); ::memcpy(dec_data.params.mybcall, (Radio::base_callsign(m_config.my_callsign())+" ").toLatin1(),12); @@ -5428,6 +5589,11 @@ void MainWindow::decode (Ft8MtdDecodeCoordinator::Stage ft8Stage, auto const publishResult = publishDecodeRequest ( decoderParams.newdat, ft8Stage, ft8Period); + if (DecodePublishResult::Published == publishResult && m_mode == "JT65") + m_jt65ClearAveragesPending = false; + if (DecodePublishResult::Published == publishResult && m_mode == "Q65") { + m_q65ClearAveragesPending = false; + } if (DecodePublishResult::Published == publishResult && scheduledFt8) { if (m_ft8MtdDecodeCoordinator.published (ft8Stage, ft8Period)) @@ -5462,6 +5628,26 @@ void MainWindow::decode (Ft8MtdDecodeCoordinator::Stage ft8Stage, } #if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) +bool MainWindow::startWavDecodeTest (QString const& path) +{ + auto const fixtureMode = ((m_mode == QStringLiteral ("JT9") + || m_mode == QStringLiteral ("JT65") + || m_mode == QStringLiteral ("Q65")) && m_TRperiod == 60.0) + || (m_mode == QStringLiteral ("FST4") && m_TRperiod == 15.0) + || (m_mode == QStringLiteral ("FST4W") && m_TRperiod == 120.0); + if (!m_automated_test || !m_config.is_dummy_rig () + || !fixtureMode || m_nSubMode != 0 || m_bFast9 || m_bFastMode + || decoderBusy () || !decoderBackendRunning () + || !ui->actionOpen->isEnabled () || m_wav_load_coordinator.isLoading ()) + return false; + monitor (false); + m_path = path; + m_diskData = true; + on_stopButton_clicked (); + read_wav_file (path); + return true; +} + bool MainWindow::configureLiveAudioTestDecodeRange () { // FT8's 1500/2048 Hz bins make 956 pixels at 4 bins/pixel span 200-3000 Hz. @@ -5584,20 +5770,7 @@ MainWindow::startLiveAudioTestFt8Transmit (qint64 targetPeriodStartMs) 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); - } - } + auto const ipc = m_decoderSession.diagnostics (); return QString {"degraded=%1 pending_final=%2 backoff_periods=%3 " "next_probe_period=%4 owner=%5 process_phase=%6 " @@ -5611,9 +5784,9 @@ QString MainWindow::liveAudioTestFt8BackpressureDiagnostics () const .arg (static_cast<int> (m_decodeOwner)) .arg (static_cast<int> (m_jt9ProcessPhase)) .arg (m_activeJt9Decode.generation) - .arg (ipcState) - .arg (ipcGeneration) - .arg (ipcProgress) + .arg (ipc.state) + .arg (ipc.generation) + .arg (ipc.progress) .arg (decoderDiagnosticElapsedMs ()) .arg (decoderDiagnosticIdleMs ()); } @@ -5625,7 +5798,6 @@ void::MainWindow::fast_decode_done() float t,tmax=-99.0; dec_data.params.nagain=false; dec_data.params.ndiskdat=false; - 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; @@ -5671,8 +5843,10 @@ void MainWindow::startDecoderProcess () : Jt9ProcessPhase::InitialStarting; m_activeJt9Decode = {}; m_decoderOutputFramer.reset (); + m_decoderSession.beginStartup (); QStringList jt9Args { - "-s", QApplication::applicationName (), // shared memory key, includes rig + "-s", m_decoderSession.name (), + "--ipc-lock", m_decoderSession.workerLockPath (), "-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 @@ -5693,27 +5867,36 @@ void MainWindow::startDecoderProcess () 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); + m_decoderStartTimer.start (5000); + updateDecodeControls (); +} + +void MainWindow::failDecoderStartup (QString const& reason) +{ + if (m_closing || Jt9ProcessPhase::Failed == m_jt9ProcessPhase) return; + m_decoderStartTimer.stop (); + m_jt9ProcessPhase = Jt9ProcessPhase::Failed; + m_decoderSession.beginStartup (); + m_valid = false; updateDecodeControls (); + qCritical () << "Decoder startup failed:" << reason; + Q_EMIT decoderBackendFailed (reason); + QTimer::singleShot (0, this, SLOT (close ())); + if (!m_automated_test) + MessageBox::critical_message (this, tr ("Decoder Error"), reason); } 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; + return m_decoderSession.reset (); } DecodeOperatingContext MainWindow::currentDecodeOperatingContext () const { - auto const periodFrequency = m_freqNominalPeriod ? m_freqNominalPeriod - : m_operatingFrequency.rx (); - auto const periodBand = m_currentBandPeriod.isEmpty () + // WAV input is independent of the live period retained across a dial change. + auto const periodFrequency = !m_diskData && m_freqNominalPeriod ? m_freqNominalPeriod + : m_operatingFrequency.rx (); + auto const periodBand = m_diskData || m_currentBandPeriod.isEmpty () ? m_config.bands ()->find (periodFrequency) : m_currentBandPeriod; DecodeOperatingContext context; context.mode = m_mode; @@ -5721,6 +5904,8 @@ DecodeOperatingContext MainWindow::currentDecodeOperatingContext () const context.periodFrequency = periodFrequency; context.band = periodBand; context.sequenceStart = m_dateTimeSeqStart; + context.inputId = m_decoderInput.inputId (); + context.analysisId = m_decoderInput.analysisId (); context.trPeriod = m_TRperiod; context.submode = m_nSubMode; context.diskData = m_diskData; @@ -5770,6 +5955,11 @@ qint64 MainWindow::currentFt8DecodePeriod () const return QDateTime::currentMSecsSinceEpoch () / periodMs; } +void MainWindow::beginDecoderInput () +{ + m_decoderInput.beginInput (); +} + bool MainWindow::usesFt8MtdFinal () const { auto const standardFinalRequired = @@ -5788,19 +5978,23 @@ int MainWindow::configuredFt8MtdEarlyStageCount () const } std::unique_ptr<Ft8MtdDecodeCoordinator::PendingMtdDecode> -MainWindow::capturePendingFt8MtdDecode (qint64 period) const +MainWindow::capturePendingFt8MtdDecode (qint64 period) { auto pending = std::make_unique<Ft8MtdDecodeCoordinator::PendingMtdDecode> (); pending->period = period; - pending->context = currentDecodeOperatingContext (); { QMutexLocker payloadLock {&dec_data_mutex ()}; pending->payload.params = dec_data.params; + pending->payload.metadata = m_decoderInput.nextMetadata (dec_data.params); + pending->payload.metadata.valid_samples = std::min ( + pending->payload.metadata.valid_samples, + static_cast<qint32> (DecoderIpc::Ft8SampleCount)); 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 ()); } + pending->context = currentDecodeOperatingContext (); return pending; } @@ -5855,9 +6049,7 @@ MainWindow::DecodePublishResult MainWindow::publishDecodeRequest ( { return DecodePublishResult::Unavailable; } - if ((!copySamples && !m_jt9PayloadValid) - || !DecoderIpc::hasUsableSize (mem_jt9->size ()) - || !mem_jt9->data ()) + if (!copySamples && !m_decoderSession.samples ()) { return DecodePublishResult::Failed; } @@ -5868,24 +6060,25 @@ MainWindow::DecodePublishResult MainWindow::publishDecodeRequest ( 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}; + DecoderIpc::Submission submitted; { 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) + auto inputs = m_decoderInput; + auto const request = m_decoderSession.prepareRequest (dec_data, copySamples, inputs); + submitted = m_decoderSession.submit (request); + if (submitted) m_decoderInput = inputs; + m_activeJt9Decode.context.inputId = request.metadata ().input_id; + m_activeJt9Decode.context.analysisId = request.metadata ().analysis_id; + } + if (!submitted) { logDecoderAbnormalClear ("decode publication failed"); m_activeJt9Decode = {}; @@ -5893,7 +6086,7 @@ MainWindow::DecodePublishResult MainWindow::publishDecodeRequest ( return DecodePublishResult::Failed; } - m_nextDecoderGeneration = generation; + m_activeJt9Decode.generation = submitted.generation.value (); return DecodePublishResult::Published; } @@ -5913,27 +6106,18 @@ MainWindow::DecodePublishResult MainWindow::publishPendingFt8Decode () { 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)) + auto const submitted = m_decoderSession.submit (DecoderIpc::Request::ft8 (pending.payload)); + if (!submitted) { logDecoderAbnormalClear ("pending FT8 decode publication failed"); m_activeJt9Decode = {}; @@ -5941,11 +6125,11 @@ MainWindow::DecodePublishResult MainWindow::publishPendingFt8Decode () return PendingPublishResult::Failed; } - m_nextDecoderGeneration = generation; + m_activeJt9Decode.generation = submitted.generation.value (); emitFt8DecoderInvocation (pending.payload.params); qInfo () << "Published pending FT8 final decode" << "period:" << pending.period - << "generation:" << generation; + << "generation:" << submitted.generation.value (); return PendingPublishResult::Published; }); @@ -5984,12 +6168,7 @@ void MainWindow::requestDecoderRestart (QString const& reason) 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); - } + m_decoderSession.shutdown (); if (QProcess::NotRunning == proc_jt9.state ()) { @@ -6064,7 +6243,7 @@ void MainWindow::updateDecodeControls () auto const enabled = !decoderBusy () && backendReady && !m_wav_load_coordinator.isLoading (); ui->DecodeButton->setEnabled (enabled && "WSPR" != m_mode - && "FST4W" != m_mode && "Echo" != m_mode); + && ("FST4W" != m_mode || m_diskData) && "Echo" != m_mode); update_wav_file_actions (); statusUpdate (); } @@ -6075,7 +6254,7 @@ void MainWindow::abortJt9Transaction () m_ft8MtdDecodeCoordinator.publicationFailed ( m_activeJt9Decode.ft8Stage, m_activeJt9Decode.ft8Period); m_activeJt9Decode = {}; - m_jt9PayloadValid = false; + m_decoderSession.abort (); dec_data.params.nagain = false; dec_data.params.ndiskdat = false; m_nclearave = 0; @@ -6176,19 +6355,13 @@ void MainWindow::logDecoderProgress() { if(DecodeOwner::Jt9 != m_decodeOwner || !m_decoderDiagActive) return; - if (DecoderIpc::hasUsableSize (mem_jt9->size ()) && mem_jt9->data ()) + auto const ipc = m_decoderSession.diagnostics (); + if (m_decoderSession.accepts (ipc.generation)) { - 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)) + if (ipc.progress != m_decoderDiagProgressCount) { - auto const progress = DecoderIpc::progress (*shared); - if (progress != m_decoderDiagProgressCount) - { - m_decoderDiagProgressCount = progress; - markDecoderProgress (); - } + m_decoderDiagProgressCount = ipc.progress; + markDecoderProgress (); } } @@ -6330,6 +6503,12 @@ void MainWindow::recoverDecoderAtBoundary (QString const& reason, bool manual) void MainWindow::finishDecodeUi () { + if (m_mode == "JTTY") { + ui->DecodeButton->setChecked(false); + if (m_diskData) m_startAnother = m_loopall; + update_wav_file_actions(); + return; + } if(m_mode=="Q65") m_wideGraph->drawRed(0,0); if ("FST4W" == m_mode) { @@ -6395,22 +6574,23 @@ void MainWindow::refreshPileupList() { // Update the ActiveStations display for Q65 pileup situation... int nlist=0; - char list[2000]; - char line[37]; + int capacity=MaxQ65PileupCallers; + char list[MaxQ65PileupCallers * Q65_CALLER_ROW_WIDTH]; + char line[Q65_CALLER_ROW_WIDTH]; 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); + get_q3list_(const_cast<char *> (fname.toLatin1().constData()), &m_diskData, &capacity, &nlist, + &list[0], (FCL)fname.length(), (FCL)Q65_CALLER_ROW_WIDTH); QString t=""; QString t0=""; std::fill(m_callers.begin(), m_callers.end(), QString {}); for(int i=0; i<qMin(nlist, MaxQ65PileupCallers); i++) { - memcpy(line,&list[37*i],37); + memcpy(line,&list[Q65_CALLER_ROW_WIDTH*i],sizeof line); // 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] = '#'; + line[Q65_CALLER_ROW_WIDTH - 1] = '#'; } t0=QString::fromLatin1(line, sizeof line)+"\n"; @@ -6501,17 +6681,19 @@ 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 < MaxQ65PileupCallers) { + if(n<0) return; + QStringList w; + if(m_mode=="Q65" and m_specOp==SpecOp::Q65_PILEUP) { + if(n>=MaxQ65PileupCallers) return; // 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. - rm_q3list_(const_cast<char *> (m_deCall.toLatin1().constData()), m_deCall.size()); + auto const fname = QDir::toNativeSeparators(m_config.writeable_data_dir().absoluteFilePath("tsil.3q")).toLatin1(); + rm_q3list_(const_cast<char *>(fname.constData()), + const_cast<char *> (m_deCall.toLatin1().constData()), fname.size(), m_deCall.size()); refreshPileupList(); return; } @@ -6526,6 +6708,9 @@ void MainWindow::callSandP2(int n) if(m_transmitting) m_restart=true; return; } + if(n>=int(m_ready2call.size())) return; + if(m_mode!="Q65" and m_ready2call[n]=="") return; + w=m_ready2call[n].split(' ', SkipEmptyParts); bool frequency_changed = false; if(m_mode=="Q65") { @@ -6656,11 +6841,54 @@ void MainWindow::activeWorked(QString call, QString band) bool MainWindow::handleDecoderOutputEvent (DecoderOutputFramer::Event const& event, bool& decodeCompleted) { + if (m_closing || Jt9ProcessPhase::Failed == m_jt9ProcessPhase) return true; + auto const starting = Jt9ProcessPhase::InitialStarting == m_jt9ProcessPhase + || Jt9ProcessPhase::ReplacementStarting == m_jt9ProcessPhase; + if (DecoderOutputFramer::EventType::Ready == event.type) + { + if (!starting || DecoderIpc::Status::Ok != m_decoderSession.acceptReady (event.protocolVersion)) + { + failDecoderStartup (tr ("The decoder reported an incompatible or unexpected startup handshake (version %1).") + .arg (event.protocolVersion)); + return true; + } + m_decoderStartTimer.stop (); + m_decoderCompletedSinceStart = false; + m_jt9ProcessPhase = Jt9ProcessPhase::Ready; + updateDecodeControls (); + Q_EMIT decoderBackendStarted (); + QTimer::singleShot (0, this, [this] { + auto const pendingResult = publishPendingFt8Decode (); + if (DecodePublishResult::Failed == pendingResult) + requestDecoderRestart ("pending FT8 decode publication failed after restart"); + }); + return true; + } + if (DecoderOutputFramer::EventType::Error == event.type) + { + failDecoderStartup (tr ("The decoder rejected the shared-memory contract: %1.") + .arg (QString::fromLatin1 (event.errorStatus))); + return true; + } + if ((DecoderOutputFramer::EventType::Malformed == event.type + && (event.rawLine.startsWith ("<DecoderReady") + || event.rawLine.startsWith ("<DecoderError"))) + || (starting && DecoderOutputFramer::EventType::Malformed != event.type)) + { + failDecoderStartup (tr ("The decoder reported a malformed or out-of-order startup handshake.")); + return true; + } + if (DecoderOutputFramer::EventType::Rejected == event.type) + { + if (DecodeOwner::Jt9 == m_decodeOwner && m_decoderSession.accepts (event.generation)) + qCritical () << "Decoder request rejected" + << "generation:" << event.generation << event.rawLine.trimmed (); + return true; + } if (DecoderOutputFramer::EventType::Record == event.type) { if (DecodeOwner::Jt9 != m_decodeOwner - || !m_activeJt9Decode.generation - || event.generation != m_activeJt9Decode.generation) + || !m_decoderSession.accepts (event.generation)) { return true; } @@ -6699,8 +6927,7 @@ bool MainWindow::handleDecoderOutputEvent (DecoderOutputFramer::Event const& eve { auto const authoritative = Jt9ProcessPhase::Ready == m_jt9ProcessPhase && DecodeOwner::Jt9 == m_decodeOwner - && m_activeJt9Decode.generation - && event.generation == m_activeJt9Decode.generation; + && m_decoderSession.accepts (event.generation); if (!authoritative) { qWarning () << "Quarantining stale decoder output" @@ -6721,8 +6948,7 @@ bool MainWindow::handleDecoderOutputEvent (DecoderOutputFramer::Event const& eve auto const completion = event.completion; auto const authoritative = DecodeOwner::Jt9 == m_decodeOwner - && m_activeJt9Decode.generation - && event.generation == m_activeJt9Decode.generation; + && m_decoderSession.accepts (event.generation); if (!authoritative) { qWarning () << "Ignoring stale decoder completion" @@ -6738,24 +6964,12 @@ bool MainWindow::handleDecoderOutputEvent (DecoderOutputFramer::Event const& eve << "generation:" << event.generation; } - 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)) - { - state = DecoderIpc::state (*shared); - consumed = DecoderIpc::consume (*shared, completion.generation); - } - } - if (!consumed) + auto const ipc = m_decoderSession.diagnostics (); + if (DecoderIpc::Status::Ok != m_decoderSession.complete (completion)) { qWarning () << "Unable to consume matching decoder completion" << "generation:" << completion.generation - << "state:" << state; + << "state:" << ipc.state; requestDecoderRestart ("matching decoder completion could not be consumed"); return true; } @@ -7225,7 +7439,6 @@ void MainWindow::readFromStdout() //readFromStdout 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); @@ -7307,15 +7520,12 @@ void MainWindow::rx_frequency_activity_cleared () { m_QSOText.clear(); set_dateTimeQSO(-1); // G4WJS: why do we do this? - // 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() void MainWindow::guiUpdate() { + if (jttyDrainInProgress()) return; static char message[38]; static char msgsent[38]; double txDuration; @@ -8070,7 +8280,7 @@ void MainWindow::guiUpdate() } } - progressBar.setVisible(true); + progressBar.setVisible(m_mode != "JTTY"); // turn the progressbar red during transmission if(m_config.progressBar_red()) { if(m_transmitting) { @@ -8121,7 +8331,7 @@ void MainWindow::guiUpdate() if(m_transmitting or m_monitoring) n=int(m_s6)%3; progressBar.setValue(n); } - if(m_mode!="Echo") { + if(m_mode!="Echo" && m_mode!="JTTY") { if(m_monitoring or m_transmitting) { progressBar.setMaximum(m_TRperiod); int isec=int(fmod(tsec,m_TRperiod)); @@ -8166,6 +8376,12 @@ void MainWindow::guiUpdate() t=m_fm1.trimmed(); } if(m_mode=="FT4" or m_mode == "JTTY") t="Tx: "+ m_currentMessage; + if (m_mode == "JTTY") { + tx_status_label.setToolTip (t); + tx_status_label.setAccessibleDescription (t); + t = tx_status_label.fontMetrics ().elidedText ( + t, Qt::ElideRight, qMax (100, statusBar ()->width () / 4)); + } tx_status_label.setText(t.trimmed()); } } @@ -8211,7 +8427,7 @@ void MainWindow::guiUpdate() transmitDisplay(false); } else if (!m_diskData && !m_tx_watchdog) { tx_status_label.setStyleSheet(""); - tx_status_label.setText(""); + tx_status_label.setText(m_mode == "JTTY" ? tr("Stopped") : QString{}); } if (m_tx_inhibited && !m_tx_watchdog && !m_generated_message_error) { tx_status_label.setStyleSheet ( @@ -8267,13 +8483,15 @@ void MainWindow::useNextCall() bool MainWindow::startTx2() { + if (jttyDrainInProgress()) return false; + bool const jtty = m_jttyTxLifecycle.active () && !m_tune; if (m_mode == "JTTY" && !m_tune - && (!m_jttyTxActive || jttyTxCommittedSamples () <= 0)) { + && (!jtty || jttyTxCommittedSamples () <= 0)) { return false; } bool modulator_active; - bool const tci_active = (m_mode == "JTTY" && m_jttyTxActive) - ? m_jttyTxUsesTciAudio + bool const tci_active = jtty + ? m_jttyTxLifecycle.backend () == JttyTxLifecycle::Backend::Tci : m_tci_audio; if (tci_active) modulator_active=m_tci_mod_active; else modulator_active=m_modulator->isActive (); @@ -8407,21 +8625,48 @@ void MainWindow::noteTxStopReason (TxEvidence::TxStopReason reason) void MainWindow::noteTxModeChange (QString const& mode) { + if (m_mode == "JTTY" && mode != m_mode) { + bool const resume = m_monitoring; + // Drain the old stream before a timed mode can reuse reference-filter history. + drainJttyReceive(); + if (resume) QTimer::singleShot(0, this, [this, mode] { + if (!m_closing && m_mode == mode) monitor(true); + }); + } 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)) + if (mode != m_mode && (m_transmitting || g_iptt == 1 + || m_jttyTxLifecycle.active () + || !m_jttyTransmitQueue.empty ())) { noteTxStopReason (TxEvidence::TxStopReason::ModeChange); + if (m_jttyTxLifecycle.active () || !m_jttyTransmitQueue.empty ()) stopTx (); + } +} + +void MainWindow::updateModeControlLock () +{ + bool enabled = !m_modeLocked && !m_transmitting + && !m_jttyTxLifecycle.active () && m_jttyTransmitQueue.empty (); +#ifdef WIN32 + enabled = enabled && !m_mmttyHandoff.active (); +#endif + ui->menuMode->setEnabled (enabled); + for (auto * button : {ui->houndButton, ui->ft8Button, ui->ft4Button, + ui->msk144Button, ui->q65Button, ui->jt65Button, + ui->echoButton}) + { + button->setEnabled (enabled); } } int MainWindow::txStopTailMs (bool tciAudio) const { return TxEvidence::TxPlaybackDiagnostics::decisionFor ( - m_pendingTxStopReason, tciAudio || m_mode == "JTTY").tail_ms; + m_pendingTxStopReason, tciAudio || m_jttyTxLifecycle.active ()).tail_ms; } void MainWindow::stopTxEvidence (int tailMs) @@ -8465,24 +8710,50 @@ void MainWindow::captureJttyTxEvidenceTotals (qint64 servedSamples, void MainWindow::stopTx() { - bool const tciAudio = (m_mode == "JTTY" && m_transmitting) - ? m_jttyTxUsesTciAudio - : m_tci_audio; + auto const jttyStop = m_jttyTxLifecycle.beginStop (); + bool const jttyTx = bool (jttyStop); +#ifdef WIN32 + bool const abnormalJttyStop = jttyTx + && m_pendingTxStopReason != TxEvidence::TxStopReason::NormalEnd; +#endif + bool const tciAudio = jttyTx + ? jttyStop->backend == JttyTxLifecycle::Backend::Tci : m_tci_audio; int const stopTxDelayMs = txStopTailMs (tciAudio); - if (m_mode == "JTTY" && m_jttyTxActive) { + if (jttyTx) { + m_delayedJttyStopContext = *jttyStop; interruptJttyTx(); + } else if (!m_jttyTransmitQueue.empty ()) { + auto const cancelled = m_jttyTransmitQueue.cancel (); + for (auto requestId : cancelled) { + Q_EMIT jttyTextRejected (requestId, JttyTxRejectReason::Aborted); + } + m_jttyQueueNotice = tr ("JTTY transmission cancelled; some text may already have transmitted."); + updateJttySendButton (); + if (!m_transmitting && g_iptt != 1) return; } if (tciAudio) Q_EMIT m_config.transceiver_modulator_stop(); else Q_EMIT endTransmitMessage (); - if (m_mode == "JTTY" && !tciAudio) { + if (jttyTx && !tciAudio) { Q_EMIT endJttyStream (); } + if (jttyTx) { + m_jttyTxWatchdog.stop (); + m_jttyEnqueueWatchdog.stop (); + m_jttyTxLifecycle.markBackendStopRouted (*jttyStop); + m_jttyTxLifecycle.reset (); + m_pendingJttyMessages.clear (); + } m_btxok = false; m_transmitting = false; g_iptt=0; + updateModeControlLock (); if (!m_tx_watchdog && !m_generated_message_error) { tx_status_label.setStyleSheet(""); tx_status_label.setText(""); + if (!m_tx_inhibited && m_mode == "JTTY") { + tx_status_label.setToolTip ({}); + tx_status_label.setAccessibleDescription ({}); + } } if (tciAudio) { ptt0Timer.start(stopTxDelayMs); @@ -8492,6 +8763,11 @@ void MainWindow::stopTx() statusUpdate (); } stopTxEvidence (stopTxDelayMs); +#ifdef WIN32 + if (abnormalJttyStop && !m_preserveMmttyOutputDuringStop) { + finalizeMmttyExternalAbort (); + } +#endif } void MainWindow::stopTx2() @@ -8500,7 +8776,11 @@ void MainWindow::stopTx2() // 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; + bool const delayedJtty = m_delayedJttyStopContext.backend + != JttyTxLifecycle::Backend::None; + bool const tciAudio = delayedJtty + ? m_delayedJttyStopContext.backend == JttyTxLifecycle::Backend::Tci + : m_tci_audio; if (tciAudio) { Q_EMIT m_config.transceiver_ptt (false); //Lower PTT monitor (true); @@ -8520,7 +8800,18 @@ void MainWindow::stopTx2() processBeaconActions (m_beaconTxController.tuneCompleted (beaconTunePlanId)); } keep_last_tx_label = true; - last_tx_label.setText(tr ("Last Tx: %1").arg (m_currentMessage.trimmed())); + QString const lastTx = tr ("Last Tx: %1").arg (m_currentMessage.trimmed()); + last_tx_label.setToolTip (lastTx); + last_tx_label.setAccessibleDescription (lastTx); + last_tx_label.setText (m_mode == "JTTY" + ? last_tx_label.fontMetrics ().elidedText ( + lastTx, Qt::ElideRight, qMax (150, statusBar ()->width () / 4)) + : lastTx); +#ifdef WIN32 + resumeMmttyHandoff (); +#endif + m_delayedJttyStopContext = {}; + if (m_mode == "JTTY") feedJttyTransmitQueue (); } QString MainWindow::expandTxMacros(QString const& message) const @@ -8737,7 +9028,10 @@ void MainWindow::handleDecodeSelection( } if(m_mode=="JTTY") { m_deCall = word; - ui->dxCallEntry->setText(m_deCall); + ui->dxCallEntry->setText(m_deCall); // clears m_jttyHisCallSnr via on_dxCallEntry_textChanged + // Capture the SNR of the decode actually selected, not whichever decoded last. + m_jttyHisCallSnr = jttySnrForSelectedWord( + word, selection_origin == DecodedMessageReaction::SelectionOrigin::ManualLeftPane); return; } DecodedText message {line.trimmed().left(61).remove("TU; ")}; @@ -9232,15 +9526,7 @@ void MainWindow::abortQSO() bool MainWindow::stdCall(QString const& w) { - static QRegularExpression standard_call_re { - R"( - ^\s* # optional leading spaces - ( [A-Z]{0,2} | [A-Z][0-9] | [0-9][A-Z] ) # part 1 - ( [0-9][A-Z]{0,3} ) # part 2 - (/R | /P)? # optional suffix - \s*$ # optional trailing spaces - )", QRegularExpression::CaseInsensitiveOption | QRegularExpression::ExtendedPatternSyntaxOption}; - return standard_call_re.match (w).hasMatch (); + return Radio::is_standard_callsign(w); } bool MainWindow::is77BitMode () const @@ -10009,6 +10295,7 @@ void MainWindow::on_dxCallEntry_textChanged (QString const& call) } set_dateTimeQSO (-1); // reset the QSO start time when DXCall changes m_hisCall = call; + if (m_mode=="JTTY") m_jttyHisCallSnr = -10; // stale SNR belonged to the previous DX call if(m_QSYMessageCreatorWidget) m_QSYMessageCreatorWidget->getDxBase(QString(Radio::base_callsign(call))); if (!blocked) ui->dxGridEntry->clear(); // conditional because not always useful with highlightDXCall/DXGrid feature if (ui->DX_Call_Button->isChecked() && !(m_mode=="FT8" && SpecOp::HOUND==m_specOp)) ui->DX_Call_Button->click (); @@ -10136,7 +10423,9 @@ void MainWindow::acceptQSO (QDateTime const& QSO_date_off, QString const& call, m_score++; m_EMEworked[call]=true; if(m_specOp==SpecOp::Q65_PILEUP) { - rm_q3list_(const_cast<char *> (m_deCall.toLatin1().constData()), m_deCall.size()); + auto const fname = QDir::toNativeSeparators(m_config.writeable_data_dir().absoluteFilePath("tsil.3q")).toLatin1(); + rm_q3list_(const_cast<char *>(fname.constData()), + const_cast<char *> (m_deCall.toLatin1().constData()), fname.size(), m_deCall.size()); refreshPileupList(); } m_ActiveStationsWidget->setRate(m_score); @@ -10685,6 +10974,7 @@ void MainWindow::setDecodeHeadings(QString const& lh, QString const& rh) void MainWindow::on_actionFST4_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("FST4")); QTimer::singleShot (50, this, [=] { ui->TxFreqSpinBox->setValue(m_settings->value("TxFreq_old",1500).toInt()); @@ -10748,6 +11038,7 @@ void MainWindow::on_actionFST4_triggered() void MainWindow::on_actionFST4W_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("FST4W")); m_mode="FST4W"; if(m_specOp==SpecOp::HOUND) { @@ -10783,6 +11074,7 @@ void MainWindow::on_actionFST4W_triggered() void MainWindow::on_actionFT4_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("FT4")); if (m_mode=="MSK144") QTimer::singleShot (75, this, [=] {on_actionFT4_triggered();}); QTimer::singleShot (50, this, [=] { @@ -10836,6 +11128,7 @@ void MainWindow::on_actionFT4_triggered() void MainWindow::on_actionFT8_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("FT8")); if (m_mode=="MSK144") QTimer::singleShot (75, this, [=] {on_actionFT8_triggered();}); QTimer::singleShot (50, this, [=] { @@ -11007,6 +11300,7 @@ void MainWindow::on_actionFT8_triggered() void MainWindow::on_actionJT4_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("JT4")); QTimer::singleShot (50, this, [=] { ui->TxFreqSpinBox->setValue(m_settings->value("TxFreq_old",1500).toInt()); @@ -11075,6 +11369,7 @@ void MainWindow::on_actionJT4_triggered() void MainWindow::on_actionJT9_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("JT9")); m_mode="JT9"; if(m_specOp==SpecOp::HOUND) { @@ -11164,6 +11459,7 @@ void MainWindow::on_actionJT9_triggered() void MainWindow::on_actionJT65_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("JT65")); if (m_mode=="MSK144") QTimer::singleShot (75, this, [=] {on_actionJT65_triggered();}); QTimer::singleShot (50, this, [=] { @@ -11172,6 +11468,7 @@ void MainWindow::on_actionJT65_triggered() }); on_actionJT9_triggered(); m_mode="JT65"; + m_jt65ClearAveragesPending = true; if(m_specOp==SpecOp::HOUND) { m_config.setSpecial_None(); m_specOp=m_config.special_op_id(); @@ -11244,6 +11541,7 @@ void MainWindow::on_actionJT65_triggered() void MainWindow::on_actionQ65_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("Q65")); if (m_mode=="MSK144") QTimer::singleShot (75, this, [=] {on_actionQ65_triggered();}); QTimer::singleShot (50, this, [=] { @@ -11324,6 +11622,7 @@ void MainWindow::on_actionQ65_triggered() void MainWindow::on_actionJTTY_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("JTTY")); on_stopButton_clicked(); m_mode = "JTTY"; @@ -11340,7 +11639,7 @@ void MainWindow::on_actionJTTY_triggered() 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_TRperiod=180; // Legacy timed interfaces; JTTY receive uses sample coordinates. m_hsymStop=620; m_wideGraph->setPeriod(m_TRperiod,m_nsps); m_detector->setTRPeriod(m_TRperiod); // marshals to the audio thread @@ -11353,6 +11652,8 @@ void MainWindow::on_actionJTTY_triggered() // 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()); + m_fastGraph->hide(); + m_wideGraph->showNormal(); setDecodeHeadings("", ""); updateJttyDecodeHeadings(); setDecodeTitles(tr ("All Decodes"), tr ("QSO Frequency")); @@ -11374,6 +11675,7 @@ void MainWindow::on_actionJTTY_triggered() void MainWindow::on_actionMSK144_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } m_hsymStop=105; m_TRperiod=ui->sbTR->value(); if(SpecOp::EU_VHF < m_specOp) { @@ -11466,6 +11768,7 @@ void MainWindow::on_actionMSK144_triggered() void MainWindow::on_actionWSPR_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("WSPR")); m_mode="WSPR"; if(m_specOp==SpecOp::HOUND) { @@ -11502,6 +11805,7 @@ void MainWindow::on_actionWSPR_triggered() void MainWindow::on_actionEcho_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("Echo")); int nd=int(m_ndepth&3); on_actionJT4_triggered(); @@ -11561,6 +11865,7 @@ void MainWindow::on_actionEcho_triggered() void MainWindow::on_actionFreqCal_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("FreqCal")); on_actionJT9_triggered(); m_mode="FreqCal"; @@ -11602,6 +11907,8 @@ void MainWindow::switch_mode (Mode mode) // Sit just under the decoded-text panes, outside the per-mode // displayWidgets()/ModeUiControl mechanism -- only meaningful for JTTY. bool const jtty = m_mode=="JTTY"; + updateJttyReceivePolicy(jtty); + progressBar.setVisible(!jtty); ui->cbLowerCase->setVisible(jtty); ui->cbIncludeTime->setVisible(jtty); if (mode != Modes::MSK144) m_msk144basefreq = 0; @@ -11664,7 +11971,7 @@ void MainWindow::WSPR_config(bool b) ui->DX_controls_widget->setVisible (!b or (m_mode=="Echo")); ui->lh_decodes_title_label->setVisible(!b and ui->cbMenus->isChecked()); ui->logQSOButton->setVisible(!b); - ui->DecodeButton->setEnabled(!b); + updateDecodeControls (); bool bFST4W=(m_mode=="FST4W"); ui->sbTxPercent->setEnabled(!bFST4W or configuredRoundRobinPolicy ().kind == BeaconTx::RoundRobinPolicy::Kind::Random); @@ -12337,7 +12644,7 @@ void MainWindow::setXIT(int n, Frequency base) 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")) { + m_mode=="FT4" || m_mode == "FT8" || m_mode=="FST4" || m_mode=="JTTY")) { // Don't use XIT for VHF & up requested_xit=(n/500)*500 - 1500; } @@ -12422,6 +12729,8 @@ void MainWindow::applyOperatingFrequencyTransition (OperatingFrequency::Transiti { if (transition.before.rx != transition.after.rx) { + if (m_mode == "JTTY") updateJttyReceiveContext(); + if (m_mode == "JT65") m_jt65ClearAveragesPending = true; cancelPendingFt8Decode ("dial frequency changed"); genCQMsg (); } @@ -12444,6 +12753,75 @@ void MainWindow::applyOperatingFrequencyTransition (OperatingFrequency::Transiti displayDialFrequency (); } +void MainWindow::updateRigMeters (Transceiver::TransceiverState const& s) +{ + bool const enabled = m_config.PWR_and_SWR (); + swr_label.setVisible (enabled && m_mode != "Echo"); + + if (enabled && s.online () && (s.ptt () || m_transmitting || m_tune)) + { + auto const power = round (s.power () / 1000.); + ui->label->setText (tr ("%1 W").arg (power)); + if (power >= 100) + { + auto const point_size = m_config.text_font ().pointSizeF (); + ui->label->setMinimumWidth (2.8 * point_size + 16); + ui->outAttenuation->setMinimumWidth (2.8 * point_size + 16); + } + } + else + { + ui->label->setText (tr ("Pwr")); + } + + auto const swr = enabled && s.online () ? s.swr () : 0; + QString style; + if (swr > 200) + { + style = "QLabel{color: #ffffff; background-color: #ff0000}"; + } + else if (swr > 150) + { + style = "QLabel{color: #000000; background-color: #ffff00}"; + } + if (swr_label.styleSheet () != style) swr_label.setStyleSheet (style); + swr_label.setText (swr ? tr ("SWR: %1").arg (swr / 100., 0, 'f', swr < 1000 ? 2 : 1) + : QString {}); +} + +bool MainWindow::stopForHighSWR (Transceiver::TransceiverState const& s) +{ + if (!m_config.PWR_and_SWR () || !m_config.check_SWR () || !s.online () + || s.swr () <= 250 + || !(s.ptt () || g_iptt == 1 || m_transmitting || m_tune + || m_tx_when_ready || ptt1Timer.isActive ())) + { + return false; + } + + requestTxStop (TxEvidence::TxStopReason::Error); + return true; +} + +void MainWindow::showHighSWRWarning (unsigned swr) +{ + if (m_swrWarning) return; + + auto * warning = new MessageBox {MessageBox::Warning, + tr ("SWR > 2.5 !!!\n\n" + "Transmission was stopped\n\n" + "Check your antenna"), MessageBox::Ok, this}; + warning->setInformativeText (tr ("SWR: %1").arg (swr / 100., 0, 'f', 2)); + m_swrWarning = warning; + warning->setDefaultButton (MessageBox::Ok); + warning->setWindowModality (Qt::ApplicationModal); + connect (warning, &QDialog::finished, this, [this, warning] { + m_swrWarning.clear (); + warning->deleteLater (); + }); + warning->show (); +} + void MainWindow::handle_transceiver_update (Transceiver::TransceiverState const& s) { if (!m_startup_rig_reported) @@ -12454,59 +12832,11 @@ void MainWindow::handle_transceiver_update (Transceiver::TransceiverState const& 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) - startTxAudioAfterPttDelay (); - } - - // Display PWR and SWR - if(m_config.PWR_and_SWR()) { - if (!band_hopping_label.isVisible ()) { - statusBar ()->addPermanentWidget (&band_hopping_label); - band_hopping_label.setMinimumSize (QSize {80, 18}); - band_hopping_label.show(); - } - if (m_rigState.power() != s.power() && m_transmitting) { - ui->label->setText(QString {tr("%1 W")}.arg (round(s.power()/1000.))); - if (round(s.power()/1000.) >= 100) { - qreal pointSize = m_config.text_font().pointSizeF(); - - ui->label->setMinimumWidth (2.8*pointSize + 16); - ui->outAttenuation->setMinimumWidth (2.8*pointSize + 16); - } - } else { - ui->label->setText(tr ("Pwr")); - } - if (m_rigState.swr() != s.swr()) { - static bool s_alreadyShowingSWRAlert = false; - if (s.swr() > 0) { - if (s.swr()>150) band_hopping_label.setStyleSheet ("QLabel{color: #000000; background-color: #ffff00}"); - if (s.swr()>200) band_hopping_label.setStyleSheet ("QLabel{color: #ffffff; background-color: #ff0000}"); - if (s.swr()>250 && m_config.check_SWR()) { - if (!s_alreadyShowingSWRAlert) { // avoid recursion - on_stopTxButton_clicked(); - s_alreadyShowingSWRAlert = true; - MessageBox::warning_message (this, tr ("SWR > 2.5 !!!\n\n" - "Transmission was stopped\n\n" - "Check your antenna")); - s_alreadyShowingSWRAlert = false; - } - } - if (s.swr()<1000) { - band_hopping_label.setText(QString {"SWR: %1"}.arg (s.swr()/100.,0,'f',2)); - } else { - band_hopping_label.setText(QString {"SWR: %1"}.arg (s.swr()/100.,0,'f',1)); - } - } else { - if (!s_alreadyShowingSWRAlert) { // retain value and color if SWR was > 2.5 - band_hopping_label.setText(""); - band_hopping_label.setStyleSheet(""); - } - } + bool const high_swr = stopForHighSWR (s); + if (s.ptt () && !high_swr) + { + startTxAudioAfterPttDelay (); } - } m_rigState = s; auto const transition = m_operatingFrequency.reconcile ( @@ -12539,6 +12869,8 @@ void MainWindow::handle_transceiver_update (Transceiver::TransceiverState const& update_dynamic_property (ui->readFreq, "state", "ok"); ui->readFreq->setEnabled (false); ui->readFreq->setText (s.split () ? "S" : ""); + updateRigMeters (s); + if (high_swr) showHighSWRWarning (s.swr ()); } void MainWindow::handle_transceiver_closing (bool failed) @@ -12548,20 +12880,32 @@ void MainWindow::handle_transceiver_closing (bool failed) m_receiveConsumer.invalidate (); m_receiveQueue.clear (); } - if (m_closing || m_mode != "JTTY" || !m_jttyTxActive - || !m_jttyTxUsesTciAudio) + if (!m_jttyTxLifecycle.active () + || m_jttyTxLifecycle.backend () != JttyTxLifecycle::Backend::Tci) { return; } noteTxStopReason (failed ? TxEvidence::TxStopReason::Error : TxEvidence::TxStopReason::UserHalt); + rejectPendingJttyMessages (JttyTxRejectReason::NotAvailable); + m_jttyTxLifecycle.failAll (); + m_pendingJttyMessages.clear (); + m_jttyEnqueueWatchdog.stop (); stopTx (); +#ifdef WIN32 + finalizeMmttyExternalAbort (); +#endif } void MainWindow::handle_transceiver_failure (QString const& reason) { noteTxStopReason (TxEvidence::TxStopReason::Error); + if (m_jttyTxLifecycle.active () || !m_jttyTransmitQueue.empty ()) { + stopTx (); + m_jttyQueueNotice = tr ("The audio backend stopped: %1").arg (reason); + updateJttySendButton (); + } m_beaconTxController.setAutoEnabled (false); if (m_beaconTxController.txLifecycle () == BeaconTx::TxLifecycle::Decided || m_beaconTxController.txLifecycle () == BeaconTx::TxLifecycle::StartRequested) @@ -12583,6 +12927,9 @@ void MainWindow::handle_transceiver_failure (QString const& reason) reset_transmit_controls_after_stop (); rigFailure (reason); rigFailed = true; +#ifdef WIN32 + finalizeMmttyExternalAbort (); +#endif } void MainWindow::rigFailure (QString const& reason) @@ -12638,7 +12985,8 @@ 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; + ? m_jttyTxLifecycle.backend () == JttyTxLifecycle::Backend::Tci + : m_tci_audio; if (useTciAudio) { if (!request.tuning && rigTuneTimer.isActive ()) @@ -12665,20 +13013,23 @@ void MainWindow::dispatchTxRequest (TxEvidence::TxRequest const& request) void MainWindow::transmit (double snr) { + bool const jttyTx = m_jttyTxLifecycle.active () && !m_tune + && jttyTxCommittedSamples () > 0; qint64 const jttyCommittedSamples = jttyTxCommittedSamples (); - beginTxEvidenceGeneration (m_mode == "JTTY" && jttyCommittedSamples > 0 + beginTxEvidenceGeneration (jttyTx ? jttyCommittedSamples - 1 : -1, false); auto const txSessionId = m_txEvidenceSourceSession; auto const txGeneration = m_txEvidenceGeneration; TxEvidence::TxRequest request; - request.mode = m_mode; + request.mode = jttyTx ? QStringLiteral ("JTTY") : 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.queue_epoch = jttyTx ? m_jttyTxLifecycle.epoch () + : TxAudioQueueEpoch::invalid (); request.tuning = m_tune; int const cwSymbols = qBound (0, int (icw[0]), NUM_CW_SYMBOLS - 1); request.cw_id.reserve (cwSymbols); @@ -12737,13 +13088,14 @@ void MainWindow::transmit (double snr) dispatchTxRequest (request); } - if (m_mode == "JTTY") { + if (request.mode == "JTTY") { + m_jttyTxLifecycle.markTransmitting (); 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.frequency_hz = ui->TxFreqSpinBox_2->value () - m_XIT; request.tone_spacing = toneSpacing; request.synchronize = false; request.tr_period_s = txt; @@ -13026,7 +13378,7 @@ void MainWindow::transmitDisplay (bool transmitting) } // the following are always disallowed in transmit - ui->menuMode->setEnabled (!transmitting && !m_modeLocked); + updateModeControlLock (); } } @@ -13794,7 +14146,9 @@ void MainWindow::astroUpdate () } auto correction = m_astroWidget->astroUpdate(QDateTime::currentDateTimeUtc (), - m_config.my_grid(), m_hisGrid,m_operatingFrequency.rx (),"Echo" == m_mode, + m_config.my_grid(), m_hisGrid, m_config.has_precise_home_coordinates (), + m_config.home_latitude (), m_config.home_longitude (), + 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; @@ -13862,7 +14216,7 @@ RigFrequencyChangePolicy::Activity MainWindow::rigFrequencyActivity () const m_tx_when_ready, m_transmitting, m_tune, - m_jttyTxActive, + m_jttyTxLifecycle.active (), ptt1Timer.isActive (), ptt0Timer.isActive (), m_rigState.ptt (), @@ -13915,11 +14269,13 @@ bool MainWindow::dispatchNominalFrequency (Frequency corrected, bool MainWindow::requestNominalFrequencyChange (Frequency frequency, FrequencyRequestOrigin origin) { + auto const previous = m_operatingFrequency.rx(); if (!m_operatingFrequency.requestNominal (frequency, m_astroCorrection.rx, [this, origin] (Frequency corrected) { return dispatchNominalFrequency (corrected, origin, m_monitoring); })) return false; + if (m_mode == "JTTY" && previous != m_operatingFrequency.rx()) updateJttyReceiveContext(); genCQMsg (); if (m_astroWidget) { @@ -14170,6 +14526,10 @@ void MainWindow::tx_watchdog (bool triggered) tx_status_label.setText (tr (" Runaway Tx watchdog ")); QApplication::alert (this); if (SpecOp::HOUND == m_specOp) ui->txrb1->click (); // Go back to Tx1 + if (m_jttyTxLifecycle.active ()) stopTx (); +#ifdef WIN32 + finalizeMmttyExternalAbort (); +#endif } else { @@ -17416,12 +17776,6 @@ void MainWindow::set_mode_from_command_line(const QString& mode, bool lock_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); + updateModeControlLock (); } } |
