/
importmxmlpass2.cpp
5977 lines (5280 loc) · 230 KB
/
importmxmlpass2.cpp
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
//=============================================================================
// MuseScore
// Linux Music Score Editor
//
// Copyright (C) 2015 Werner Schweer and others
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//=============================================================================
#include "libmscore/arpeggio.h"
#include "libmscore/accidental.h"
#include "libmscore/breath.h"
#include "libmscore/chord.h"
#include "libmscore/chordline.h"
#include "libmscore/chordlist.h"
#include "libmscore/chordrest.h"
#include "libmscore/drumset.h"
#include "libmscore/dynamic.h"
#include "libmscore/figuredbass.h"
#include "libmscore/fingering.h"
#include "libmscore/fret.h"
#include "libmscore/glissando.h"
#include "libmscore/hairpin.h"
#include "libmscore/harmony.h"
#include "libmscore/instrchange.h"
#include "libmscore/interval.h"
#include "libmscore/jump.h"
#include "libmscore/keysig.h"
#include "libmscore/lyrics.h"
#include "libmscore/marker.h"
#include "libmscore/measure.h"
#include "libmscore/mscore.h"
#include "libmscore/note.h"
#include "libmscore/part.h"
#include "libmscore/pedal.h"
#include "libmscore/rest.h"
#include "libmscore/slur.h"
#include "libmscore/staff.h"
#include "libmscore/stafftext.h"
#include "libmscore/sym.h"
#include "libmscore/tempotext.h"
#include "libmscore/tie.h"
#include "libmscore/timesig.h"
#include "libmscore/tremolo.h"
#include "libmscore/trill.h"
#include "libmscore/utils.h"
#include "libmscore/volta.h"
#include "libmscore/textline.h"
#include "importmxmlpass2.h"
#include "musicxmlfonthandler.h"
#include "musicxmlsupport.h"
#include "preferences.h"
namespace Ms {
//---------------------------------------------------------
// local defines for debug output
//---------------------------------------------------------
//#define DEBUG_VOICE_MAPPER true
//---------------------------------------------------------
// support enums / structs / classes
//---------------------------------------------------------
//---------------------------------------------------------
// MusicXmlTupletDesc
//---------------------------------------------------------
MusicXmlTupletDesc::MusicXmlTupletDesc()
: type(MxmlStartStop::NONE), placement(Element::Placement::BELOW),
bracket(Tuplet::BracketType::AUTO_BRACKET), shownumber(Tuplet::NumberType::SHOW_NUMBER)
{
// nothing
}
//---------------------------------------------------------
// MusicXmlLyricsExtend
//---------------------------------------------------------
//---------------------------------------------------------
// init
//---------------------------------------------------------
void MusicXmlLyricsExtend::init()
{
_lyrics.clear();
}
//---------------------------------------------------------
// addLyric
//---------------------------------------------------------
// add a single lyric to be extended later
// called when lyric with "extend" or "extend type=start" is found
void MusicXmlLyricsExtend::addLyric(Lyrics* const lyric)
{
_lyrics.insert(lyric);
}
//---------------------------------------------------------
// lastChordTicks
//---------------------------------------------------------
// find the duration of the chord starting at or after s in track and ending at tick
static int lastChordTicks(const Segment* s, const int track, const int tick)
{
while (s && s->tick() < tick) {
Element* el = s->element(track);
if (el && el->isChordRest()) {
ChordRest* cr = static_cast<ChordRest*>(el);
if (cr->tick() + cr->actualTicks() == tick)
return cr->actualTicks();
}
s = s->nextCR(track, true);
}
return 0;
}
//---------------------------------------------------------
// setExtend
//---------------------------------------------------------
// set extend for lyric no in track to end at tick
// called when lyric (with or without "extend") or note with "extend type=stop" is found
// note that no == -1 means all lyrics in this track
void MusicXmlLyricsExtend::setExtend(const int no, const int track, const int tick)
{
QList<Lyrics*> list;
foreach(Lyrics* l, _lyrics) {
Element* const el = l->parent();
if (el->type() == Element::Type::CHORD) { // TODO: rest also possible ?
ChordRest* const par = static_cast<ChordRest*>(el);
if (par->track() == track && (no == -1 || l->no() == no)) {
int lct = lastChordTicks(l->segment(), track, tick);
if (lct > 0) {
// set lyric tick to the total length fron the lyric note
// plus all notes covered by the melisma minus the last note length
l->setTicks(tick - par->tick() - lct);
}
list.append(l);
}
}
}
// cleanup
foreach(Lyrics* l, list) {
_lyrics.remove(l);
}
}
//---------------------------------------------------------
// noteTypeToFraction
//---------------------------------------------------------
/**
Convert MusicXML note type to fraction.
*/
static Fraction noteTypeToFraction(const QString& type)
{
if (type == "1024th")
return Fraction(1, 1024);
else if (type == "512th")
return Fraction(1, 512);
else if (type == "256th")
return Fraction(1, 256);
else if (type == "128th")
return Fraction(1, 128);
else if (type == "64th")
return Fraction(1, 64);
else if (type == "32nd")
return Fraction(1, 32);
else if (type == "16th")
return Fraction(1, 16);
else if (type == "eighth")
return Fraction(1, 8);
else if (type == "quarter")
return Fraction(1, 4);
else if (type == "half")
return Fraction(1, 2);
else if (type == "whole")
return Fraction(1, 1);
else if (type == "breve")
return Fraction(2, 1);
else if (type == "long")
return Fraction(4, 1);
else if (type == "maxima")
return Fraction(8, 1);
else
return Fraction(0, 0);
}
//---------------------------------------------------------
// calculateFraction
//---------------------------------------------------------
/**
Convert note type, number of dots and actual and normal notes into a duration
*/
static Fraction calculateFraction(const QString& type, const int dots, const Fraction timeMod)
{
// type
Fraction f = noteTypeToFraction(type);
if (f.isValid()) {
// dot(s)
Fraction f_no_dots = f;
for (int i = 0; i < dots; ++i)
f += (f_no_dots / (2 << i));
// tuplet
if (timeMod.isValid())
f *= timeMod;
// clean up (just in case)
f.reduce();
}
return f;
}
//---------------------------------------------------------
// MusicXMLStepAltOct2Pitch
//---------------------------------------------------------
/**
Convert MusicXML \a step (0=C, 1=D, etc.) / \a alter / \a octave to midi pitch.
Note: same code is in pass 1 and in pass 2.
TODO: combine
*/
static int MusicXMLStepAltOct2Pitch(int step, int alter, int octave)
{
// c d e f g a b
static int table[7] = { 0, 2, 4, 5, 7, 9, 11 };
if (step < 0 || step > 6) {
qDebug("MusicXMLStepAltOct2Pitch: illegal step %d", step);
return -1;
}
int pitch = table[step] + alter + (octave+1) * 12;
if (pitch < 0)
pitch = -1;
if (pitch > 127)
pitch = -1;
return pitch;
}
//---------------------------------------------------------
// xmlSetPitch
//---------------------------------------------------------
/**
Convert MusicXML \a step / \a alter / \a octave to midi pitch,
set pitch and tpc.
Note that n's staff and track have not been set yet
*/
static void xmlSetPitch(Note* n, int step, int alter, int octave, const int octaveShift, const Instrument* instr)
{
//qDebug("xmlSetPitch(n=%p, step=%d, alter=%d, octave=%d, octaveShift=%d)",
// n, step, alter, octave, octaveShift);
//const Staff* staff = n->score()->staff(track / VOICES);
//const Instrument* instr = staff->part()->instr();
const Interval intval = instr->transpose(); // TODO: tick
//qDebug(" staff=%p instr=%p dia=%d chro=%d",
// staff, instr, (int) intval.diatonic, (int) intval.chromatic);
int pitch = MusicXMLStepAltOct2Pitch(step, alter, octave);
pitch += intval.chromatic; // assume not in concert pitch
pitch += 12 * octaveShift; // correct for octave shift
// ensure sane values
pitch = limit(pitch, 0, 127);
int tpc2 = step2tpc(step, AccidentalVal(alter));
int tpc1 = Ms::transposeTpc(tpc2, intval, true);
n->setPitch(pitch, tpc1, tpc2);
//qDebug(" pitch=%d tpc1=%d tpc2=%d", n->pitch(), n->tpc1(), n->tpc2());
}
//---------------------------------------------------------
// fillGap
//---------------------------------------------------------
/**
Fill one gap (tstart - tend) in this track in this measure with rest(s).
*/
static void fillGap(Measure* measure, int track, int tstart, int tend)
{
int ctick = tstart;
int restLen = tend - tstart;
// qDebug("\nfillGIFV fillGap(measure %p track %d tstart %d tend %d) restLen %d len",
// measure, track, tstart, tend, restLen);
// note: as MScore::division (#ticks in a quarter note) equals 480
// MScore::division / 64 (#ticks in a 256th note) uequals 7.5 but is rounded down to 7
while (restLen > MScore::division / 64) {
int len = restLen;
TDuration d(TDuration::DurationType::V_INVALID);
if (measure->ticks() == restLen)
d.setType(TDuration::DurationType::V_MEASURE);
else
d.setVal(len);
Rest* rest = new Rest(measure->score(), d);
rest->setDuration(Fraction::fromTicks(len));
rest->setTrack(track);
rest->setVisible(false);
Segment* s = measure->getSegment(rest, tstart);
s->add(rest);
len = rest->globalDuration().ticks();
// qDebug(" %d", len);
ctick += len;
restLen -= len;
}
}
//---------------------------------------------------------
// fillGapsInFirstVoices
//---------------------------------------------------------
/**
Fill gaps in first voice of every staff in this measure for this part with rest(s).
*/
static void fillGapsInFirstVoices(Measure* measure, Part* part)
{
Q_ASSERT(measure);
Q_ASSERT(part);
int measTick = measure->tick();
int measLen = measure->ticks();
int nextMeasTick = measTick + measLen;
int staffIdx = part->score()->staffIdx(part);
/*
qDebug("fillGIFV measure %p part %p idx %d nstaves %d tick %d - %d (len %d)",
measure, part, staffIdx, part->nstaves(),
measTick, nextMeasTick, measLen);
*/
for (int st = 0; st < part->nstaves(); ++st) {
int track = (staffIdx + st) * VOICES;
int endOfLastCR = measTick;
for (Segment* s = measure->first(); s; s = s->next()) {
// qDebug("fillGIFV segment %p tp %s", s, s->subTypeName());
Element* el = s->element(track);
if (el) {
// qDebug(" el[%d] %p", track, el);
if (s->isChordRestType()) {
ChordRest* cr = static_cast<ChordRest*>(el);
int crTick = cr->tick();
int crLen = cr->globalDuration().ticks();
int nextCrTick = crTick + crLen;
/*
qDebug(" chord/rest tick %d - %d (len %d)",
crTick, nextCrTick, crLen);
*/
if (crTick > endOfLastCR) {
/*
qDebug(" GAP: track %d tick %d - %d",
track, endOfLastCR, crTick);
*/
fillGap(measure, track, endOfLastCR, crTick);
}
endOfLastCR = nextCrTick;
}
}
}
if (nextMeasTick > endOfLastCR) {
/*
qDebug("fillGIFV measure end GAP: track %d tick %d - %d",
track, endOfLastCR, nextMeasTick);
*/
fillGap(measure, track, endOfLastCR, nextMeasTick);
}
}
}
//---------------------------------------------------------
// hasDrumset
//---------------------------------------------------------
/**
Determine if \a mxmlDrumset contains a valid drumset.
This is the case if any instrument has a midi-unpitched element,
(which stored in the MusicXMLDrumInstrument pitch field).
*/
static bool hasDrumset(const MusicXMLDrumset& mxmlDrumset)
{
bool res = false;
MusicXMLDrumsetIterator ii(mxmlDrumset);
while (ii.hasNext()) {
ii.next();
// debug: dump the drumset
//qDebug("hasDrumset: instrument: %s %s", qPrintable(ii.key()), qPrintable(ii.value().toString()));
int pitch = ii.value().pitch;
if (0 <= pitch && pitch <= 127) {
res = true;
}
}
return res;
}
//---------------------------------------------------------
// initDrumset
//---------------------------------------------------------
/**
Initialize drumset \a drumset.
*/
// determine if the part contains a drumset
// this is the case if any instrument has a midi-unpitched element,
// (which stored in the MusicXMLDrumInstrument pitch field)
// if the part contains a drumset, Drumset drumset is intialized
static void initDrumset(Drumset* drumset, const MusicXMLDrumset& mxmlDrumset)
{
drumset->clear();
MusicXMLDrumsetIterator ii(mxmlDrumset);
while (ii.hasNext()) {
ii.next();
// debug: also dump the drumset for this part
//qDebug("initDrumset: instrument: %s %s", qPrintable(ii.key()), qPrintable(ii.value().toString()));
int pitch = ii.value().pitch;
if (0 <= pitch && pitch <= 127) {
drumset->drum(ii.value().pitch)
= DrumInstrument(ii.value().name.toLatin1().constData(),
ii.value().notehead, ii.value().line, ii.value().stemDirection);
}
}
}
//---------------------------------------------------------
// setFirstInstrument
//---------------------------------------------------------
/**
Set first instrument for Part \a part
*/
static void setFirstInstrument(Part* part, const QString& partId,
const QString& instrId, const MusicXMLDrumset& mxmlDrumset)
{
if (mxmlDrumset.size() > 0) {
//qDebug("setFirstInstrument: initial instrument '%s'", qPrintable(instrId));
MusicXMLDrumInstrument instr;
if (instrId == "")
instr = mxmlDrumset.first();
else if (mxmlDrumset.contains(instrId))
instr = mxmlDrumset.value(instrId);
else {
qDebug("setFirstInstrument: initial instrument '%s' not found in part '%s'", qPrintable(instrId), qPrintable(partId)); // TODO
instr = mxmlDrumset.first();
}
part->setMidiChannel(instr.midiChannel, instr.midiPort);
part->setMidiProgram(instr.midiProgram);
part->setPan(instr.midiPan);
part->setVolume(instr.midiVolume);
part->instrument()->setTrackName(instr.name);
}
else
qDebug("setFirstInstrument: no instrument found for part '%s'", qPrintable(partId)); // TODO
}
//---------------------------------------------------------
// setStaffTypePercussion
//---------------------------------------------------------
/**
Set staff type to percussion
*/
static void setStaffTypePercussion(Part* part, Drumset* drumset)
{
for (int j = 0; j < part->nstaves(); ++j)
if (part->staff(j)->lines() == 5 && !part->staff(j)->isDrumStaff())
part->staff(j)->setStaffType(StaffType::preset(StaffTypes::PERC_DEFAULT));
// set drumset for instrument
part->instrument()->setDrumset(drumset);
part->instrument()->channel(0)->bank = 128;
part->instrument()->channel(0)->updateInitList();
}
//---------------------------------------------------------
// findDeleteStaffText
//---------------------------------------------------------
/**
Find a non-empty staff text in \a s at \a track (which originates as MusicXML <words>).
If found, delete it and return its text.
*/
static QString findDeleteStaffText(Segment* s, int track)
{
//qDebug("findDeleteWords(s %p track %d)", s, track);
foreach (Element* e, s->annotations()) {
//qDebug("findDeleteWords e %p type %hhd track %d", e, e->type(), e->track());
if (e->type() != Element::Type::STAFF_TEXT || e->track() < track || e->track() >= track+VOICES)
continue;
Text* t = static_cast<Text*>(e);
//qDebug("findDeleteWords t %p text '%s'", t, qPrintable(t->text()));
QString res = t->xmlText();
if (res != "") {
s->remove(t);
return res;
}
}
return "";
}
//---------------------------------------------------------
// setPartInstruments
//---------------------------------------------------------
static void setPartInstruments(Part* part, const QString& partId,
Score* score, const MusicXmlInstrList& il, const MusicXMLDrumset& mxmlDrumset)
{
QString prevInstrId;
for (auto it = il.cbegin(); it != il.cend(); ++it) {
Fraction f = (*it).first;
if (f == Fraction(0, 1))
prevInstrId = (*it).second; // instrument id at t = 0
else if (f > Fraction(0, 1)) {
auto instrId = (*it).second;
bool mustInsert = instrId != prevInstrId;
/*
qDebug("setPartInstruments: f %s previd %s id %s mustInsert %d",
qPrintable(f.print()),
qPrintable(prevInstrId),
qPrintable(instrId),
mustInsert);
*/
if (mustInsert) {
int staff = score->staffIdx(part);
int track = staff * VOICES;
qDebug("setPartInstruments: instrument change: tick %s (%d) track %d instr '%s'",
qPrintable(f.print()), f.ticks(), track, qPrintable(instrId));
Segment* segment = score->tick2segment(f.ticks(), true, Segment::Type::ChordRest, true);
if (!segment)
qDebug("setPartInstruments: segment for instrument change at tick %d not found", f.ticks()); // TODO
else if (!mxmlDrumset.contains(instrId))
qDebug("setPartInstruments: changed instrument '%s' at tick %d not found in part '%s'",
qPrintable(instrId), f.ticks(), qPrintable(partId)); // TODO
else {
MusicXMLDrumInstrument mxmlInstr = mxmlDrumset.value(instrId);
Instrument instr;
qDebug("setPartInstruments: instr %p", &instr);
instr.channel(0)->program = mxmlInstr.midiProgram;
instr.channel(0)->pan = mxmlInstr.midiPan;
instr.channel(0)->volume = mxmlInstr.midiVolume;
instr.setTrackName(mxmlInstr.name);
InstrumentChange* ic = new InstrumentChange(instr, score);
ic->setTrack(track);
// if there is already a staff text at this tick / track,
// delete it and use its text here instead of "Instrument"
QString text = findDeleteStaffText(segment, track);
ic->setXmlText(text.isEmpty() ? "Instrument" : text);
segment->add(ic);
int key = part->instruments()->rbegin()->first;
part->setMidiChannel(mxmlInstr.midiChannel, mxmlInstr.midiPort, key);
}
}
prevInstrId = instrId;
}
}
}
//---------------------------------------------------------
// text2syms
//---------------------------------------------------------
/**
Convert SMuFL code points to MuseScore <sym>...</sym>
*/
static QString text2syms(const QString& t)
{
//QTime time;
//time.start();
// first create a map from symbol (Unicode) text to symId
// note that this takes about 1 msec on a Core i5,
// caching does not gain much
ScoreFont* sf = ScoreFont::fallbackFont();
QMap<QString, SymId> map;
int maxStringSize = 0; // maximum string size found
for (int i = int(SymId::noSym); i < int(SymId::lastSym); ++i) {
SymId id((SymId(i)));
QString string(sf->toString(id));
// insert all syms except space to prevent matching all regular spaces
if (id != SymId::space)
map.insert(string, id);
if (string.size() > maxStringSize)
maxStringSize = string.size();
}
//qDebug("text2syms map count %d maxsz %d filling time elapsed: %d ms",
// map.size(), maxStringSize, time.elapsed());
// then look for matches
QString in = t;
QString res;
while (in != "") {
// try to find the largest match possible
int maxMatch = qMin(in.size(), maxStringSize);
QString sym;
while (maxMatch > 0) {
QString toBeMatched = in.left(maxMatch);
if (map.contains(toBeMatched)) {
sym = Sym::id2name(map.value(toBeMatched));
break;
}
maxMatch--;
}
if (maxMatch > 0) {
// found a match, add sym to res and remove match from string in
res += "<sym>";
res += sym;
res += "</sym>";
in.remove(0, maxMatch);
}
else {
// not found, move one char from res to in
res += in.left(1);
in.remove(0, 1);
}
}
//qDebug("text2syms total time elapsed: %d ms, res '%s'", time.elapsed(), qPrintable(res));
return res;
}
//---------------------------------------------------------
// decodeEntities
//---------------------------------------------------------
/**
Decode &#...; in string \a src into UNICODE (utf8) character.
*/
static QString decodeEntities( const QString& src )
{
QString ret(src);
QRegExp re("&#([0-9]+);");
re.setMinimal(true);
int pos = 0;
while ( (pos = re.indexIn(src, pos)) != -1 ) {
ret = ret.replace(re.cap(0), QChar(re.cap(1).toInt(0,10)));
pos += re.matchedLength();
}
return ret;
}
//---------------------------------------------------------
// nextPartOfFormattedString
//---------------------------------------------------------
// TODO: probably should be shared between pass 1 and 2
/**
Read the next part of a MusicXML formatted string and convert to MuseScore internal encoding.
*/
static QString nextPartOfFormattedString(QXmlStreamReader& e)
{
//QString lang = e.attribute(QString("xml:lang"), "it");
QString fontWeight = e.attributes().value("font-weight").toString();
QString fontSize = e.attributes().value("font-size").toString();
QString fontStyle = e.attributes().value("font-style").toString();
QString underline = e.attributes().value("underline").toString();
QString fontFamily = e.attributes().value("font-family").toString();
// TODO: color, enclosure, yoffset in only part of the text, ...
QString txt = e.readElementText();
// replace HTML entities
txt = decodeEntities(txt);
QString syms = text2syms(txt);
QString importedtext;
if (!fontSize.isEmpty()) {
bool ok = true;
float size = fontSize.toFloat(&ok);
if (ok)
importedtext += QString("<font size=\"%1\"/>").arg(size);
}
if (!fontFamily.isEmpty() && txt == syms) {
// add font family only if no <sym> replacement made
importedtext += QString("<font face=\"%1\"/>").arg(fontFamily);
}
if (fontWeight == "bold")
importedtext += "<b>";
if (fontStyle == "italic")
importedtext += "<i>";
if (!underline.isEmpty()) {
bool ok = true;
int lines = underline.toInt(&ok);
if (ok && (lines > 0)) // 1,2, or 3 underlines are imported as single underline
importedtext += "<u>";
else
underline = "";
}
if (txt == syms) {
txt.replace(QString("\r"), QString("")); // convert Windows line break \r\n -> \n
importedtext += txt.toHtmlEscaped();
}
else {
// <sym> replacement made, should be no need for line break or other conversions
importedtext += syms;
}
if (underline != "")
importedtext += "</u>";
if (fontStyle == "italic")
importedtext += "</i>";
if (fontWeight == "bold")
importedtext += "</b>";
//qDebug("importedtext '%s'", qPrintable(importedtext));
return importedtext;
}
//---------------------------------------------------------
// addLyric
//---------------------------------------------------------
/**
Add a single lyric to the score or delete it (if number too high)
*/
static void addLyric(ChordRest* cr, Lyrics* l, int lyricNo, MusicXmlLyricsExtend& extendedLyrics)
{
if (lyricNo > MAX_LYRICS) {
qDebug("too much lyrics (>%d)", MAX_LYRICS); // TODO
delete l;
}
else {
l->setNo(lyricNo);
cr->add(l);
extendedLyrics.setExtend(lyricNo, cr->track(), cr->tick());
}
}
//---------------------------------------------------------
// addLyrics
//---------------------------------------------------------
/**
Add a notes lyrics to the score
*/
static void addLyrics(ChordRest* cr,
QMap<int, Lyrics*>& numbrdLyrics,
QMap<int, Lyrics*>& defyLyrics,
QList<Lyrics*>& unNumbrdLyrics,
QSet<Lyrics*>& extLyrics,
MusicXmlLyricsExtend& extendedLyrics)
{
// first the lyrics with valid number
int lyricNo = -1;
for (QMap<int, Lyrics*>::const_iterator i = numbrdLyrics.constBegin(); i != numbrdLyrics.constEnd(); ++i) {
lyricNo = i.key(); // use number obtained from MusicXML file
Lyrics* l = i.value();
addLyric(cr, l, lyricNo, extendedLyrics);
if (extLyrics.contains(l))
extendedLyrics.addLyric(l);
}
// then the lyrics without valid number but with valid default-y
for (QMap<int, Lyrics*>::const_iterator i = defyLyrics.constBegin(); i != defyLyrics.constEnd(); ++i) {
lyricNo++; // use sequence number
Lyrics* l = i.value();
addLyric(cr, l, lyricNo, extendedLyrics);
if (extLyrics.contains(l))
extendedLyrics.addLyric(l);
}
// finally the remaining lyrics, which are simply added in order they appear in the MusicXML file
for (QList<Lyrics*>::const_iterator i = unNumbrdLyrics.constBegin(); i != unNumbrdLyrics.constEnd(); ++i) {
lyricNo++; // use sequence number
Lyrics* l = *i;
addLyric(cr, l, lyricNo, extendedLyrics);
if (extLyrics.contains(l))
extendedLyrics.addLyric(l);
}
}
//---------------------------------------------------------
// addElemOffset
//---------------------------------------------------------
static void addElemOffset(Element* el, int track, const QString& placement, Measure* measure, int tick)
{
/*
qDebug("addElem el %p track %d placement %s tick %d",
el, track, qPrintable(placement), tick);
*/
// calc y offset assuming five line staff and default style
// note that required y offset is element type dependent
const qreal stafflines = 5; // assume five line staff, but works OK-ish for other sizes too
qreal offsAbove = 0;
qreal offsBelow = 0;
if (el->type() == Element::Type::TEMPO_TEXT || el->type() == Element::Type::REHEARSAL_MARK) {
offsAbove = 0;
offsBelow = 8 + (stafflines - 1);
}
else if (el->type() == Element::Type::TEXT || el->type() == Element::Type::STAFF_TEXT) {
offsAbove = 0;
offsBelow = 6 + (stafflines - 1);
}
else if (el->type() == Element::Type::SYMBOL) {
offsAbove = -2;
offsBelow = 4 + (stafflines - 1);
}
else if (el->type() == Element::Type::DYNAMIC) {
offsAbove = -5.75 - (stafflines - 1);
offsBelow = -0.75;
}
else
qDebug("addElem el %p unsupported type %d",
el, int(el->type())); //TODO
// move to correct position
// TODO: handle rx, ry
qreal y = 0;
if (el->isDynamic()) {
el->setPlacement(placement == "above"
? Element::Placement::ABOVE : Element::Placement::BELOW);
}
else {
if (placement == "above")
y += offsAbove;
if (placement == "below")
y += offsBelow;
//qDebug(" y = %g", y);
y *= el->score()->spatium();
el->setUserOff(QPoint(0, y));
}
el->setTrack(track);
Segment* s = measure->getSegment(Segment::Type::ChordRest, tick);
s->add(el);
}
//---------------------------------------------------------
// tupletAssert -- check assertions for tuplet handling
//---------------------------------------------------------
/**
Check assertions for tuplet handling. If this fails, MusicXML
import will almost certainly break in non-obvious ways.
Should never happen, thus it is OK to quit the application.
*/
#if 0
static void tupletAssert()
{
if (!(int(TDuration::DurationType::V_BREVE) == int(TDuration::DurationType::V_LONG) + 1
&& int(TDuration::DurationType::V_WHOLE) == int(TDuration::DurationType::V_BREVE) + 1
&& int(TDuration::DurationType::V_HALF) == int(TDuration::DurationType::V_WHOLE) + 1
&& int(TDuration::DurationType::V_QUARTER) == int(TDuration::DurationType::V_HALF) + 1
&& int(TDuration::DurationType::V_EIGHTH) == int(TDuration::DurationType::V_QUARTER) + 1
&& int(TDuration::DurationType::V_16TH) == int(TDuration::DurationType::V_EIGHTH) + 1
&& int(TDuration::DurationType::V_32ND) == int(TDuration::DurationType::V_16TH) + 1
&& int(TDuration::DurationType::V_64TH) == int(TDuration::DurationType::V_32ND) + 1
&& int(TDuration::DurationType::V_128TH) == int(TDuration::DurationType::V_64TH) + 1
&& int(TDuration::DurationType::V_256TH) == int(TDuration::DurationType::V_128TH) + 1
)) {
qFatal("tupletAssert() failed");
}
}
#endif
//---------------------------------------------------------
// smallestTypeAndCount
//---------------------------------------------------------
/**
Determine the smallest note type and the number of those
present in a ChordRest.
For a note without dots the type equals the note type
and count is one.
For a single dotted note the type equals half the note type
and count is three.
A double dotted note is similar.
Note: code assumes when duration().type() is incremented,
the note length is divided by two, checked by tupletAssert().
*/
static void smallestTypeAndCount(ChordRest const* const cr, int& type, int& count)
{
type = int(cr->durationType().type());
count = 1;
switch (cr->durationType().dots()) {
case 0:
// nothing to do
break;
case 1:
type += 1; // next-smaller type
count = 3;
break;
case 2:
type += 2; // next-next-smaller type
count = 7;
break;
default:
qDebug("smallestTypeAndCount() does not support more than 2 dots");
}
}
//---------------------------------------------------------
// matchTypeAndCount
//---------------------------------------------------------
/**
Given two note types and counts, if the types are not equal,
make them equal by successively doubling the count of the
largest type.
*/
static void matchTypeAndCount(int& type1, int& count1, int& type2, int& count2)
{
while (type1 < type2) {
type1++;
count1 *= 2;
}
while (type2 < type1) {
type2++;
count2 *= 2;
}
}
//---------------------------------------------------------
// determineTupletTypeAndCount
//---------------------------------------------------------
/**
Determine type and number of smallest notes in the tuplet
*/
static void determineTupletTypeAndCount(Tuplet* t, int& tupletType, int& tupletCount)
{
int elemCount = 0; // number of tuplet elements handled
foreach (DurationElement* de, t->elements()) {
if (de->type() == Element::Type::CHORD || de->type() == Element::Type::REST) {
ChordRest* cr = static_cast<ChordRest*>(de);
if (elemCount == 0) {
// first note: init variables
smallestTypeAndCount(cr, tupletType, tupletCount);
}
else {
int noteType = 0;
int noteCount = 0;
smallestTypeAndCount(cr, noteType, noteCount);
// match the types
matchTypeAndCount(tupletType, tupletCount, noteType, noteCount);
tupletCount += noteCount;
}
}
elemCount++;
}
}
//---------------------------------------------------------
// determineTupletBaseLen
//---------------------------------------------------------
/**
Determine tuplet baseLen as determined by the tuplet ratio,
and type and number of smallest notes in the tuplet.
Example: baselen of a 3:2 tuplet with 1/16, 1/8, 1/8 and 1/16
is 1/8. For this tuplet smalles note is 1/16, count is 6.
*/
// TODO: this is defined twice, remove one
static TDuration determineTupletBaseLen(Tuplet* t)
{
int tupletType = 0; // smallest note type in the tuplet