summaryrefslogtreecommitdiff
path: root/widgets/JttyMessages.hpp
blob: 9f51a6a01e7b25d91f80547912466285e900b21c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
// -*- Mode: C++ -*-
#ifndef JTTY_MESSAGES_HPP
#define JTTY_MESSAGES_HPP

#include <algorithm>
#include <cmath>
#include <cstddef>
#include <optional>
#include <type_traits>

#include <QByteArray>
#include <QDateTime>
#include <QRegularExpression>
#include <QString>
#include <QStringList>
#include <QTime>
#include <QVector>

namespace Jtty
{
  // A content-free "keep transmitting" pattern (ordinary TEXT5-encoded text, nothing protocol-special) used to bridge a typing pause without PTT dropping/re-keying; '<' isn't used in normal chat text, so it's recognized and suppressed wherever JTTY text is displayed or logged.
  inline QString const jttyFillerText =
    QStringLiteral ("<<<<< <<<<<");

  inline bool isJttyFillerText (QString const& text)
  {
    QString const trimmed = text.trimmed ();
    if (trimmed.isEmpty ()) return false;
    for (QChar const c : trimmed) {
      if (c != QLatin1Char ('<') && c != QLatin1Char (' ')) return false;
    }
    return true;
  }

  // Collapses embedded filler runs (any internal spacing) to a single space, without trimming the string's own leading/trailing edge. For a growing-message delta fragment (e.g. ReceiveResultController's N1MM echo), a leading/trailing space is the word boundary against already-echoed text, not something filler-adjacent to discard.
  inline QString collapseJttyFillerRuns (QString text)
  {
    static QRegularExpression const pattern (
      QStringLiteral ("\\s*(?:<{5}\\s*)+"));
    text.replace (pattern, QStringLiteral (" "));
    return text;
  }

  // Filler travels gaplessly inside the same growing message as the real content around it, so it shows up embedded mid-string rather than as an isolated update; strips one-or-more 5-char '<' blocks (any internal spacing) and collapses the surrounding whitespace to a single space.
  inline QString stripJttyFillerText (QString text)
  {
    return collapseJttyFillerRuns (text).simplified ();
  }

  struct ParsedDecodeLine
  {
    int frequency {0};
    QString message;
    bool valid {false};
  };

  struct PreparedTransmitText
  {
    QString text;
    bool substituted {false};
  };

  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;
    int snr {-10};  // SNR of received signal, for %R; stubbed until the decoder reports it

    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;
    result.text.reserve (message.size ());

    for (QChar c : message) {
      if (c == QChar::Null || c == QLatin1Char {'~'}) {
        result.text.append (QLatin1Char {' '});
        result.substituted = true;
      } else if (c == QLatin1Char {'\n'} || c == QLatin1Char {'\r'}) {
        // A forced segment boundary, not a character; execute_jtty_tx splits on it.
        result.text.append (QLatin1Char {'\n'});
      } else if (isSourceCharacter (c)) {
        result.text.append (c);
      } else {
        result.text.append (QLatin1Char {'#'});
        result.substituted = true;
      }
    }

    return result;
  }

  struct TransmitTextSegment
  {
    int offset {0};
    int length {0};
    QString text;
  };

  // Source spans include separator spaces so every submitted character is accounted for.
  inline TransmitTextSegment nextTransmitTextSegment (
      QString const& message, int offset, int maximumLength = maxTransmitLength)
  {
    if (offset < 0 || offset >= message.size () || maximumLength <= 0) return {};

    int length = std::min ({message.size () - offset, maximumLength, maxTransmitLength});
    if (offset + length < message.size ()
        && message.at (offset + length) != QLatin1Char {' '}) {
      for (int i = length - 1; i > 0; --i) {
        if (message.at (offset + i) == QLatin1Char {' '}
            && !message.mid (offset, i).trimmed ().isEmpty ()) {
          length = i + 1;
          break;
        }
      }
    }
    return {offset, length, message.mid (offset, length)};
  }

  // A segment that does not encode refuses the line rather than being cut shorter: the rest would continue the receiver's 80-column message.
  template <typename Encode>
  std::optional<QVector<TransmitTextSegment>> encodeTransmitLine (QString const& line, Encode&& encode)
  {
    QVector<TransmitTextSegment> segments;
    for (int offset = 0; offset < line.size ();) {
      auto const source = nextTransmitTextSegment (line, offset);
      if (!source.text.trimmed ().isEmpty ()) {
        if (!encode (source.text)) return std::nullopt;
        segments.append (source);
      }
      offset += source.length;
    }
    return segments;
  }

  // An empty result rejects oversized text before it reaches the fixed-width codec.
  inline QString transmitFrame (QString const& message)
  {
    if (message.size () > maxTransmitLength) return {};
    return message + QString (maxTransmitLength - message.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 {};
    }
  }

  // Chat/QSO-style templates for JTTY's "FT8 style" message preset (as opposed
  // to the contest-exchange-oriented templates above). F7/F8 are left blank.
  inline QString ft8StyleMacroTemplate (int functionKey)
  {
    static QString const templates[] {
      QStringLiteral ("%H %M %G"),
      QStringLiteral ("%H %M %R"),
      QStringLiteral ("%H %M R%R"),
      QStringLiteral ("%H %M RRR"),
      QStringLiteral ("%H %M 73"),
      QStringLiteral ("CQ %M %G"),
      QString {},
      QString {}
    };
    if (functionKey < 1 || functionKey > 8) return {};
    return templates[functionKey - 1];
  }

  enum class MessageStyle : qint8 { Contest = 0, Ft8 = 1 };

  // QSettings key for one function key's template under the given style, so
  // Contest- and FT8-style edits persist independently of each other.
  inline QString messageStyleSettingsKey (MessageStyle style, int functionKey)
  {
    return style == MessageStyle::Ft8
      ? QStringLiteral ("JTTY_FT8_msg%1").arg (functionKey)
      : QStringLiteral ("JTTY_msg%1").arg (functionKey);
  }

  inline QString messageStyleDefaultTemplate (MessageStyle style, int functionKey)
  {
    return style == MessageStyle::Ft8
      ? ft8StyleMacroTemplate (functionKey) : nativeMacroTemplate (functionKey);
  }

  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 formatSnr (int snr)
  {
    return QString::asprintf ("%+03d", snr);
  }

  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.trimmed ().toUpper ().left (4));
    macroTemplate.replace (QStringLiteral ("%R"), formatSnr (context.snr));
    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));
  }

  // Matches a decode line's freq/SNR column layout with the SNR field left
  // blank (a sent message has no measured SNR), so Tx and Rx lines line up.
  inline QString formatJttyTxLine (float frequency, QString const& message)
  {
    QString const frequencyText = QStringLiteral ("%1").arg (qRound (frequency), 4);
    return frequencyText + QStringLiteral ("      ") + message;
  }

  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;
  }

  // Format one JTTY decode line for display/logging: "Freq SNR  Message" (a
  // leading UTC time label, when wanted, is prepended by the caller). SNR is
  // plain right-justified, no zero-pad/forced sign -- matches the existing
  // decode-pane convention used by other modes (e.g. FT8's own line format,
  // lib/decoder_callbacks.f90, "i4" for its SNR field), deliberately
  // different from formatSnr's zero-padded convention for the %R Tx macro.
  inline QString formatJttyDecodeLine (float frequency, int snr, QString const& message)
  {
    QString const frequencyText = QStringLiteral ("%1").arg (qRound (frequency), 4);
    QString const snrText = QStringLiteral ("%1").arg (snr, 3);
    return message.isEmpty ()
      ? frequencyText
      : frequencyText + QStringLiteral (" ") + snrText + QStringLiteral ("  ") + message;
  }

  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};
    int snr {-10};
  };

  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