forked from musescore/MuseScore
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
importmxmlpass2.cpp
6390 lines (5643 loc) · 225 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-2019 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 <memory>
#include <utility>
#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/instrtemplate.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 "libmscore/barline.h"
#include "libmscore/articulation.h"
#include "libmscore/ottava.h"
#include "libmscore/rehearsalmark.h"
#include "libmscore/fermata.h"
#include "importmxmllogger.h"
#include "importmxmlnoteduration.h"
#include "importmxmlnotepitch.h"
#include "importmxmlpass2.h"
#include "musicxmlfonthandler.h"
#include "musicxmlsupport.h"
#include "mscore/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(Placement::BELOW),
bracket(TupletBracketType::AUTO_BRACKET), shownumber(TupletNumberType::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 Fraction lastChordTicks(const Segment* s, const int track, const Fraction& 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 Fraction(0,1);
}
//---------------------------------------------------------
// 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 Fraction& tick)
{
QList<Lyrics*> list;
foreach (Lyrics* l, _lyrics) {
Element* const el = l->parent();
if (el->type() == ElementType::CHORD) { // TODO: rest also possible ?
ChordRest* const par = static_cast<ChordRest*>(el);
if (par->track() == track && (no == -1 || l->no() == no)) {
Fraction lct = lastChordTicks(l->segment(), track, tick);
if (lct > Fraction(0,1)) {
// set lyric tick to the total length from 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);
}
}
//---------------------------------------------------------
// 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, static_cast<int>(intval.diatonic), static_cast<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, const Fraction& tstart, const Fraction& tend)
{
Fraction ctick = tstart;
Fraction 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 > Fraction(1,256)) {
Fraction len = restLen;
TDuration d(TDuration::DurationType::V_INVALID);
if (measure->ticks() == restLen) {
d.setType(TDuration::DurationType::V_MEASURE);
} else {
d.setVal(len.ticks());
}
Rest* rest = new Rest(measure->score(), d);
rest->setTicks(len);
rest->setTrack(track);
rest->setVisible(false);
Segment* s = measure->getSegment(SegmentType::ChordRest, tstart);
s->add(rest);
len = rest->globalTicks();
// 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);
Fraction measTick = measure->tick();
Fraction measLen = measure->ticks();
Fraction 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;
Fraction 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);
Fraction crTick = cr->tick();
Fraction crLen = cr->globalTicks();
Fraction 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;
}
}
/*
for (const auto& instr : mxmlDrumset) {
// MusicXML elements instrument-name, midi-program, instrument-sound, virtual-library, virtual-name
// in a shell script use "mscore ... 2>&1 | grep GREP_ME | cut -d' ' -f3-" to extract
qDebug("GREP_ME '%s',%d,'%s','%s','%s'",
qPrintable(instr.name),
instr.midiProgram + 1,
qPrintable(instr.sound),
qPrintable(instr.virtLib),
qPrintable(instr.virtName)
);
}
*/
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 initialized
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);
}
}
}
//---------------------------------------------------------
// createInstrument
//---------------------------------------------------------
/**
Create an Instrument based on the information in \a mxmlInstr.
*/
static Instrument createInstrument(const MusicXMLDrumInstrument& mxmlInstr)
{
Instrument instr;
InstrumentTemplate* it {};
if (!mxmlInstr.sound.isEmpty()) {
it = Ms::searchTemplateForMusicXmlId(mxmlInstr.sound);
}
/*
qDebug("sound '%s' it %p trackname '%s' program %d",
qPrintable(mxmlInstr.sound), it,
it ? qPrintable(it->trackName) : "",
mxmlInstr.midiProgram);
*/
if (it) {
// initialize from template with matching MusicXmlId
instr = Instrument::fromTemplate(it);
// reset transpose, as it is determined later from MusicXML data
instr.setTranspose(Interval());
} else {
// set articulations to default (global articulations)
instr.setArticulation(articulation);
// set default program
instr.channel(0)->setProgram(mxmlInstr.midiProgram >= 0 ? mxmlInstr.midiProgram : 0);
}
// add / overrule with values read from MusicXML
instr.channel(0)->setPan(mxmlInstr.midiPan);
instr.channel(0)->setVolume(mxmlInstr.midiVolume);
instr.setTrackName(mxmlInstr.name);
return instr;
}
//---------------------------------------------------------
// setFirstInstrument
//---------------------------------------------------------
/**
Set first instrument for Part \a part
*/
static void setFirstInstrument(MxmlLogger* logger, const QXmlStreamReader* const xmlreader,
Part* part, const QString& partId,
const QString& instrId, const MusicXMLDrumset& mxmlDrumset)
{
if (mxmlDrumset.size() > 0) {
//qDebug("setFirstInstrument: initial instrument '%s'", qPrintable(instrId));
MusicXMLDrumInstrument mxmlInstr;
if (instrId == "") {
mxmlInstr = mxmlDrumset.first();
} else if (mxmlDrumset.contains(instrId)) {
mxmlInstr = mxmlDrumset.value(instrId);
} else {
logger->logError(QString("initial instrument '%1' not found in part '%2'")
.arg(instrId).arg(partId), xmlreader);
mxmlInstr = mxmlDrumset.first();
}
Instrument instr = createInstrument(mxmlInstr);
part->setInstrument(instr);
if (mxmlInstr.midiChannel >= 0) {
part->setMidiChannel(mxmlInstr.midiChannel, mxmlInstr.midiPort);
}
// note: setMidiProgram() does more than simply setting the MIDI program
if (mxmlInstr.midiProgram >= 0) {
part->setMidiProgram(mxmlInstr.midiProgram);
}
} else {
logger->logError(QString("no instrument found for part '%1'")
.arg(partId), xmlreader);
}
}
//---------------------------------------------------------
// 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(Fraction(0,1)) == 5 && !part->staff(j)->isDrumStaff(Fraction(0,1))) {
part->staff(j)->setStaffType(Fraction(0,1), *StaffType::preset(StaffTypes::PERC_DEFAULT));
}
}
// set drumset for instrument
part->instrument()->setDrumset(drumset);
part->instrument()->channel(0)->setBank(128);
}
//---------------------------------------------------------
// setPartInstruments
//---------------------------------------------------------
static void setPartInstruments(MxmlLogger* logger, const QXmlStreamReader* const xmlreader,
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("f %s previd %s id %s mustInsert %d",
qPrintable(f.print()),
qPrintable(prevInstrId),
qPrintable(instrId),
mustInsert);
*/
if (mustInsert) {
const int staff = score->staffIdx(part);
const int track = staff * VOICES;
const Fraction tick = f;
//qDebug("instrument change: tick %s (%d) track %d instr '%s'",
// qPrintable(f.print()), f.ticks(), track, qPrintable(instrId));
auto segment = score->tick2segment(tick, true, SegmentType::ChordRest, true);
if (!segment) {
logger->logError(QString("segment for instrument change at tick %1 not found")
.arg(tick.ticks()), xmlreader);
} else if (!mxmlDrumset.contains(instrId)) {
logger->logError(QString("changed instrument '%1' at tick %2 not found in part '%3'")
.arg(instrId).arg(tick.ticks()).arg(partId), xmlreader);
} else {
MusicXMLDrumInstrument mxmlInstr = mxmlDrumset.value(instrId);
Instrument instr = createInstrument(mxmlInstr);
//qDebug("instr %p", &instr);
InstrumentChange* ic = new InstrumentChange(instr, score);
ic->setTrack(track);
// for text use instrument name (if known) else use "Instrument change"
const QString text = mxmlInstr.name;
ic->setXmlText(text.isEmpty() ? "Instrument change" : text);
ic->setVisible(false);
segment->add(ic); // note: includes part::setInstrument(instr);
// setMidiChannel() depends on setInstrument() already been done
if (mxmlInstr.midiChannel >= 0) {
part->setMidiChannel(mxmlInstr.midiChannel, mxmlInstr.midiPort, tick);
}
}
}
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(MxmlLogger* logger, const QXmlStreamReader* const xmlreader,
ChordRest* cr, Lyrics* l, int lyricNo, MusicXmlLyricsExtend& extendedLyrics)
{
if (lyricNo > MAX_LYRICS) {
logger->logError(QString("too much lyrics (>%1)")
.arg(MAX_LYRICS), xmlreader);
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(MxmlLogger* logger, const QXmlStreamReader* const xmlreader,
ChordRest* cr,
const QMap<int, Lyrics*>& numbrdLyrics,
const QSet<Lyrics*>& extLyrics,
MusicXmlLyricsExtend& extendedLyrics)
{
for (const auto lyricNo : numbrdLyrics.keys()) {
const auto lyric = numbrdLyrics.value(lyricNo);
addLyric(logger, xmlreader, cr, lyric, lyricNo, extendedLyrics);
if (extLyrics.contains(lyric)) {
extendedLyrics.addLyric(lyric);
}
}
}
//---------------------------------------------------------
// addElemOffset
//---------------------------------------------------------
static void addElemOffset(Element* el, int track, const QString& placement, Measure* measure, const Fraction& tick)
{
/*
qDebug("addElem el %p track %d placement %s tick %d",
el, track, qPrintable(placement), tick);
*/
#if 0 // ws: use placement for symbols
// move to correct position
// TODO: handle rx, ry
if (el->isSymbol()) {
qreal y = 0;
// 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;
offsAbove = -2;
offsBelow = 4 + (stafflines - 1);
if (placement == "above") {
y += offsAbove;
}
if (placement == "below") {
y += offsBelow;
}
//qDebug(" y = %g", y);
y *= el->score()->spatium();
el->setUserOff(QPoint(0, y));
} else {
el->setPlacement(placement == "above" ? Placement::ABOVE : Placement::BELOW);
}
#endif
el->setPlacement(placement == "above" ? Placement::ABOVE : Placement::BELOW);
el->setPropertyFlags(Pid::PLACEMENT, PropertyFlags::UNSTYLED);
el->setTrack(el->isTempoText() ? 0 : track); // TempoText must be in track 0
Segment* s = measure->getSegment(SegmentType::ChordRest, tick);
s->add(el);
}
//---------------------------------------------------------
// calculateTupletDuration
//---------------------------------------------------------
/**
Calculate the duration of all notes in the tuplet combined
*/
static Fraction calculateTupletDuration(const Tuplet* const t)
{
Fraction res;
foreach (DurationElement* de, t->elements()) {
if (de->type() == ElementType::CHORD || de->type() == ElementType::REST) {
const auto cr = static_cast<ChordRest*>(de);
const auto durationType = cr->actualDurationType();
if (durationType.isValid() && !durationType.isMeasure()) {
res += durationType.fraction();
}
}
}
res /= t->ratio();
return res;
}
//---------------------------------------------------------
// determineTupletBaseLen
//---------------------------------------------------------
/**
Determine tuplet baseLen as determined by the tuplet ratio
and duration.
*/
static TDuration determineTupletBaseLen(const Tuplet* const t)
{
Fraction tupletFraction;
Fraction tupletFullDuration;
determineTupletFractionAndFullDuration(calculateTupletDuration(t), tupletFraction, tupletFullDuration);
auto baseLen = tupletFullDuration * Fraction(1, t->ratio().denominator());
/*
qDebug("tupletFraction %s tupletFullDuration %s ratio %s baseLen %s",
qPrintable(tupletFraction.toString()),
qPrintable(tupletFullDuration.toString()),
qPrintable(t->ratio().toString()),
qPrintable(baseLen.toString())
);
*/
return TDuration(baseLen);
}
//---------------------------------------------------------
// handleTupletStart
//---------------------------------------------------------
static void handleTupletStart(const ChordRest* const cr, Tuplet*& tuplet,
const int actualNotes, const int normalNotes,
const MusicXmlTupletDesc& tupletDesc)
{
tuplet = new Tuplet(cr->score());
tuplet->setTrack(cr->track());
tuplet->setRatio(Fraction(actualNotes, normalNotes));
// tuplet->setTick(cr->tick());
tuplet->setBracketType(tupletDesc.bracket);
tuplet->setNumberType(tupletDesc.shownumber);
// TODO type, placement, bracket
tuplet->setParent(cr->measure());
}
//---------------------------------------------------------
// handleTupletStop
//---------------------------------------------------------
static void handleTupletStop(Tuplet*& tuplet, const int normalNotes)
{
// allow handleTupletStop to be called w/o error of no tuplet active
if (!tuplet) {
return;
}
// set baselen
TDuration td = determineTupletBaseLen(tuplet);
tuplet->setBaseLen(td);
Fraction f(normalNotes, td.fraction().denominator());
f.reduce();
tuplet->setTicks(f);
// TODO determine usefulness of following check
int totalDuration = 0;
foreach (DurationElement* de, tuplet->elements()) {
if (de->type() == ElementType::CHORD || de->type() == ElementType::REST) {
totalDuration+=de->globalTicks().ticks();
}
}
if (!(totalDuration && normalNotes)) {
qDebug("MusicXML::import: tuplet stop but bad duration"); // TODO
}
tuplet = 0;
}
//---------------------------------------------------------
// setElementPropertyFlags
//---------------------------------------------------------
static void setElementPropertyFlags(ScoreElement* element, const Pid propertyId,
const QString value1, const QString value2 = QString())
{
if (value1.isEmpty()) { // Set as an implicit value
element->setPropertyFlags(propertyId, PropertyFlags::STYLED);
} else if (!value1.isNull() || !value2.isNull()) { // Set as an explicit value
element->setPropertyFlags(propertyId, PropertyFlags::UNSTYLED);
}
}
//---------------------------------------------------------
// addArticulationToChord
//---------------------------------------------------------
static void addArticulationToChord(const Notation& notation, ChordRest* cr)
{
const SymId articSym = notation.symId();
const QString dir = notation.attribute("type");
const QString place = notation.attribute("placement");
Articulation* na = new Articulation(articSym, cr->score());
if (!dir.isNull()) { // Only for case where XML attribute is present (isEmpty wouldn't work)
na->setUp(dir.isEmpty() || dir == "up");
}
setElementPropertyFlags(na, Pid::DIRECTION, dir);
if (place == "above" || dir.isEmpty() || dir == "up") {
na->setAnchor(ArticulationAnchor::TOP_STAFF);
} else if (place == "below" || dir == "down") {
na->setAnchor(ArticulationAnchor::BOTTOM_STAFF);
}
setElementPropertyFlags(na, Pid::DIRECTION, dir, place);
cr->add(na);
}
//---------------------------------------------------------
// addFermataToChord
//---------------------------------------------------------
/**
Add a MusicXML fermata.
Note: MusicXML common.mod: "The fermata type is upright if not specified."
*/
static void addFermataToChord(const Notation& notation, ChordRest* cr)
{
const SymId articSym = notation.symId();
const QString direction = notation.attribute("type");
Fermata* na = new Fermata(articSym, cr->score());
na->setTrack(cr->track());
if (!direction.isNull()) { // Only for case where XML attribute is present (isEmpty wouldn't work)
na->setPlacement(direction == "inverted" ? Placement::BELOW : Placement::ABOVE);
}
setElementPropertyFlags(na, Pid::PLACEMENT, direction);
if (cr->segment() == nullptr && cr->isGrace()) {
cr->el().push_back(na); // store for later move to segment
} else {
cr->segment()->add(na);
}
}
//---------------------------------------------------------
// addMordentToChord
//---------------------------------------------------------
/**