File: displaytext.cpp

package info (click to toggle)
wsjtx-improved 3.0.0%2B250924%2Brepack-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 86,260 kB
  • sloc: cpp: 105,882; f90: 60,117; python: 27,241; ansic: 13,372; fortran: 2,382; makefile: 197; sh: 135
file content (1202 lines) | stat: -rwxr-xr-x 42,432 bytes parent folder | download
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
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
#include "displaytext.h"

#include <vector>
#include <algorithm>

#include <QAudio>
#include <QAudioOutput>
#include <QSound>
#include <QDir>
#include <QCoreApplication>
#include <QTimer>
#include <QMouseEvent>
#include <QDateTime>
#include <QTextCharFormat>
#include <QTextCursor>
#include <QTextBlock>
#include <QMenu>
#include <QAction>
#include <QListIterator>
#include <QRegularExpression>
#include <QScrollBar>

#include "Configuration.hpp"
#include "Decoder/decodedtext.h"
#include "Network/LotWUsers.hpp"
#include "models/DecodeHighlightingModel.hpp"
#include "logbook/logbook.h"
#include "Logger.hpp"

#include "qt_helpers.hpp"
#include "moc_displaytext.cpp"

bool play_CQ = false;
bool play_MyCall = false;
bool play_DXCC = false;
bool play_DXCCOB = false;
bool play_Grid = false;
bool play_GridOB = false;
bool play_Continent = false;
bool play_ContinentOB = false;
bool play_CQZ = false;
bool play_CQZOB = false;
bool play_ITUZ = false;
bool play_ITUZOB = false;
bool muted = false;

using SpecOp = Configuration::SpecialOperatingActivity;

DisplayText::DisplayText(QWidget *parent)
  : QTextEdit(parent)
  , m_config {nullptr}
  , erase_action_ {new QAction {tr ("&Erase"), this}}
  , high_volume_ {false}
  , modified_vertical_scrollbar_max_ {-1}
{
  setReadOnly (true);
  setUndoRedoEnabled (false);
  viewport ()->setCursor (Qt::ArrowCursor);
  setWordWrapMode (QTextOption::NoWrap);

  // max lines to limit heap usage
  document ()->setMaximumBlockCount (5000);

  // context menu erase action
  setContextMenuPolicy (Qt::CustomContextMenu);
  connect (this, &DisplayText::customContextMenuRequested, [this] (QPoint const& position) {
      auto * menu = createStandardContextMenu (position);
      menu->addAction (erase_action_);
      menu->exec (mapToGlobal (position));
      delete menu;
    });
  connect (erase_action_, &QAction::triggered, this, &DisplayText::erase);
}

void DisplayText::erase ()
{
  clear ();
  Q_EMIT erased ();
}

void DisplayText::setContentFont(QFont const& font)
{
  char_font_ = font;
  selectAll ();
  auto cursor = textCursor ();
  cursor.beginEditBlock ();
  auto char_format = cursor.charFormat ();
  char_format.setFont (char_font_);
  cursor.mergeCharFormat (char_format);
  cursor.clearSelection ();
  cursor.movePosition (QTextCursor::End);

  // position so viewport scrolled to left
  cursor.movePosition (QTextCursor::Up);
  cursor.movePosition (QTextCursor::StartOfLine);
  cursor.endEditBlock ();

  if (!high_volume_ || !m_config || !m_config->decodes_from_top ())
    {
      setTextCursor (cursor);
      ensureCursorVisible ();
    }
}

void DisplayText::mouseDoubleClickEvent(QMouseEvent *e)
{
  Q_EMIT selectCallsign(e->modifiers ());
}

void DisplayText::insertLineSpacer(QString const& line)
{
  insertText (line, "#d3d3d3");
}

namespace
{
  using Highlight = DecodeHighlightingModel::Highlight;
  using highlight_types = std::vector<Highlight>;
  Highlight set_colours (Configuration const * config, QColor * bg, QColor * fg, highlight_types const& types)
  {
    Highlight result = Highlight::CQ;
    if (config)
      {
        QListIterator<DecodeHighlightingModel::HighlightInfo> it {config->decode_highlighting ().items ()};
        // iterate in reverse to honor priorities
        it.toBack ();
        while (it.hasPrevious ())
          {
            auto const& item = it.previous ();
            auto const& type = std::find (types.begin (), types.end (), item.type_);
            if (type != types.end () && item.enabled_)
              {
                if (item.background_.style () != Qt::NoBrush)
                  {
                    *bg = item.background_.color ();
                  }
                if (item.foreground_.style () != Qt::NoBrush)
                  {
                    *fg = item.foreground_.color ();
                  }
                result = item.type_;
              }
          }
      }
    return result;            // highest priority enabled highlighting
  }
}

void DisplayText::insertText(QString const& text, QColor bg, QColor fg
                             , QString const& call1, QString const& call2, QTextCursor::MoveOperation location)
{
  auto cursor = textCursor ();
  cursor.movePosition (location);
  auto block_format = cursor.blockFormat ();
  auto format = cursor.blockCharFormat ();
  format.setFont (char_font_);
  block_format.clearBackground ();
  if (bg.isValid ())
    {
      block_format.setBackground (bg);
    }
  format.clearForeground ();
  if (fg.isValid ())
    {
      format.setForeground (fg);
    }
  if (cursor.position ())
    {
      cursor.insertBlock (block_format, format);
    }
  else
    {
      cursor.setBlockFormat (block_format);
      cursor.setBlockCharFormat (format);
    }

  int text_index {0};
  auto temp_format = format;
  if (call1.size ())
    {
      auto call_index = text.indexOf (call1);
      if (call_index != -1) // sanity check
        {
          auto pos = highlighted_calls_.find (call1);
          if (pos != highlighted_calls_.end ())
            {
              cursor.insertText(text.left (call_index));
              if (pos.value ().first.isValid ())
                {
                  temp_format.setBackground (pos.value ().first);
                }
              if (pos.value ().second.isValid ())
                {
                  temp_format.setForeground (pos.value ().second);
                }
              cursor.insertText(text.mid (call_index, call1.size ()), temp_format);
              text_index = call_index + call1.size ();
            }
        }
    }
  if (call2.size ())
    {
      auto call_index = text.indexOf (call2, text_index);
      if (call_index != -1) // sanity check
        {
          auto pos = highlighted_calls_.find (call2);
          if (pos != highlighted_calls_.end ())
            {
              temp_format = format;
              cursor.insertText(text.mid (text_index, call_index - text_index), format);
              if (pos.value ().second.isValid ())
                {
                  temp_format.setBackground (pos.value ().first);
                }
              if (pos.value ().second.isValid ())
                {
                  temp_format.setForeground (pos.value ().second);
                }
              cursor.insertText(text.mid (call_index, call2.size ()), temp_format);
              text_index = call_index + call2.size ();
            }
        }
    }
  cursor.insertText(text.mid (text_index), format);

  // position so viewport scrolled to left
  cursor.movePosition (QTextCursor::StartOfLine);
  if (!high_volume_ || !m_config || !m_config->decodes_from_top ())
    {
      setTextCursor (cursor);
      ensureCursorVisible ();
    }
  document ()->setMaximumBlockCount (document ()->maximumBlockCount ());
}

void DisplayText::extend_vertical_scrollbar (int min, int max)
{
  if (high_volume_ && m_config && m_config->decodes_from_top ())
    {
      if (max && max != modified_vertical_scrollbar_max_)
        {
          setViewportMargins (0,4,0,0);  // ensure first line is readable
          auto vp_margins = viewportMargins ();
          // add enough to vertical scroll bar range to allow last
          // decode to just scroll of the top of the view port
          max += viewport ()->height () - vp_margins.top () - vp_margins.bottom ();
          modified_vertical_scrollbar_max_ = max;
        }
      verticalScrollBar ()->setRange (min, max);
    }
}

void DisplayText::new_period ()
{
  if (m_config->decodes_from_top ()) {
    document ()->setMaximumBlockCount (4800);
    document ()->setMaximumBlockCount (5000);
  }
  alertsTimer.stop ();
  disconnect (&alertsTimer, &QTimer::timeout, this, &DisplayText::AudioAlerts);
  if (m_config->alert_Enabled() && (m_config->alert_MyCall() || m_config->alert_DXCC() || m_config->alert_DXCCOB() ||
      m_config->alert_Grid() || m_config->alert_GridOB() || m_config->alert_Continent() || m_config->alert_ContinentOB() ||
      m_config->alert_CQZ() || m_config->alert_CQZOB() || m_config->alert_ITUZ() || m_config->alert_ITUZOB() ||
      m_config->alert_CQ())) {
      connect (&alertsTimer, &QTimer::timeout, this, &DisplayText::AudioAlerts);
      alertsTimer.setSingleShot (true);
      alertsTimer.start (1000);
  }

  extend_vertical_scrollbar (verticalScrollBar ()->minimum (), verticalScrollBar ()->maximum ());
  if (high_volume_ && m_config && m_config->decodes_from_top () && !vertical_scroll_connection_)
    {
      vertical_scroll_connection_ = connect (verticalScrollBar (), &QScrollBar::rangeChanged
                                             , [this] (int min, int max) {
                                               extend_vertical_scrollbar (min, max );
                                             });
    }
  verticalScrollBar ()->setSliderPosition (verticalScrollBar ()->maximum ());
}

QString DisplayText::appendWorkedB4 (QString message, QString call, QString const& grid,
                                     QColor * bg, QColor * fg, LogBook const& logBook,
                                     QString const& currentBand, QString const& currentMode,
                                     QString extra)
{
  QString countryName;
  bool callB4;
  bool callB4onBand;
  bool countryB4;
  bool countryB4onBand;
  bool gridB4;
  bool gridB4onBand;
  bool continentB4;
  bool continentB4onBand;
  bool CQZoneB4;
  bool CQZoneB4onBand;
  bool ITUZoneB4;
  bool ITUZoneB4onBand;

  if(call.length()==2) {
    int i0=message.indexOf("CQ "+call);
    call=message.mid(i0+6,-1);
    i0=call.indexOf(" ");
    call=call.mid(0,i0);
  }
  if(call.length()<3) return message;
  if(!call.contains(QRegExp("[0-9]|[A-Z]"))) return message;

  auto const& looked_up = logBook.countries ()->lookup (call);
  logBook.match (call, currentMode, grid, looked_up, callB4, countryB4, gridB4, continentB4, CQZoneB4, ITUZoneB4);
  logBook.match (call, currentMode, grid, looked_up, callB4onBand, countryB4onBand, gridB4onBand,
                 continentB4onBand, CQZoneB4onBand, ITUZoneB4onBand, currentBand);
  if(grid=="") {
    gridB4=true;
    gridB4onBand=true;
  }

  if(callB4onBand) m_points=0;

  message = message.trimmed ();

  highlight_types types;
  // no shortcuts here as some types may be disabled
  if (!countryB4) {
    types.push_back (Highlight::DXCC);
    if (m_config->alert_DXCC()) {
      if (!muted) play_DXCC = true;
    }
  }
  if(!countryB4onBand) {
    types.push_back (Highlight::DXCCBand);
    if (m_config->alert_DXCCOB()) {
       if (!muted) play_DXCCOB = true;
    }
  }
  if(!gridB4) {
    types.push_back (Highlight::Grid);
    if (m_config->alert_Grid()) {
      if (!muted) play_Grid = true;
    }
  }
  if(!gridB4onBand) {
    types.push_back (Highlight::GridBand);
    if (m_config->alert_GridOB()) {
      if (!muted) play_GridOB = true;
    }
  }
  if (!callB4) {
    types.push_back (Highlight::Call);
  }
  if(!callB4onBand) {
    types.push_back (Highlight::CallBand);
  }
  if (!continentB4) {
    types.push_back (Highlight::Continent);
    if (m_config->alert_Continent()) {
      if (!muted) play_Continent = true;
    }
  }
  if(!continentB4onBand) {
    types.push_back (Highlight::ContinentBand);
    if (m_config->alert_ContinentOB()) {
      if (!muted) play_ContinentOB = true;
    }
  }
  if (!CQZoneB4) {
    types.push_back (Highlight::CQZone);
    if (m_config->alert_CQZ()) {
      if (!muted) play_CQZ = true;
    }
  }
  if(!CQZoneB4onBand) {
    types.push_back (Highlight::CQZoneBand);
    if (m_config->alert_CQZOB()) {
      if (!muted) play_CQZOB = true;
    }
  }
  if (!ITUZoneB4) {
    types.push_back (Highlight::ITUZone);
    if (m_config->alert_ITUZ()) {
      if (!muted) play_ITUZ = true;
    }
  }
  if(!ITUZoneB4onBand) {
    types.push_back (Highlight::ITUZoneBand);
    if (m_config->alert_ITUZOB()) {
      if (!muted) play_ITUZOB = true;
    }
  }
  if (m_config && m_config->lotw_users ().user (call))
    {
      types.push_back (Highlight::LotW);
    }
  types.push_back (Highlight::CQ);
  auto top_highlight = set_colours (m_config, bg, fg, types);

  switch (top_highlight)
    {
    case Highlight::Continent:
    case Highlight::ContinentBand:
      extra += AD1CCty::continent (looked_up.continent);
      break;
    case Highlight::CQZone:
    case Highlight::CQZoneBand:
      extra += QString {"CQ Zone %1"}.arg (looked_up.CQ_zone);
      break;
    case Highlight::ITUZone:
    case Highlight::ITUZoneBand:
      extra += QString {"ITU Zone %1"}.arg (looked_up.ITU_zone);
      break;
    default:
      if (m_bPrincipalPrefix)
        {
          extra += looked_up.primary_prefix;
        }
      else
        {
          auto countryName = looked_up.entity_name;

          // do some obvious abbreviations
          countryName.replace ("Islands", "Is.");
          countryName.replace ("Island", "Is.");
          countryName.replace ("North ", "N. ");
          countryName.replace ("Northern ", "N. ");
          countryName.replace ("South ", "S. ");
          countryName.replace ("East ", "E. ");
          countryName.replace ("Eastern ", "E. ");
          countryName.replace ("West ", "W. ");
          countryName.replace ("Western ", "W. ");
          countryName.replace ("Central ", "C. ");
          countryName.replace (" and ", " & ");
          countryName.replace ("Republic", "Rep.");
          countryName.replace ("United States of America", "U.S.A.");
          countryName.replace ("United States", "U.S.A.");
          countryName.replace ("Fed. Rep. of ", "");
          countryName.replace ("French ", "Fr.");
          countryName.replace ("Asiatic", "AS");
          countryName.replace ("European", "EU");
          countryName.replace ("African", "AF");

          // assign WAE entities to the correct DXCC when "Include extra WAE entities" is not selected
          if (!(m_config->include_WAE_entities())) {
            countryName.replace ("Bear Is.", "Svalbard");
            countryName.replace ("Shetland Is.", "Scotland");
            countryName.replace ("AF Italy", "Italy");
            countryName.replace ("Sicily", "Italy");
            countryName.replace ("Vienna Intl Ctr", "Austria");
            countryName.replace ("AF Turkey", "Turkey");
            countryName.replace ("EU Turkey", "Turkey");
          }

          extra += countryName;
        }
    }
    m_CQPriority=DecodeHighlightingModel::highlight_name(top_highlight);

    if(((m_points == 00) or (m_points == -1)) and m_bDisplayPoints) return message;
    return leftJustifyAppendage (message, extra);
}

QString DisplayText::leftJustifyAppendage (QString message, QString const& appendage0) const
{
  QString appendage=appendage0;
  if(m_bDisplayPoints and (m_points>0)) {
    appendage=" " + QString::number(m_points);
    if(m_points<10) appendage=" " + appendage;
  }
  if (appendage.size ())
    {
      // allow for seconds
      int padding {message.indexOf (" ") > 4 ? 2 : 0};

      // use a nbsp to save the start of appended text so we can find
      // it again later, align appended data at a fixed column if
      // there is space otherwise let it float to the right
      int space_count;
      space_count = (40 + m_config->align_steps() + padding - message.size ());
      if (space_count > 0) {
        message += QString {space_count, QChar {' '}};
      }
      message += QChar::Nbsp + appendage;
    }
  return message;
}

void DisplayText::displayDecodedText(DecodedText const& decodedText, QString const& myCall,
                                     QString const& mode,
                                     bool displayDXCCEntity, LogBook const& logBook,
                                     QString const& currentBand, bool ppfx, bool bCQonly,
                                     bool haveFSpread, float fSpread, bool bDisplayPoints,
                                     int points, QString distance, bool alertsMuted)
{
  m_points=points;
  m_bDisplayPoints=bDisplayPoints;
  m_bPrincipalPrefix=ppfx;
  muted=alertsMuted;
  QColor bg;
  QColor fg;
  bool CQcall = false;
  auto is_73 = decodedText.messageWords().filter (QRegularExpression {"^(73|RR73)$"}).size();
  if (decodedText.string ().contains (" CQ ")) {
    if (m_config->alert_CQ()) {
      if (!muted) play_CQ = true;
    }
  }
  if (decodedText.string ().contains (" CQ ")
      || decodedText.string ().contains (" CQDX ")
      || decodedText.string ().contains (" QRZ ")
      || (is_73 && (m_config->highlight_73 ())))
    {
      CQcall = true;
    }
  else
    {
      if (bCQonly) return;
    }
  auto message = decodedText.string();
  QString dxCall;
  QString dxGrid;
  decodedText.deCallAndGrid (/*out*/ dxCall, dxGrid);
  QRegularExpression grid_regexp {"\\A(?![Rr]{2}73)[A-Ra-r]{2}[0-9]{2}([A-Xa-x]{2}){0,1}\\z"};
  if(!dxGrid.contains(grid_regexp)) dxGrid="";
  message = message.left (message.indexOf (QChar::Nbsp)).trimmed (); // strip appended info
  QString extra;
  QString state;    // NJ0A

  if (displayDXCCEntity && dxGrid.length() > 0  && logBook.countries ()->lookup (dxCall).primary_prefix  == "K") {
      //std::cout << dxCall << " -> " << dxGrid <<  " " << logBook.countries ()->lookup (dxCall).primary_prefix <<"\n";
      if (m_config->GridMap()) {
          if (CQcall || is_73 || m_config->GridMapAll()) {
            state = logBook.countries ()->findState(dxGrid);
          }
      }
  }
  //NJ0A

  if (haveFSpread)
    {
      extra += QString {"%1"}.arg (fSpread, 5, 'f', fSpread < 0.95 ? 3 : 2) + QChar {' '};
    }
  auto ap_pos = message.lastIndexOf (QRegularExpression {R"((?:\?\s)?(?:a[0-9]|q[0-9][0-9*]?)$)"});
  if (ap_pos >= 0)
    {
      extra += message.mid (ap_pos) + QChar {' '};
      message = message.left (ap_pos).trimmed ();
    }
  m_CQPriority="";
  if (CQcall || (is_73 && m_config->highlight_73()) || (mode == "FT4" && m_config->highlight_73() && m_config->NCCC_Sprint()
      && (SpecOp::NA_VHF == m_config->special_op_id()) && decodedText.string().contains(" R ")))
    {
      if (displayDXCCEntity)
        {
          // if enabled add the DXCC entity and B4 status to the end of the
          // preformated text line t1
          auto currentMode = mode;
          message = appendWorkedB4 (message, dxCall, dxGrid, &bg, &fg
                                    , logBook, currentBand, currentMode, extra);
        }
      else
        {
          message = leftJustifyAppendage (message, extra);
          highlight_types types {Highlight::CQ};
          if (m_config && m_config->lotw_users ().user (decodedText.CQersCall()))
            {
              types.push_back (Highlight::LotW);
            }
          set_colours (m_config, &bg, &fg, types);
        }
    }
  else
    {
      if (m_config->show_country_names())
        {
          auto const& looked_up = logBook.countries ()->lookup (dxCall);
          auto countryName = looked_up.entity_name;

          if (m_bPrincipalPrefix) {
              extra += looked_up.primary_prefix;
          } else {
              // do some obvious abbreviations
              countryName.replace ("Islands", "Is.");
              countryName.replace ("Island", "Is.");
              countryName.replace ("North ", "N. ");
              countryName.replace ("Northern ", "N. ");
              countryName.replace ("South ", "S. ");
              countryName.replace ("East ", "E. ");
              countryName.replace ("Eastern ", "E. ");
              countryName.replace ("West ", "W. ");
              countryName.replace ("Western ", "W. ");
              countryName.replace ("Central ", "C. ");
              countryName.replace (" and ", " & ");
              countryName.replace ("Republic", "Rep.");
              countryName.replace ("United States of America", "U.S.A.");
              countryName.replace ("United States", "U.S.A.");
              countryName.replace ("Fed. Rep. of ", "");
              countryName.replace ("French ", "Fr.");
              countryName.replace ("Asiatic", "AS");
              countryName.replace ("European", "EU");
              countryName.replace ("African", "AF");

              // assign WAE entities to the correct DXCC when "Include extra WAE entities" is not selected
              if (!(m_config->include_WAE_entities())) {
                countryName.replace ("Bear Is.", "Svalbard");
                countryName.replace ("Shetland Is.", "Scotland");
                countryName.replace ("AF Italy", "Italy");
                countryName.replace ("Sicily", "Italy");
                countryName.replace ("Vienna Intl Ctr", "Austria");
                countryName.replace ("AF Turkey", "Turkey");
                countryName.replace ("EU Turkey", "Turkey");
              }

              extra += countryName;
          }
          message = leftJustifyAppendage(message, extra);
        }
      else
        {
          message = leftJustifyAppendage (message, extra);
        }
    }

  if (myCall.size ())
    {
      QString regexp {"[ <]" + myCall + "[ >]"};
      if (Radio::is_compound_callsign (myCall))
        {
          regexp = "(?:" + regexp + "|[ <]" + Radio::base_callsign (myCall) + "[ >])";
        }
      if ((decodedText.clean_string () + " ").contains (QRegularExpression {regexp}))
        {
        QStringList tw;
        if (mode == "FT8" or mode == "FT4" or mode == "MSK144") {
          tw=decodedText.string().mid(24).split(" ",SkipEmptyParts);
        } else {
          tw=decodedText.string().mid(22).split(" ",SkipEmptyParts);
        }
          if ((tw.size () > 0 && tw[0].contains(myCall)) or decodedText.clean_string().contains("; " + myCall)) {
            highlight_types types {Highlight::MyCall};
            set_colours (m_config, &bg, &fg, types);
            if (m_config->alert_MyCall()) play_MyCall = true;
          } else {
            highlight_types types {Highlight::Tx};
            set_colours (m_config, &bg, &fg, types);
          }
        }
    }

  if (m_config->GridMap() && !m_bDisplayPoints) {
      if (ppfx) {               //NJ0A
          extra = " ";
      } else {
          extra = "      ";
      }
      message = leftJustifyAppendage(message, state);    //NJ0A
  }

  // display distance and azimuth
  if (distance.length() > 0) {
      if (m_config->align()) {
          if (!displayDXCCEntity) {
              message = leftJustifyAppendage (message, "[" + distance + "]");
          } else {
              QString space = " ";
              if (m_bPrincipalPrefix) {
                  if (message.length() < (49 + m_config->align_steps() + m_config->align_steps2())) {
                      message = leftJustifyAppendage ((message + (space.repeated(30))).left(48 + m_config->align_steps() + m_config->align_steps2()), "[" + distance + "]");
                  } else {
                      message = leftJustifyAppendage (message, " [" + distance + "]");
                  }
              } else {
                  if (message.length() < 59 + m_config->align_steps() + m_config->align_steps2()) {
                      message = leftJustifyAppendage ((message + (space.repeated(40))).left(59 + m_config->align_steps() + m_config->align_steps2()), "[" + distance + "]");
                  } else {
                      message = leftJustifyAppendage (message, "[" + distance + "]");
                  }
              }
          }
      } else {
         message = leftJustifyAppendage (message, "[" + distance + "]");
      }
  }

  // initialize audible alerts for MSK144 (still experimental)
  if(mode=="MSK144") {
    if ((m_config->alert_Enabled()) && ((m_config->alert_DXCC()) || (m_config->alert_DXCCOB()) || (m_config->alert_Grid()) ||
        (m_config->alert_GridOB()) || (m_config->alert_Continent()) || (m_config->alert_ContinentOB()) || (m_config->alert_CQZ()) ||
        (m_config->alert_CQZOB()) || (m_config->alert_ITUZ()) || (m_config->alert_ITUZOB()) || (m_config->alert_CQ()))) {
      alertsTimer.stop ();
      disconnect (&alertsTimer, &QTimer::timeout, this, &DisplayText::AudioAlerts);
      connect (&alertsTimer, &QTimer::timeout, this, &DisplayText::AudioAlerts);
      alertsTimer.setSingleShot (true);
      alertsTimer.start (1000);
    }
  }

  insertText (message.trimmed (), bg, fg, decodedText.call (), dxCall);
}

void DisplayText::displayTransmittedText(QString text, QString modeTx, qint32 txFreq,
                                         bool bFastMode, double TRperiod,bool bSuperfox)
{
    QString t1=" @  ";
    if(modeTx=="FT4") t1=" +  ";
    if(modeTx.contains("FT8")) t1=" ~  ";
    if(modeTx=="JT4") t1=" $  ";
    if(modeTx=="Q65") t1=" :  ";
    if(modeTx=="JT65") t1=" #  ";
    if(modeTx=="MSK144") t1=" &  ";
    if(modeTx=="FST4") t1=" `  ";
    QString t2;
    t2 = t2.asprintf("%4d",txFreq);
    QString t;
    if(bFastMode or modeTx=="FT8" or modeTx=="FT4" or (TRperiod<60) or
       (modeTx=="Q65" and TRperiod==60)) {
      t = QDateTime::currentDateTimeUtc().toString("hhmmss") + \
        "  Tx      " + t2 + t1 + text;
    } else if(modeTx.mid(0,6)=="FT8fox") {
      t = QDateTime::currentDateTimeUtc().toString("hhmmss") + \
        " Tx" + modeTx.mid(7) + " " + text;
    } else {
      t = QDateTime::currentDateTimeUtc().toString("hhmm") + \
        "  Tx      " + t2 + t1 + text;
    }
    QColor bg;
    QColor fg;
    highlight_types types {Highlight::Tx};
    set_colours (m_config, &bg, &fg, types);
    if(bSuperfox and t.contains(";")) {
      int i0=t.indexOf(";");
      int i1=t.indexOf("<");
      int i2=t.indexOf(">");
      QString foxcall=t.mid(i1+1,i2-i1-1);
      t2=t.left(i0).replace(" RR73", " " + foxcall + " RR73");
      QString t3=t.left(24) + t.mid(i0+2,-1).remove("<").remove(">");
      insertText (t2, bg, fg);
      insertText (t3, bg, fg);
    } else {
      insertText (t, bg, fg);
    }
}

void DisplayText::displayQSY(QString text)
{
  QString t = QDateTime::currentDateTimeUtc().toString("hhmmss") + "            " + text;
  insertText (t, "hotpink");
}

void DisplayText::displayHoundToBeCalled(QString t, bool bAtTop, QColor bg, QColor fg)
{
  if (bAtTop)  t = t + "\n"; // need a newline when insertion at top
  insertText(t, bg, fg, "", "", bAtTop ? QTextCursor::Start : QTextCursor::End);
}

void DisplayText::setHighlightedHoundText(QString t) {
  QColor bg=QColor{255,255,255};
  QColor fg=QColor{0,0,0};
  highlight_types types{Highlight::Call};
  set_colours(m_config, &bg, &fg, types);
  // t is multiple lines of text, each line is a hound calling
  // iterate through each line and highlight the callsign
  auto lines = t.split(QChar('\n'), SkipEmptyParts);
  clear();
  foreach (auto line, lines)
  {
    auto fields = line.split(QChar(' '), SkipEmptyParts);
    insertText(line, bg, fg, fields.first(), QString{});
  }
}

namespace
{
  void update_selection (QTextCursor& cursor, QColor const& bg, QColor const& fg)
  {
    QTextCharFormat format {cursor.charFormat ()};
    if (bg.isValid ())
      {
        format.setBackground (bg);
      }
    else
      {
        format.clearBackground ();
      }
    if (fg.isValid ())
      {
        format.setForeground (fg);
      }
    else
      {
        format.clearForeground ();
      }
    cursor.mergeCharFormat (format);
  }

  void reset_selection (QTextCursor& cursor)
  {
    // restore previous text format, we rely on the text
    // char format at he start of the selection being the
    // old one which should be the case
    auto c2 = cursor;
    c2.setPosition (c2.selectionStart ());
    cursor.setCharFormat (c2.charFormat ());
  }
}

namespace
{
  QString get_timestamp (QTextCursor& cursor)
  {
    QString timestamp;
    if (cursor.movePosition (QTextCursor::PreviousCharacter)
        && cursor.movePosition (QTextCursor::StartOfLine)
        && cursor.movePosition (QTextCursor::EndOfWord, QTextCursor::KeepAnchor)
        && cursor.hasSelection ())
      {
        timestamp = cursor.selectedText ();
        cursor.movePosition (QTextCursor::StartOfLine);
      }
    return timestamp;
  }
}

void DisplayText::highlight_callsign (QString const& callsign, QColor const& bg,
                                      QColor const& fg, bool last_period_only)
{
  auto regexp = callsign;
  if (!callsign.size () || callsign == "" || callsign == " " || callsign == "0")
    {
      return;
    }
  if (callsign == "CLEARALL!")  // programmatic means of clearing all highlighting
  {
    highlighted_calls_.clear();
    return;
  }
  // allow for hashed callsigns and escape any regexp metacharacters
  QRegularExpression target {QString {"<?"}
                             + regexp.replace (QLatin1Char {'+'}, QLatin1String {"\\+"})
                                 .replace (QLatin1Char {'.'}, QLatin1String {"\\."})
                                 .replace (QLatin1Char {'?'}, QLatin1String {"\\?"})
                             + QString {">?"}
                             , QRegularExpression::DontCaptureOption};
  QTextCharFormat old_format {currentCharFormat ()};
  QTextCursor cursor {document ()};
  if (last_period_only)
    {
      // highlight each instance of the given callsign (word) in the
      // current period
      cursor.movePosition (QTextCursor::End);
      QTextCursor period_start {cursor};
      QTextCursor prior {cursor};
      auto period_timestamp = get_timestamp (period_start);
      while (period_timestamp.size () && period_timestamp == get_timestamp (prior))
        {
          period_start = prior;
        }
      cursor = period_start;
      while (!cursor.isNull ())
        {
          cursor = document ()->find (target, cursor, QTextDocument::FindWholeWords);
          if (!cursor.isNull () && cursor.hasSelection ())
            {
              if (bg.isValid () || fg.isValid ())
                {
                  update_selection (cursor, bg, fg);
                }
              else
                {
                  reset_selection (cursor);
                }
            }
        }
    }
  else
    {
      auto pos = highlighted_calls_.find (callsign);
      if (bg.isValid () || fg.isValid ())
        {
          auto colours = qMakePair (bg, fg);
          if (pos == highlighted_calls_.end ())
            {
              pos = highlighted_calls_.insert (callsign.toUpper (), colours);
            }
          else
            {
              pos.value () = colours; // update colours
            }
          while (!cursor.isNull ())
            {
              cursor = document ()->find (target, cursor, QTextDocument::FindWholeWords);
              if (!cursor.isNull () && cursor.hasSelection ())
                {
                  update_selection (cursor, bg, fg);
                }
            }
        }
      else
        {
          if (pos != highlighted_calls_.end ())
            {
              highlighted_calls_.erase (pos);
            }
          QTextCursor cursor {document ()};
          while (!cursor.isNull ())
            {
              cursor = document ()->find (target, cursor, QTextDocument::FindWholeWords);
              if (!cursor.isNull () && cursor.hasSelection ())
                {
                  reset_selection (cursor);
                }
            }
        }
    }
  setCurrentCharFormat (old_format);
}

void DisplayText::AudioAlerts()
{
#ifdef WIN32
  if(m_config->alert_Enabled()) {
        QAudioOutput info(QAudioDeviceInfo::defaultOutputDevice());
        QString binPath = QCoreApplication::applicationDirPath();
        QAudioFormat format;
        format.setCodec("audio/pcm");
        format.setSampleRate (48000);
        format.setChannelCount (1);
        format.setSampleSize (16);
        format.setSampleType(QAudioFormat::SignedInt);
        QAudioOutput* audio;
        audio = new QAudioOutput(format, this);
        connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State)));
#else
  if(m_config->alert_Enabled()) {
        QString binPath = "/usr/share/wsjtx";
#endif
        QFile *effect2 = new QFile(this);
        QFile *effect3 = new QFile(this);
        QFile *effect4 = new QFile(this);
        QFile *effect5 = new QFile(this);
        QFile *effect6 = new QFile(this);
        QFile *effect7 = new QFile(this);
        QFile *effect8 = new QFile(this);
        QFile *effect9 = new QFile(this);
        QFile *effect10 = new QFile(this);
        QFile *effect11 = new QFile(this);
        QFile *effect12 = new QFile(this);
        QFile *effect13 = new QFile(this);
        effect2->setFileName(QString("%1/%2").arg(binPath, "/sounds/MyCall.wav"));
        effect3->setFileName(QString("%1/%2").arg(binPath, "/sounds/DXCC.wav"));
        effect4->setFileName(QString("%1/%2").arg(binPath, "/sounds/DXCCOnBand.wav"));
        effect5->setFileName(QString("%1/%2").arg(binPath, "/sounds/Continent.wav"));
        effect6->setFileName(QString("%1/%2").arg(binPath, "/sounds/ContinentOnBand.wav"));
        effect7->setFileName(QString("%1/%2").arg(binPath, "/sounds/CQZone.wav"));
        effect8->setFileName(QString("%1/%2").arg(binPath, "/sounds/CQZoneOnBand.wav"));
        effect9->setFileName(QString("%1/%2").arg(binPath, "/sounds/ITUZone.wav"));
        effect10->setFileName(QString("%1/%2").arg(binPath, "/sounds/ITUZoneOnBand.wav"));
        effect11->setFileName(QString("%1/%2").arg(binPath, "/sounds/Grid.wav"));
        effect12->setFileName(QString("%1/%2").arg(binPath, "/sounds/GridOnBand.wav"));
        effect13->setFileName(QString("%1/%2").arg(binPath, "/sounds/CQ.wav"));
        static int startIndex = 0;
        int nextStartIndex = startIndex +1;
        switch (startIndex) {
        case 0:
            if (play_MyCall) {
#ifdef WIN32
                effect2->open(QIODevice::ReadOnly);
                audio->start(effect2);
#else
                QSound::play(binPath + "/sounds/MyCall.wav");  // for Linux and macOS
#endif
                play_MyCall = false;
                alertsTimer.start (1000);
                startIndex = nextStartIndex;
                return;
            } else {
                nextStartIndex++;
            }
            Q_FALLTHROUGH();
        case 1:
            if (play_DXCC) {
#ifdef WIN32
                effect3->open(QIODevice::ReadOnly);
                audio->start(effect3);
#else
                QSound::play(binPath + "/sounds/DXCC.wav");  // for Linux and macOS
#endif
                play_DXCC = false;
                play_DXCCOB = false;
                alertsTimer.start (1200);
                startIndex = nextStartIndex;
                return;
            } else {
                nextStartIndex++;
            }
            Q_FALLTHROUGH();
        case 2:
            if (play_DXCCOB && !play_DXCC) {
#ifdef WIN32
                effect4->open(QIODevice::ReadOnly);
                audio->start(effect4);
#else
                QSound::play(binPath + "/sounds/DXCCOnBand.wav");  // for Linux and macOS
#endif
                play_DXCCOB = false;
                alertsTimer.start (1800);
                startIndex = nextStartIndex;
                return;
            } else {
                nextStartIndex++;
            }
            Q_FALLTHROUGH();
        case 3:
            if (play_Continent) {
#ifdef WIN32
                effect5->open(QIODevice::ReadOnly);
                audio->start(effect5);
#else
                QSound::play(binPath + "/sounds/Continent.wav");  // for Linux and macOS
#endif
                play_Continent = false;
                play_ContinentOB = false;
                play_GridOB = false;
                play_CQZOB = false;
                play_ITUZOB = false;
                alertsTimer.start (1000);
                startIndex = nextStartIndex;
                return;
            } else {
                nextStartIndex++;
            }
            Q_FALLTHROUGH();
        case 4:
            if (play_ContinentOB && !play_Continent) {
#ifdef WIN32
                effect6->open(QIODevice::ReadOnly);
                audio->start(effect6);
#else
                QSound::play(binPath + "/sounds/ContinentOnBand.wav");  // for Linux and macOS
#endif
                play_ContinentOB = false;
                play_GridOB = false;
                play_CQZOB = false;
                play_ITUZOB = false;
                alertsTimer.start (2000);
                startIndex = nextStartIndex;
                return;
            } else {
                nextStartIndex++;
            }
            Q_FALLTHROUGH();
        case 5:
            if (play_CQZ) {
#ifdef WIN32
                effect7->open(QIODevice::ReadOnly);
                audio->start(effect7);
#else
                QSound::play(binPath + "/sounds/CQZone.wav");  // for Linux and macOS
#endif
                play_CQZ = false;
                play_CQZOB = false;
                alertsTimer.start (1500);
                startIndex = nextStartIndex;
                return;
            } else {
                nextStartIndex++;
            }
            Q_FALLTHROUGH();
        case 6:
            if (play_CQZOB && !play_CQZ) {
#ifdef WIN32
                effect8->open(QIODevice::ReadOnly);
                audio->start(effect8);
#else
                QSound::play(binPath + "/sounds/CQZoneOnBand.wav");  // for Linux and macOS
#endif
                play_CQZOB = false;
                alertsTimer.start (1800);
                startIndex = nextStartIndex;
                return;
            } else {
                nextStartIndex++;
            }
            Q_FALLTHROUGH();
        case 7:
            if (play_ITUZ) {
#ifdef WIN32
                effect9->open(QIODevice::ReadOnly);
                audio->start(effect9);
#else
                QSound::play(binPath + "/sounds/ITUZone.wav");  // for Linux and macOS
#endif
                play_ITUZ = false;
                play_ITUZOB = false;
                play_GridOB = false;
                alertsTimer.start (1500);
                startIndex = nextStartIndex;
                return;
            } else {
                nextStartIndex++;
            }
            Q_FALLTHROUGH();
        case 8:
            if (play_ITUZOB && !(play_ITUZ)) {
#ifdef WIN32
                effect10->open(QIODevice::ReadOnly);
                audio->start(effect10);
#else
                QSound::play(binPath + "/sounds/ITUZoneOnBand.wav");  // for Linux and macOS
#endif
                play_ITUZOB = false;
                play_GridOB = false;
                alertsTimer.start (1900);
                startIndex = nextStartIndex;
                return;
            } else {
                nextStartIndex++;
            }
            Q_FALLTHROUGH();
        case 9:
            if (play_Grid) {
#ifdef WIN32
                effect11->open(QIODevice::ReadOnly);
                audio->start(effect11);
#else
                QSound::play(binPath + "/sounds/Grid.wav");  // for Linux and macOS
#endif
                play_Grid = false;
                play_GridOB = false;
                alertsTimer.start (1000);
                startIndex = nextStartIndex;
                return;
            } else {
                nextStartIndex++;
            }
            Q_FALLTHROUGH();
        case 10:
            if (play_GridOB && !play_Grid) {
#ifdef WIN32
                effect12->open(QIODevice::ReadOnly);
                audio->start(effect12);
#else
                QSound::play(binPath + "/sounds/GridOnBand.wav");  // for Linux and macOS
#endif
                play_GridOB = false;
                alertsTimer.start (1500);
                startIndex = nextStartIndex;
                return;
            } else {
                nextStartIndex++;
            }
            Q_FALLTHROUGH();
        case 11:
            if (play_CQ) {
#ifdef WIN32
                effect13->open(QIODevice::ReadOnly);
                audio->start(effect13);
#else
                QSound::play(binPath + "/sounds/CQ.wav");  // for Linux and macOS
#endif
                play_CQ = false;
                alertsTimer.start (1000);
                nextStartIndex++;
                return;
            } else {
                nextStartIndex++;
            }
            Q_FALLTHROUGH();
        case 12:
            // stop any running alerts timer, clear temp data, and restart alerts timer
            alertsTimer.stop ();
#ifdef WIN32
            effect2->close();
            effect2->deleteLater();
            effect3->close();
            effect3->deleteLater();
            effect4->close();
            effect4->deleteLater();
            effect5->close();
            effect5->deleteLater();
            effect6->close();
            effect6->deleteLater();
            effect7->close();
            effect7->deleteLater();
            effect8->close();
            effect8->deleteLater();
            effect9->close();
            effect9->deleteLater();
            effect10->close();
            effect10->deleteLater();
            effect11->close();
            effect11->deleteLater();
            effect12->close();
            effect12->deleteLater();
            effect13->close();
            effect13->deleteLater();
            audio->deleteLater();  // remove QAudioSink to avoid a memory leak
#endif
            alertsTimer.start (1250);
            startIndex = 0;
            return;
        }
  }
}