File: fret.cpp

package info (click to toggle)
musescore3 3.2.3%2Bdfsg2-11
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 210,672 kB
  • sloc: cpp: 291,093; xml: 200,238; sh: 3,779; ansic: 1,447; python: 393; makefile: 240; perl: 82; pascal: 79
file content (1468 lines) | stat: -rw-r--r-- 49,951 bytes parent folder | download | duplicates (4)
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
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
//=============================================================================
//  MuseScore
//  Music Composition & Notation
//
//  Copyright (C) 2010-2011 Werner Schweer
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License version 2
//  as published by the Free Software Foundation and appearing in
//  the file LICENCE.GPL
//=============================================================================

#include "fret.h"
#include "measure.h"
#include "system.h"
#include "score.h"
#include "stringdata.h"
#include "chord.h"
#include "note.h"
#include "segment.h"
#include "mscore.h"
#include "harmony.h"
#include "staff.h"
#include "undo.h"

namespace Ms {

//    parent() is Segment or Box
//

//---------------------------------------------------------
//   fretStyle
//---------------------------------------------------------

static const ElementStyle fretStyle {
      { Sid::fretNumPos,                         Pid::FRET_NUM_POS            },
      { Sid::fretMag,                            Pid::MAG                     },
      { Sid::fretPlacement,                      Pid::PLACEMENT               },
      { Sid::fretStrings,                        Pid::FRET_STRINGS            },
      { Sid::fretFrets,                          Pid::FRET_FRETS              },
      { Sid::fretNut,                            Pid::FRET_NUT                },
      { Sid::fretMinDistance,                    Pid::MIN_DISTANCE            },
      };

//---------------------------------------------------------
//   FretDiagram
//---------------------------------------------------------

FretDiagram::FretDiagram(Score* score)
   : Element(score, ElementFlag::MOVABLE | ElementFlag::ON_STAFF)
      {
      font.setFamily("FreeSans");
      font.setPointSize(4.0 * mag());
      initElementStyle(&fretStyle);
      }

FretDiagram::FretDiagram(const FretDiagram& f)
   : Element(f)
      {
      _strings    = f._strings;
      _frets      = f._frets;
      _fretOffset = f._fretOffset;
      _maxFrets   = f._maxFrets;
      font        = f.font;
      _userMag    = f._userMag;
      _numPos     = f._numPos;
      _dots       = f._dots;
      _markers    = f._markers;
      _barres     = f._barres;
      _showNut    = f._showNut;

      if (f._harmony) {
            Harmony* h = new Harmony(*f._harmony);
            add(h);
            }
      }

FretDiagram::~FretDiagram()
      {
      if (_harmony)
            delete _harmony;
      }

//---------------------------------------------------------
//   fromString
///   Create diagram from string like "XO-123"
///   Always assume barre on the first visible fret
//---------------------------------------------------------

FretDiagram* FretDiagram::fromString(Score* score, const QString &s)
      {
      FretDiagram* fd = new FretDiagram(score);
      int strings = s.size();

      fd->setStrings(strings);
      fd->setFrets(4);
      fd->setPropertyFlags(Pid::FRET_STRINGS, PropertyFlags::UNSTYLED);
      fd->setPropertyFlags(Pid::FRET_FRETS,   PropertyFlags::UNSTYLED);
      int offset = 0;
      int barreString = -1;
      std::vector<std::pair<int, int>> dotsToAdd;

      for (int i = 0; i < strings; i++) {
            QChar c = s.at(i);
            if (c == 'X' || c == 'O') {
                  FretMarkerType mt = (c == 'X' ? FretMarkerType::CROSS : FretMarkerType::CIRCLE);
                  fd->setMarker(i, mt);
                  }
            else if (c == '-' && barreString == -1) {
                  barreString = i;
                  }
            else {
                  int fret = c.digitValue();
                  if (fret != -1) {
                        dotsToAdd.push_back(make_pair(i, fret));
                        if (fret - 3 > 0 && offset < fret - 3)
                            offset = fret - 3;
                        }
                  }
            }

      if (offset > 0)
            fd->setFretOffset(offset);

      for (std::pair<int, int> d : dotsToAdd) {
            fd->setDot(d.first, d.second - offset, true);
            }

      // This assumes that any barre goes to the end of the fret
      if (barreString >= 0)
            fd->setBarre(barreString, -1, 1);

      return fd;
      }

//---------------------------------------------------------
//   pagePos
//---------------------------------------------------------

QPointF FretDiagram::pagePos() const
      {
      if (parent() == 0)
            return pos();
      if (parent()->isSegment()) {
            Measure* m = toSegment(parent())->measure();
            System* system = m->system();
            qreal yp = y();
            if (system)
                  yp += system->staffYpage(staffIdx());
            return QPointF(pageX(), yp);
            }
      else
            return Element::pagePos();
      }

//---------------------------------------------------------
//   dragAnchor
//---------------------------------------------------------

QLineF FretDiagram::dragAnchor() const
      {
      qreal xp = 0.0;
      for (Element* e = parent(); e; e = e->parent())
            xp += e->x();
      qreal yp;
      if (parent()->isSegment()) {
            System* system = toSegment(parent())->measure()->system();
            yp = system->staffCanvasYpage(staffIdx());
            }
      else
            yp = parent()->canvasPos().y();
      QPointF p1(xp, yp);
      return QLineF(p1, canvasPos());
#if 0 // TODOxx
      if (parent()->isSegment()) {
            Segment* s     = toSegment(parent());
            Measure* m     = s->measure();
            System* system = m->system();
            qreal yp      = system->staff(staffIdx())->y() + system->y();
            qreal xp      = m->tick2pos(s->tick()) + m->pagePos().x();
            QPointF p1(xp, yp);

            qreal x  = 0.0;
            qreal y  = 0.0;
            qreal tw = width();
            qreal th = height();
            if (_align & Align::BOTTOM)
                  y = th;
            else if (_align & Align::VCENTER)
                  y = (th * .5);
            else if (_align & Align::BASELINE)
                  y = baseLine();
            if (_align & Align::RIGHT)
                  x = tw;
            else if (_align & Align::HCENTER)
                  x = (tw * .5);
            return QLineF(p1, abbox().topLeft() + QPointF(x, y));
            }
      return QLineF(parent()->pagePos(), abbox().topLeft());
#endif
      }

//---------------------------------------------------------
//   setStrings
//---------------------------------------------------------

void FretDiagram::setStrings(int n)
      {
      int difference = n - _strings;
      if (difference == 0 || n <= 0)
            return;

      // Move all dots, makers, barres to the RIGHT, so we add strings to the left
      // This is more useful - few instruments need strings added to the right.
      DotMap tempDots;
      MarkerMap tempMarkers;

      for (int string = 0; string < _strings; ++string) {
            if (string + difference < 0)
                  continue;

            for (auto const& d : dot(string)) {
                  if (d.exists())
                        tempDots[string + difference].push_back(FretItem::Dot(d));
                  }

            if (marker(string).exists())
                  tempMarkers[string + difference] = marker(string);
            }

      _dots = tempDots;
      _markers = tempMarkers;

      for (int fret = 1; fret <= _frets; ++fret) {
            if (barre(fret).exists()) {
                  if (_barres[fret].startString + difference <= 0) {
                        removeBarre(fret);
                        continue;
                        }

                  _barres[fret].startString = qMax(0, _barres[fret].startString + difference);
                  _barres[fret].endString   = _barres[fret].endString == -1 ? -1 : _barres[fret].endString + difference;
                  }

            }

      _strings = n;
      }

//---------------------------------------------------------
//   init
//---------------------------------------------------------

void FretDiagram::init(StringData* stringData, Chord* chord)
      {
      if (!stringData)
            setStrings(6);
      else
            setStrings(stringData->strings());
      if (stringData) {
            for (int string = 0; string < _strings; ++string)
                  setMarker(string, FretMarkerType::CROSS);
            for (const Note* note : chord->notes()) {
                  int string;
                  int fret;
                  if (stringData->convertPitch(note->pitch(), chord->staff(), chord->segment()->tick(), &string, &fret))
                        setDot(string, fret);
                  }
            _maxFrets = stringData->frets();
            }
      else
            _maxFrets = 6;
      }

//---------------------------------------------------------
//   draw
//---------------------------------------------------------

void FretDiagram::draw(QPainter* painter) const
      {
      // Init pen and other values
      qreal _spatium = spatium() * _userMag;
      QPen pen(curColor());
      pen.setCapStyle(Qt::FlatCap);
      painter->setBrush(QBrush(QColor(painter->pen().color())));

      // x2 is the x val of the rightmost string
      qreal x2 = (_strings-1) * stringDist;

      // Draw the nut
      pen.setWidthF(nutLw);
      painter->setPen(pen);
      painter->drawLine(QLineF(-stringLw * .5, 0.0, x2 + stringLw * .5, 0.0));

      // Draw strings and frets
      pen.setWidthF(stringLw);
      painter->setPen(pen);

      // y2 is the y val of the bottom fretline
      qreal y2 = fretDist * (_frets + .5);
      for (int i = 0; i < _strings; ++i) {
            qreal x = stringDist * i;
            painter->drawLine(QLineF(x, _fretOffset ? -_spatium * .2 : 0.0, x, y2));
            }
      for (int i = 1; i <= _frets; ++i) {
            qreal y = fretDist * i;
            painter->drawLine(QLineF(0.0, y, x2, y));
            }

      // Setup the font for the markers
      QFont scaledFont(font);
      scaledFont.setPointSizeF(font.pointSize() * _userMag * (spatium() / SPATIUM20));
      QFontMetricsF fm(scaledFont, MScore::paintDevice());
      scaledFont.setPointSizeF(scaledFont.pointSizeF() * MScore::pixelRatio);

      painter->setFont(scaledFont);

      // dotd is the diameter of a dot
      qreal dotd = _spatium * .49 * score()->styleD(Sid::fretDotSize);

      // Draw dots, sym pen is used to draw them
      QPen symPen(pen);
      symPen.setCapStyle(Qt::RoundCap);
      qreal symPenWidth = stringLw * 1.2;
      symPen.setWidthF(symPenWidth);

      for (auto const& i : _dots) {
            for (auto const& d : i.second) {
                  if (!d.exists())
                        continue;

                  int string = i.first;
                  int fret = d.fret - 1;

                  // Calculate coords of the top left corner of the dot
                  qreal x = stringDist * string - dotd * .5;
                  qreal y = fretDist * fret + fretDist * .5 - dotd * .5;

                  // Draw different symbols
                  painter->setPen(symPen);
                  switch (d.dtype) {
                        case FretDotType::CROSS:
                              // Give the cross a slightly larger width
                              symPen.setWidthF(symPenWidth * 1.5);
                              painter->setPen(symPen);
                              painter->drawLine(QLineF(x, y, x + dotd, y + dotd));
                              painter->drawLine(QLineF(x + dotd, y, x, y + dotd));
                              symPen.setWidthF(symPenWidth);
                              break;
                        case FretDotType::SQUARE:
                              painter->setBrush(Qt::NoBrush);
                              painter->drawRect(QRectF(x, y, dotd, dotd));
                              break;
                        case FretDotType::TRIANGLE:
                              painter->drawLine(QLineF(x, y + dotd, x + .5 * dotd, y));
                              painter->drawLine(QLineF(x + .5 * dotd, y, x + dotd, y + dotd));
                              painter->drawLine(QLineF(x + dotd, y + dotd, x, y + dotd));                                    
                              break;
                        case FretDotType::NORMAL:
                        default:
                              painter->setBrush(symPen.color());
                              painter->setPen(Qt::NoPen);
                              painter->drawEllipse(QRectF(x, y, dotd, dotd));
                              break;
                        }
                  }
            }

      // Draw markers
      painter->setPen(pen);
      for (auto const& i : _markers) {
            int string = i.first;
            FretItem::Marker marker = i.second;

            QChar markerChar = FretItem::markerToChar(marker.mtype);

            qreal x = stringDist * string;
            qreal y = -fretDist * .3 - fm.ascent();
            painter->drawText(QRectF(x, y, .0, .0),
               Qt::AlignHCenter|Qt::TextDontClip, markerChar);
            }

      // Draw barres
      for (auto const& i : _barres) {
            int fret        = i.first;
            int startString = i.second.startString;
            int endString   = i.second.endString;

            qreal x1    = stringDist * startString;
            qreal newX2 = endString == -1 ? x2 : stringDist * endString;
            qreal y     = fretDist * (fret - 1) + fretDist * .5;
            pen.setWidthF(dotd * score()->styleD(Sid::barreLineWidth));
            pen.setCapStyle(Qt::RoundCap);
            painter->setPen(pen);
            painter->drawLine(QLineF(x1, y, newX2, y));
            }

      // Draw fret offset number
      if (_fretOffset > 0) {
            qreal fretNumMag = score()->styleD(Sid::fretNumMag);
            scaledFont.setPointSizeF(scaledFont.pointSizeF() * fretNumMag);
            painter->setFont(scaledFont);
            if (_numPos == 0) {
                  painter->drawText(QRectF(-stringDist *.4, .0, .0, fretDist),
                     Qt::AlignVCenter|Qt::AlignRight|Qt::TextDontClip,
                     QString("%1").arg(_fretOffset+1));
                  }
            else {
                  painter->drawText(QRectF(x2 + (stringDist * 0.4), .0, .0, fretDist),
                     Qt::AlignVCenter|Qt::AlignLeft|Qt::TextDontClip,
                     QString("%1").arg(_fretOffset+1));
                  }
            painter->setFont(font);
            }

      // NOTE:JT possible future todo - draw fingerings
      }

//---------------------------------------------------------
//   layout
//---------------------------------------------------------

void FretDiagram::layout()
      {
      qreal _spatium  = spatium() * _userMag;
      stringLw        = _spatium * 0.08;
      nutLw           = (_fretOffset || !_showNut) ? stringLw : _spatium * 0.2;
      stringDist      = score()->styleP(Sid::fretStringSpacing) * _userMag;
      fretDist        = score()->styleP(Sid::fretFretSpacing) * _userMag;

      qreal w    = stringDist * (_strings - 1);
      qreal h    = _frets * fretDist + fretDist * .5;
      qreal y    = 0.0;
      qreal dotd = _spatium * .49 * score()->styleD(Sid::fretDotSize);
      qreal x    = -((dotd+stringLw) * .5);
      w         += dotd + stringLw;

      // Always allocate space for markers
      QFont scaledFont(font);
      scaledFont.setPointSize(font.pointSize() * _userMag);
      QFontMetricsF fm(scaledFont, MScore::paintDevice());
      y  = -(fretDist * .1 + fm.height());
      h -= y;

      if (_fretOffset > 0) {
            qreal fretNumMag = score()->styleD(Sid::fretNumMag);
            scaledFont.setPointSizeF(scaledFont.pointSizeF() * fretNumMag);
            QFontMetricsF fm2(scaledFont, MScore::paintDevice());
            qreal numw = fm2.width(QString("%1").arg(_fretOffset+1));
            qreal xdiff = numw + stringDist * .4;
            w += xdiff;
            x += _numPos == 0 ? -xdiff : 0;
            }

      bbox().setRect(x, y, w, h);

      setPos(-_spatium, -h - styleP(Sid::fretY) + _spatium );

      if (!parent() || !parent()->isSegment()) {
            setPos(QPointF());
            return;
            }
      autoplaceSegmentElement();

      // don't display harmony in palette
      if (!parent())
            return;

      if (_harmony)
            _harmony->layout();
      if (_harmony && _harmony->autoplace() && _harmony->parent()) {
            Segment* s = toSegment(parent());
            Measure* m = s->measure();
            int si     = staffIdx();

            SysStaff* ss = m->system()->staff(si);
            QRectF r     = _harmony->bbox().translated(m->pos() + s->pos() + pos() + _harmony->pos());

            qreal minDistance = _harmony->minDistance().val() * spatium();
            SkylineLine sk(false);
            sk.add(r.x(), r.bottom(), r.width());
            qreal d = sk.minDistance(ss->skyline().north());
            if (d > -minDistance) {
                  qreal yd = d + minDistance;
                  yd *= -1.0;
                  _harmony->rypos() += yd;
                  r.translate(QPointF(0.0, yd));
                  }
            if (_harmony->addToSkyline())
                  ss->skyline().add(r);
            }
      }

//---------------------------------------------------------
//   centerX
///   used by harmony for layout. Keep in sync with layout, same dotd and x as above
//---------------------------------------------------------

qreal FretDiagram::centerX() const
      {
      qreal dotd = spatium() * _userMag * .49 * score()->styleD(Sid::fretDotSize);
      qreal x    = -((dotd+stringLw) * .5);
      return bbox().right() * .5 + x;
      }

//---------------------------------------------------------
//   write
//    NOTICE: if you are looking to change how fret diagrams are
//    written, edit the writeNew function. writeOld is purely compatability.
//---------------------------------------------------------

static const std::array<Pid, 7> pids { {
      Pid::MIN_DISTANCE,
      Pid::FRET_OFFSET,
      Pid::FRET_FRETS,
      Pid::FRET_STRINGS,
      Pid::FRET_NUT,
      Pid::MAG,
      Pid::FRET_NUM_POS
      } };

void FretDiagram::write(XmlWriter& xml) const
      {
      if (!xml.canWrite(this))
            return;
      xml.stag(this);

      // Write properties first and only once
      for (Pid p : pids) {
            writeProperty(xml, p);
            }
      Element::writeProperties(xml);

      if (_harmony)
            _harmony->write(xml);

      // Lowercase f indicates new writing format
      // TODO: in the next score format version (4) use only write new + props and discard
      // the compatability writing.
      xml.stag("fretDiagram");
      writeNew(xml);
      xml.etag();

      writeOld(xml);
      xml.etag();
      }

//---------------------------------------------------------
//   writeOld
//    This is the old method of writing. This is for backwards
//    compatability with < 3.1 versions.
//---------------------------------------------------------

void FretDiagram::writeOld(XmlWriter& xml) const
      {
      int lowestDotFret = -1;
      int furthestLeftLowestDot = -1;

      // Do some checks for details needed for checking whether to add barres
      for (int i = 0; i < _strings; ++i) {
            std::vector<FretItem::Dot> allDots = dot(i);

            bool dotExists = false;
            for (auto const& d : allDots) {
                  if (d.exists()) {
                        dotExists = true;
                        break;
                        }
                  }

            if (!dotExists)
                  continue;

            for (auto const& d : allDots) {
                  if (d.exists()) {
                        if (d.fret < lowestDotFret || lowestDotFret == -1) {
                              lowestDotFret = d.fret;
                              furthestLeftLowestDot = i;
                              }
                        else if (d.fret == lowestDotFret && (i < furthestLeftLowestDot || furthestLeftLowestDot == -1)) {
                              furthestLeftLowestDot = i;
                              }
                        }
                  }
            }

      // The old system writes a barre as a bool, which causes no problems in any way, not at all.
      // So, only write that if the barre is on the lowest fret with a dot,
      // and there are no other dots on its fret, and it goes all the way to the right.
      int barreStartString = -1;
      int barreFret = -1;
      for (auto const& i : _barres) {
            FretItem::Barre b = i.second;
            if (b.exists()) {
                  int fret = i.first;
                  if (fret <= lowestDotFret && b.endString == -1 && !(fret == lowestDotFret && b.startString > furthestLeftLowestDot)) {
                        barreStartString = b.startString;
                        barreFret = fret;
                        break;
                        }
                  }
            }

      for (int i = 0; i < _strings; ++i) {
            FretItem::Marker m = marker(i);
            std::vector<FretItem::Dot> allDots = dot(i);

            bool dotExists = false;
            for (auto const& d : allDots) {
                  if (d.exists()) {
                        dotExists = true;
                        break;
                        }
                  }

            if (!dotExists && !m.exists() && i != barreStartString)
                  continue;

            xml.stag(QString("string no=\"%1\"").arg(i));

            if (m.exists())
                  xml.tag("marker", FretItem::markerToChar(m.mtype).unicode());

            for (auto const& d : allDots) {
                  if (d.exists() && !(i == barreStartString && d.fret == barreFret)) {
                        xml.tag("dot", d.fret);
                        }
                  }

            // Add dot so barre will display in pre-3.1
            if (barreStartString == i) {
                  xml.tag("dot", barreFret);
                  }

            xml.etag();
            }

      if (barreFret > 0)
            xml.tag("barre", 1);
      }

//---------------------------------------------------------
//   writeNew
//    This is the important one for 3.1+
//---------------------------------------------------------

void FretDiagram::writeNew(XmlWriter& xml) const
      {
      for (int i = 0; i < _strings; ++i) {
            FretItem::Marker m = marker(i);
            std::vector<FretItem::Dot> allDots = dot(i);

            bool dotExists = false;
            for (auto const& d : allDots) {
                  if (d.exists()) {
                        dotExists = true;
                        break;
                        }
                  }

            // Only write a string if we have anything to write
            if (!dotExists && !m.exists())
                  continue;

            // Start the string writing
            xml.stag(QString("string no=\"%1\"").arg(i));

            // Write marker
            if (m.exists())
                  xml.tag("marker", FretItem::markerTypeToName(m.mtype));

            // Write any dots
            for (auto const& d : allDots) {
                  if (d.exists()) {
                        // TODO: write fingering
                        xml.tag(QString("dot fret=\"%1\"").arg(d.fret), FretItem::dotTypeToName(d.dtype));
                        }
                  }

            xml.etag();
            }

      for (int f = 1; f <= _frets; ++f) {
            FretItem::Barre b = barre(f);
            if (!b.exists())
                  continue;

            xml.tag(QString("barre start=\"%1\" end=\"%2\"").arg(b.startString).arg(b.endString), f);
            }
      }

//---------------------------------------------------------
//   read
//---------------------------------------------------------

void FretDiagram::read(XmlReader& e)
      {
      // Read the old format first
      bool hasBarre = false;
      bool haveReadNew = false;

      while (e.readNextStartElement()) {
            const QStringRef& tag(e.name());

            // Check for new format fret diagram
            if (haveReadNew) {
                  e.skipCurrentElement();
                  continue;
                  }
            if (tag == "fretDiagram") {
                  readNew(e);
                  haveReadNew = true;       
                  }
            
            // Check for new properties
            else if (tag == "showNut")
                  readProperty(e, Pid::FRET_NUT);

            // Then read the rest if there is no new format diagram (compatability read)
            else if (tag == "strings")
                  readProperty(e, Pid::FRET_STRINGS);
            else if (tag == "frets")
                  readProperty(e, Pid::FRET_FRETS);
            else if (tag == "fretOffset")
                  readProperty(e, Pid::FRET_OFFSET);
            else if (tag == "string") {
                  int no = e.intAttribute("no");
                  while (e.readNextStartElement()) {
                        const QStringRef& t(e.name());
                        if (t == "dot")
                              setDot(no, e.readInt());
                        else if (t == "marker")
                              setMarker(no, QChar(e.readInt()) == 'X' ? FretMarkerType::CROSS : FretMarkerType::CIRCLE);
                        /*else if (t == "fingering")
                              setFingering(no, e.readInt());*/
                        else
                              e.unknown();
                        }
                  }
            else if (tag == "barre")
                  hasBarre = e.readBool();
            else if (tag == "mag")
                  readProperty(e, Pid::MAG);
            else if (tag == "Harmony") {
                  Harmony* h = new Harmony(score());
                  h->read(e);
                  add(h);
                  }
            else if (!Element::readProperties(e))
                  e.unknown();
            }

      // Old handling of barres
      if (hasBarre) {
            for (int s = 0; s < _strings; ++s) {
                  for (auto& d : dot(s)) {
                        if (d.exists()) {
                              setBarre(s, -1, d.fret);
                              return;
                              }
                        }
                  }
            }
      }

//---------------------------------------------------------
//   readNew
//    read the new 'fretDiagram' tag
//---------------------------------------------------------

void FretDiagram::readNew(XmlReader& e)
      {
      while (e.readNextStartElement()) {
            const QStringRef& tag(e.name());

            if (tag == "string") {
                  int no = e.intAttribute("no");
                  while (e.readNextStartElement()) {
                        const QStringRef& t(e.name());
                        if (t == "dot") {
                              int fret = e.intAttribute("fret", 0);
                              FretDotType dtype = FretItem::nameToDotType(e.readElementText());
                              setDot(no, fret, true, dtype);
                              }
                        else if (t == "marker") {
                              FretMarkerType mtype = FretItem::nameToMarkerType(e.readElementText());
                              setMarker(no, mtype);
                              }
                        else if (t == "fingering") {
                              e.readElementText();
                              /*setFingering(no, e.readInt()); NOTE:JT todo */
                              }
                        else
                              e.unknown();
                        }
                  }
            else if (tag == "barre") {
                  int start = e.intAttribute("start", -1);
                  int end = e.intAttribute("end", -1);
                  int fret = e.readInt();

                  setBarre(start, end, fret);
                  }
            else if (!Element::readProperties(e))
                  e.unknown();
            }
      }

//---------------------------------------------------------
//   setDot
//    take a fret value of 0 to mean remove the dot, except with add
//    where we actually need to pass a fret val.
//---------------------------------------------------------

void FretDiagram::setDot(int string, int fret, bool add /*= false*/, FretDotType dtype /*= FretDotType::NORMAL*/)
      {
      if (fret == 0)
            removeDot(string, fret);
      else if (string >= 0 && string < _strings) {
            // Special case - with add, if there is a dot in the position, remove it
            // If not, add it.
            if (add) {
                  if (dot(string, fret)[0].exists()) {
                        removeDot(string, fret);
                        return;     // We are done here, all we needed to do was remove a single dot
                        }
                  }
            else
                  _dots[string].clear();

            _dots[string].push_back(FretItem::Dot(fret, dtype));
            setMarker(string, FretMarkerType::NONE);
            }
      }

//---------------------------------------------------------
//   setMarker
//    Remove any dots and barres if the marker is being set to anything other than none.
//---------------------------------------------------------

void FretDiagram::setMarker(int string, FretMarkerType mtype)
      {
      if (string >= 0 && string < _strings) {
            _markers[string] = FretItem::Marker(mtype);
            if (mtype != FretMarkerType::NONE) {
                  removeDot(string);
                  removeBarres(string);
                  }
            }
      }

//---------------------------------------------------------
//   setFingering
//    NOTE:JT: todo possible future feature
//---------------------------------------------------------

#if 0
void FretDiagram::setFingering(int string, int finger)
      {
      if (_dots.find(string) != _dots.end()) {
            _dots[string].fingering = finger;
            qDebug("set finger: s %d finger %d", string, finger);
            }
      }
#endif

//---------------------------------------------------------
//   setBarre
//    We'll accept a value of -1 for the end string, to denote
//    that the barre goes as far right as possible.
//    Take a start string value of -1 to mean 'remove this barre'
//---------------------------------------------------------

void FretDiagram::setBarre(int startString, int endString, int fret)
      {
      if (startString == -1)
            removeBarre(fret);
      else if (startString >= 0 && endString >= -1 && startString < _strings && endString < _strings)
            _barres[fret] = FretItem::Barre(startString, endString);
      }

//---------------------------------------------------------
//    This version is for clicks on a dot with shift.
//    If there is no barre at fret, then add one with the string as the start.
//    If there is a barre with a -1 end string, set the end string to string.
//    If there is a barre with a set start and end, remove it.
//    Add may be used in the future if we decide to add dots as default with barres.
//---------------------------------------------------------

void FretDiagram::setBarre(int string, int fret, bool add /*= false*/)
      {
      Q_UNUSED(add);

      FretItem::Barre b = barre(fret);
      if (!b.exists()) {
            if (string < _strings - 1) {
                  _barres[fret] = FretItem::Barre(string, -1);
                  removeDotsMarkers(string, -1, fret);
                  }
            } 
      else if (b.endString == -1 && b.startString < string) {
            _barres[fret].endString = string;
            }
      else {
            removeDotsMarkers(b.startString, b.endString, fret);
            removeBarre(fret);
            }
      }

//---------------------------------------------------------
//   undoSetFretDot
//---------------------------------------------------------

void FretDiagram::undoSetFretDot(int _string, int _fret, bool _add /*= true*/, FretDotType _dtype /*= FretDotType::NORMAl*/)
      {
      for (ScoreElement* e : linkList()) {
            FretDiagram* fd = toFretDiagram(e);
            fd->score()->undo(new FretDot(fd, _string, _fret, _add, _dtype));
            }
      }

//---------------------------------------------------------
//   undoSetFretMarker
//---------------------------------------------------------

void FretDiagram::undoSetFretMarker(int _string, FretMarkerType _mtype)
      {
      for (ScoreElement* e : linkList()) {
            FretDiagram* fd = toFretDiagram(e);
            fd->score()->undo(new FretMarker(fd, _string, _mtype));
            }
      }

//---------------------------------------------------------
//   undoSetFretBarre
//    add refers to using multiple dots per string when adding dots automatically
//---------------------------------------------------------

void FretDiagram::undoSetFretBarre(int _string, int _fret, bool _add /*= false*/)
      {
      for (ScoreElement* e : linkList()) {
            FretDiagram* fd = toFretDiagram(e);
            fd->score()->undo(new FretBarre(fd, _string, _fret, _add));
            }
      }

//---------------------------------------------------------
//   removeBarre
//    Remove a barre on a given fret.
//---------------------------------------------------------

void FretDiagram::removeBarre(int f)
      {
      _barres.erase(f);
      }

//---------------------------------------------------------
//   removeBarres
//    Remove barres crossing a certain point. Fret of 0 means any point along
//    the string.
//---------------------------------------------------------

void FretDiagram::removeBarres(int string, int fret /*= 0*/)
      {
      auto iter = _barres.begin();
      while (iter != _barres.end()) {
            int bfret = iter->first;
            FretItem::Barre b = iter->second;

            if (b.exists() && b.startString <= string && (b.endString >= string || b.endString == -1)) {
                  if (fret > 0 && fret != bfret)
                        ++iter;
                  else
                        iter = _barres.erase(iter);
                  }
            else
                  ++iter;
            }
      }   

//---------------------------------------------------------
//   removeMarker
//---------------------------------------------------------

void FretDiagram::removeMarker(int s)
      {
      auto it = _markers.find(s);
      _markers.erase(it);
      }

//---------------------------------------------------------
//   removeDot
//    take a fret value of 0 to mean remove all dots
//---------------------------------------------------------

void FretDiagram::removeDot(int s, int f /*= 0*/)
      {
      if (f > 0) {
            std::vector<FretItem::Dot> tempDots;
            for (auto const& d : dot(s)) {
                  if (d.exists() && d.fret != f)
                        tempDots.push_back(FretItem::Dot(d));
                  }

            _dots[s] = tempDots;
            }
      else
            _dots[s].clear();

      if (_dots[s].size() == 0) {
            auto it = _dots.find(s);
            _dots.erase(it);
            }
      }

//---------------------------------------------------------
//   removeDotsMarkers
//    removes all markers between [ss, es] and dots between [ss, es],
//    where the dots have a fret of fret.
//---------------------------------------------------------

void FretDiagram::removeDotsMarkers(int ss, int es, int fret)
      {
      if (ss == -1)
            return;

      int end = es == -1 ? _strings : es;
      for (int string = ss; string <= end; ++string) {
            removeDot(string, fret);

            if (marker(string).exists())
                  removeMarker(string);
            }
      }

//---------------------------------------------------------
//   clear
//---------------------------------------------------------

void FretDiagram::clear()
      {
      _barres.clear();
      _dots.clear();
      _markers.clear();
      }

//---------------------------------------------------------
//   undoFretClear
//---------------------------------------------------------

void FretDiagram::undoFretClear()
      {
      for (ScoreElement* e : linkList()) {
            FretDiagram* fd = toFretDiagram(e);
            fd->score()->undo(new FretClear(fd));
            }
      }

//---------------------------------------------------------
//   dot
//    take fret value of zero to mean all dots 
//---------------------------------------------------------

std::vector<FretItem::Dot> FretDiagram::dot(int s, int f /*= 0*/) const
      {
      if (_dots.find(s) != _dots.end()) {
            if (f != 0) {
                  for (auto const& d : _dots.at(s)) {
                        if (d.fret == f)
                              return std::vector<FretItem::Dot> { FretItem::Dot(d) };
                        }
                  }
            else
                  return _dots.at(s);
            }
      return std::vector<FretItem::Dot> { FretItem::Dot(0) };
      }

//---------------------------------------------------------
//   marker
//---------------------------------------------------------

FretItem::Marker FretDiagram::marker(int s) const
      {
      if (_markers.find(s) != _markers.end())
            return _markers.at(s);
      return FretItem::Marker(FretMarkerType::NONE);
      }

//---------------------------------------------------------
//   barre
//---------------------------------------------------------

FretItem::Barre FretDiagram::barre(int f) const
      {
      if (_barres.find(f) != _barres.end())
            return _barres.at(f);
      return FretItem::Barre(-1, -1);
      }

//---------------------------------------------------------
//   setHarmony
///   if this is being done by the user, use undoSetHarmony instead
//---------------------------------------------------------

void FretDiagram::setHarmony(QString harmonyText)
      {
      if (!_harmony) {
            Harmony* h = new Harmony(score());
            add(h);
            }

      _harmony->setHarmony(harmonyText);
      _harmony->setXmlText(_harmony->harmonyName());
      triggerLayout();
      }

//---------------------------------------------------------
//   add
//---------------------------------------------------------

void FretDiagram::add(Element* e)
      {
      e->setParent(this);
      if (e->isHarmony()) {
            _harmony = toHarmony(e);
            _harmony->setTrack(track());
            _harmony->resetProperty(Pid::OFFSET);
            }
      else
            qWarning("FretDiagram: cannot add <%s>\n", e->name());
      }

//---------------------------------------------------------
//   remove
//---------------------------------------------------------

void FretDiagram::remove(Element* e)
      {
      if (e == _harmony)
            _harmony = 0;
      else
            qWarning("FretDiagram: cannot remove <%s>\n", e->name());
      }

//---------------------------------------------------------
//   acceptDrop
//---------------------------------------------------------

bool FretDiagram::acceptDrop(EditData& data) const
      {
      return data.dropElement->type() == ElementType::HARMONY;
      }

//---------------------------------------------------------
//   drop
//---------------------------------------------------------

Element* FretDiagram::drop(EditData& data)
      {
      Element* e = data.dropElement;
      if (e->isHarmony()) {
            Harmony* h = toHarmony(e);
            h->setParent(parent());
            h->setTrack(track());
            score()->undoAddElement(h);
            }
      else {
            qWarning("FretDiagram: cannot drop <%s>\n", e->name());
            delete e;
            e = 0;
            }
      return e;
      }

//---------------------------------------------------------
//   scanElements
//---------------------------------------------------------

void FretDiagram::scanElements(void* data, void (*func)(void*, Element*), bool all)
      {
      Q_UNUSED(all);
      func(data, this);
      // don't display harmony in palette
      if (_harmony && !!parent())
            func(data, _harmony);
      }

//---------------------------------------------------------
//   Write MusicXML
//---------------------------------------------------------

void FretDiagram::writeMusicXML(XmlWriter& xml) const
      {
      qDebug("FretDiagram::writeMusicXML() this %p harmony %p", this, _harmony);
      xml.stag("frame");
      xml.tag("frame-strings", _strings);
      xml.tag("frame-frets", frets());
      QString strDots = "'";
      QString strMarker = "'";
      QString strFingering = "'";

      for (int i = 0; i < _strings; ++i) {
            int mxmlString = _strings - i;

            std::vector<int> bStarts;
            std::vector<int> bEnds;
            for (auto const& j : _barres) {
                  FretItem::Barre b = j.second;
                  int fret = j.first;
                  if (!b.exists())
                        continue;

                  if (b.startString == i)
                        bStarts.push_back(fret);
                  else if (b.endString == i || (b.endString == -1 && mxmlString == 1))
                        bEnds.push_back(fret);
                  }

            if (marker(i).exists() && marker(i).mtype == FretMarkerType::CIRCLE) {
                  xml.stag("frame-note");
                  xml.tag("string", mxmlString);
                  xml.tag("fret", "0");
                  xml.etag();
                  }
            else {
                  // Write dots
                  for (auto const& d : dot(i)) {
                        if (!d.exists())
                              continue;
                        xml.stag("frame-note");
                        xml.tag("string", mxmlString);
                        xml.tag("fret", d.fret);
                        // TODO: write fingerings

                        // Also write barre if it starts at this dot
                        if (std::find(bStarts.begin(), bStarts.end(), d.fret) != bStarts.end()) {
                              xml.tagE("barre type=\"start\"");
                              bStarts.erase(std::remove(bStarts.begin(), bStarts.end(), d.fret), bStarts.end());
                              }
                        if (std::find(bEnds.begin(), bEnds.end(), d.fret) != bEnds.end()) {
                              xml.tagE("barre type=\"stop\"");
                              bEnds.erase(std::remove(bEnds.begin(), bEnds.end(), d.fret), bEnds.end());
                              }
                        xml.etag();
                        }
                  }

            // Write unwritten barres
            for (int j : bStarts) {
                  xml.stag("frame-note");
                  xml.tag("string", mxmlString);
                  xml.tag("fret", j);
                  xml.tagE("barre type=\"start\"");
                  xml.etag();
                  }

            for (int j : bEnds) {
                  xml.stag("frame-note");
                  xml.tag("string", mxmlString);
                  xml.tag("fret", j);
                  xml.tagE("barre type=\"stop\"");
                  xml.etag();
                  }
            }

      xml.etag();
      }

//---------------------------------------------------------
//   getProperty
//---------------------------------------------------------

QVariant FretDiagram::getProperty(Pid propertyId) const
      {
      switch (propertyId) {
            case Pid::MAG:
                  return userMag();
            case Pid::FRET_STRINGS:
                  return strings();
            case Pid::FRET_FRETS:
                  return frets();
            case Pid::FRET_NUT:
                  return showNut();
            case Pid::FRET_OFFSET:
                  return fretOffset();
            case Pid::FRET_NUM_POS:
                  return _numPos;
            default:
                  return Element::getProperty(propertyId);
            }
      }

//---------------------------------------------------------
//   setProperty
//---------------------------------------------------------

bool FretDiagram::setProperty(Pid propertyId, const QVariant& v)
      {
      switch (propertyId) {
            case Pid::MAG:
                  setUserMag(v.toDouble());
                  break;
            case Pid::FRET_STRINGS:
                  setStrings(v.toInt());
                  break;
            case Pid::FRET_FRETS:
                  setFrets(v.toInt());
                  break;
            case Pid::FRET_NUT:
                  setShowNut(v.toBool());
                  break;
            case Pid::FRET_OFFSET:
                  setFretOffset(v.toInt());
                  break;
            case Pid::FRET_NUM_POS:
                  _numPos = v.toInt();
                  break;
            default:
                  return Element::setProperty(propertyId, v);
            }
      triggerLayout();
      return true;
      }

//---------------------------------------------------------
//   propertyDefault
//---------------------------------------------------------

QVariant FretDiagram::propertyDefault(Pid pid) const
      {
      // We shouldn't style the fret offset
      if (pid == Pid::FRET_OFFSET) {
            return QVariant(0);
            }

      for (const StyledProperty& p : *styledProperties()) {
            if (p.pid == pid) {
                  if (propertyType(pid) == P_TYPE::SP_REAL)
                        return score()->styleP(p.sid);
                  return score()->styleV(p.sid);
                  }
            }
      return Element::propertyDefault(pid);
      }


//---------------------------------------------------------
//   markerToChar
//---------------------------------------------------------

QChar FretItem::markerToChar(FretMarkerType t)
      {
      switch (t) {
            case FretMarkerType::CIRCLE:
                  return QChar('O');
            case FretMarkerType::CROSS:
                  return QChar('X');
            case FretMarkerType::NONE:
            default:
                  return QChar();
            }
      }

//---------------------------------------------------------
//   markerTypeToName
//---------------------------------------------------------

const std::vector<FretItem::MarkerTypeNameItem> FretItem::markerTypeNameMap = {
      { FretMarkerType::CIRCLE,     "circle"    },
      { FretMarkerType::CROSS,      "cross"     },
      { FretMarkerType::NONE,       "none"      }
      };

QString FretItem::markerTypeToName(FretMarkerType t)
      {
      for (auto i : FretItem::markerTypeNameMap) {
            if (i.mtype == t)
                  return i.name;
            }
      qFatal("Unrecognised FretMarkerType!");
      return QString();       // prevent compiler warnings
      }

//---------------------------------------------------------
//   nameToMarkerType
//---------------------------------------------------------

FretMarkerType FretItem::nameToMarkerType(QString n)
      {
      for (auto i : FretItem::markerTypeNameMap) {
            if (i.name == n)
                  return i.mtype;
            }
      qWarning("Unrecognised marker name!");
      return FretMarkerType::NONE;       // default
      }

//---------------------------------------------------------
//   dotTypeToName
//---------------------------------------------------------

const std::vector<FretItem::DotTypeNameItem> FretItem::dotTypeNameMap = {
      { FretDotType::NORMAL,        "normal"    },
      { FretDotType::CROSS,         "cross"     },
      { FretDotType::SQUARE,        "square"    },
      { FretDotType::TRIANGLE,      "triangle"  },
      };

QString FretItem::dotTypeToName(FretDotType t)
      {
      for (auto i : FretItem::dotTypeNameMap) {
            if (i.dtype == t)
                  return i.name;
            }
      qFatal("Unrecognised FretDotType!");
      return QString();       // prevent compiler warnings
      }

//---------------------------------------------------------
//   nameToDotType
//---------------------------------------------------------

FretDotType FretItem::nameToDotType(QString n)
      {
      for (auto i : FretItem::dotTypeNameMap) {
            if (i.name == n)
                  return i.dtype;
            }
      qWarning("Unrecognised dot name!");
      return FretDotType::NORMAL;       // default
      }

//---------------------------------------------------------
//   updateStored
//---------------------------------------------------------

FretUndoData::FretUndoData(FretDiagram* fd)
      {
      // We need to store the old barres and markers, since predicting how
      // adding dots, markers, barres etc. will change things is too difficult.
      // Update linked fret diagrams:
      _diagram = fd;
      _dots = _diagram->_dots;
      _markers = _diagram->_markers;
      _barres = _diagram->_barres;
      }

//---------------------------------------------------------
//   updateDiagram
//---------------------------------------------------------

void FretUndoData::updateDiagram()
      {
      if (!_diagram) {
            qFatal("Tried to undo fret diagram change without ever setting diagram!");
            return;
            }

      // Reset every fret diagram property of the changed diagram
      // FretUndoData is a friend of FretDiagram so has access to these private members
      _diagram->_barres = _barres;
      _diagram->_markers = _markers;
      _diagram->_dots = _dots;
      }

}