-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
importxml.cpp
5454 lines (5008 loc) · 224 KB
/
importxml.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
//=============================================================================
// MusE Score
// Linux Music Score Editor
// $Id: importxml.cpp 5653 2012-05-19 20:19:58Z lvinken $
//
// Copyright (C) 2002-2014 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.
//=============================================================================
// TODO LVI 2011-01-18: it seems brackets ending after the last note in a measure
// import OK but stop is not exported OK. Find out what causes this (import, export,
// structural issue).
// TODO LVI 2011-10-30: determine how to report import errors.
// Currently all output (both debug and error reports) are done using qDebug.
// TODO LVI 2012-04-26: read drumset definition from MusicXML
// Mapping Musescore DrumInstrument to MusicXML elements
// pitch part-list/score-part/midi-instrument/midi-unpitched
// name part-list/score-part/score-instrument/instrument-name
// notehead part/measure/note/notehead (once for each individual note)
// line part/measure/note/unpitched (once for each individual note) + current clef
// stemdirection part/measure/note/stem (once for each individual note)
// voice N/A (leave empty ?)
// shortcut N/A (leave empty ?)
/**
MusicXML import.
*/
#include "config.h"
// #include "musescore.h"
#include "musicxml.h"
#include "file.h"
#include "libmscore/score.h"
#include "libmscore/rest.h"
#include "libmscore/chord.h"
#include "libmscore/sig.h"
#include "libmscore/key.h"
#include "libmscore/clef.h"
#include "libmscore/note.h"
#include "libmscore/element.h"
#include "libmscore/sym.h"
#include "libmscore/slur.h"
#include "libmscore/tie.h"
#include "libmscore/hairpin.h"
#include "libmscore/tuplet.h"
#include "libmscore/segment.h"
#include "libmscore/dynamic.h"
#include "libmscore/page.h"
#include "libmscore/staff.h"
#include "libmscore/part.h"
#include "libmscore/measure.h"
#include "libmscore/style.h"
#include "libmscore/bracket.h"
#include "libmscore/timesig.h"
#include "libmscore/xml.h"
#include "libmscore/barline.h"
#include "libmscore/lyrics.h"
#include "libmscore/volta.h"
#include "libmscore/textline.h"
#include "libmscore/keysig.h"
#include "libmscore/pitchspelling.h"
#include "libmscore/utils.h"
#include "libmscore/layoutbreak.h"
#include "libmscore/tremolo.h"
#include "libmscore/box.h"
#include "libmscore/repeat.h"
#include "libmscore/ottava.h"
#include "libmscore/trill.h"
#include "libmscore/pedal.h"
#include "libmscore/harmony.h"
#include "libmscore/tempotext.h"
#include "libmscore/articulation.h"
#include "libmscore/arpeggio.h"
#include "libmscore/glissando.h"
#include "libmscore/breath.h"
#include "libmscore/tempo.h"
#include "libmscore/chordlist.h"
#include "libmscore/mscore.h"
#include "libmscore/accidental.h"
#include "libmscore/rehearsalmark.h"
#include "libmscore/fingering.h"
#include "preferences.h"
#include "musicxmlsupport.h"
#include "libmscore/chordline.h"
#include "libmscore/figuredbass.h"
#include "libmscore/fret.h"
#include "thirdparty/qzip/qzipreader_p.h"
#include "libmscore/stafftype.h"
#include "libmscore/stringdata.h"
#include "libmscore/drumset.h"
#include "libmscore/beam.h"
#include "libmscore/jump.h"
#include "libmscore/marker.h"
#include "importxmlfirstpass.h"
namespace Ms {
//---------------------------------------------------------
// local defines for debug output
//---------------------------------------------------------
// #define DEBUG_VOICE_MAPPER true
// #define DEBUG_TICK true
//---------------------------------------------------------
// MusicXMLStepAltOct2Pitch
//---------------------------------------------------------
/**
Convert MusicXML \a step / \a alter / \a octave to midi pitch.
Note: same code is also in libmscore/tablature.cpp.
TODO: combine ?
*/
static int MusicXMLStepAltOct2Pitch(char step, int alter, int octave)
{
int istep = step - 'A';
// a b c d e f g
static int table[7] = { 9, 11, 0, 2, 4, 5, 7 };
if (istep < 0 || istep > 6) {
qDebug("MusicXMLStepAltOct2Pitch: illegal step %d, <%c>", istep, step);
return -1;
}
int pitch = table[istep] + 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.
*/
static void xmlSetPitch(Note* n, char step, int alter, int octave, Ottava* ottava, int track)
{
// qDebug("xmlSetPitch(n=%p, st=%c, alter=%d, octave=%d)",
// n, step, alter, octave);
int pitch = MusicXMLStepAltOct2Pitch(step, alter, octave);
if (pitch < 0)
pitch = 0;
if (pitch > 127)
pitch = 127;
if (ottava != 0 && ottava->track() == track)
pitch -= ottava->pitchShift();
n->setPitch(pitch);
int istep = step - 'A';
// a b c d e f g
static int table1[7] = { 5, 6, 0, 1, 2, 3, 4 };
int tpc = step2tpc(table1[istep], AccidentalVal(alter));
// alternativ: tpc = step2tpc((istep + 5) % 7, alter); // rotate istep 5 steps
n->setTpc(tpc);
n->setLine(absStep(tpc, pitch));
}
//---------------------------------------------------------
// calcTicks
//---------------------------------------------------------
static int calcTicks(QString text, int divisions)
{
bool ok;
int val = MxmlSupport::stringToInt(text, &ok);
if (!ok) {
qDebug("MusicXml-Import: bad duration value: <%s>",
qPrintable(text));
}
if (val == 0) // neuratron scanner produces sometimes 0 !?
val = 1;
val *= MScore::division;
val /= divisions;
return val;
}
//---------------------------------------------------------
// noteDurationAsFraction
//---------------------------------------------------------
/**
Determine note duration as fraction. Prefer note type over duration.
Input e is the note element.
If chord or grace, duration is 0.
*/
static Fraction noteDurationAsFraction(const int divisions, const QDomElement e)
{
int actualNotes = 0;
bool chord = false;
int dots = 0;
int duration = 0;
bool grace = false;
int normalNotes = 0;
bool rest = false;
QString type;
for (QDomElement ee = e.firstChildElement(); !ee.isNull(); ee = ee.nextSiblingElement()) {
if (ee.tagName() == "chord")
chord = true;
else if (ee.tagName() == "dot")
dots++;
else if (ee.tagName() == "duration") {
bool ok;
duration = MxmlSupport::stringToInt(ee.text(), &ok);
if (!ok)
qDebug("MusicXml-Import: bad duration value: <%s>",
qPrintable(ee.text()));
}
else if (ee.tagName() == "grace")
grace = true;
else if (ee.tagName() == "rest")
rest = true;
else if (ee.tagName() == "time-modification") {
for (QDomElement eee = ee.firstChildElement(); !eee.isNull(); eee = eee.nextSiblingElement()) {
if (eee.tagName() == "actual-notes") {
bool ok;
actualNotes = MxmlSupport::stringToInt(eee.text(), &ok);
if (!ok || divisions <= 0)
qDebug("MusicXml-Import: bad actual-notes value: <%s>",
qPrintable(eee.text()));
}
if (eee.tagName() == "normal-notes") {
bool ok;
normalNotes = MxmlSupport::stringToInt(eee.text(), &ok);
if (!ok || divisions <= 0)
qDebug("MusicXml-Import: bad normal-notes value: <%s>",
qPrintable(eee.text()));
}
}
}
else if (ee.tagName() == "type")
type = ee.text();
}
// if chord or grace, duration is 0
if (chord || grace)
return Fraction(0, 1);
// calculate note duration as fraction based on type, dots, normal and actual notes
// if that does not succeed, fallback to using the <duration> element
// note divisions = ticks / quarter note
Fraction f = MxmlSupport::calculateFraction(type, dots, normalNotes, actualNotes);
if (!f.isValid()) {
f = Fraction(duration, 4 * divisions);
}
// bug fix for rests in triplet
if (f.isValid() && rest && normalNotes == 0 && actualNotes == 0) {
if ((Fraction(duration, 4 * divisions) / f) == Fraction(2, 3)) {
// duration is exactly 2/3 of what is expected based on type
f = Fraction(duration, 4 * divisions);
}
}
#ifdef DEBUG_TICK
qDebug("time-in-fraction: note type %s dots %d norm %d act %d"
" dur %d chord %d grace %d-> dt frac %s (ticks %d)",
qPrintable(type), dots, normalNotes, actualNotes, duration,
chord, grace, qPrintable(f.print()), f.ticks());
#endif
return f;
}
//---------------------------------------------------------
// moveTick
//---------------------------------------------------------
/**
Move tick and typFr by amount specified in the element e, which must be
a forward, backup or note.
*/
static void moveTick(const int mtick, int& tick, int& maxtick, Fraction& typFr, const int divisions, const QDomElement e)
{
if (e.tagName() == "forward") {
for (QDomElement ee = e.firstChildElement(); !ee.isNull(); ee = ee.nextSiblingElement()) {
if (ee.tagName() == "duration") {
int val = calcTicks(ee.text(), divisions);
#ifdef DEBUG_TICK
qDebug("forward %d", val);
#endif
bool ok;
val = MxmlSupport::stringToInt(ee.text(), &ok);
if (!ok || divisions <= 0)
qDebug("MusicXml-Import: bad divisions value: <%s>",
qPrintable(ee.text()));
Fraction f(val, 4 * divisions); // note divisions = ticks / quarter note
typFr += f;
typFr.reduce();
tick = mtick + typFr.ticks();
if (tick > maxtick)
maxtick = tick;
}
else if (ee.tagName() == "voice")
;
else if (ee.tagName() == "staff")
;
else
domError(ee);
}
}
else if (e.tagName() == "backup") {
for (QDomElement ee = e.firstChildElement(); !ee.isNull(); ee = ee.nextSiblingElement()) {
if (ee.tagName() == "duration") {
int val = calcTicks(ee.text(), divisions);
#ifdef DEBUG_TICK
qDebug("backup %d", val);
#endif
bool ok;
val = MxmlSupport::stringToInt(ee.text(), &ok);
if (!ok || divisions <= 0)
qDebug("MusicXml-Import: bad divisions value: <%s>",
qPrintable(ee.text()));
Fraction f(val, 4 * divisions); // note divisions = ticks / quarter note
if (f < typFr) {
typFr -= f;
typFr.reduce();
}
else
typFr = Fraction(0, 1);
tick = mtick + typFr.ticks();
}
else
domError(ee);
}
}
else if (e.tagName() == "note") {
#ifdef DEBUG_TICK
int ticks = 0;
for (QDomElement ee = e.firstChildElement(); !ee.isNull(); ee = ee.nextSiblingElement()) {
QString tag(ee.tagName());
if (tag == "duration") {
ticks = calcTicks(ee.text(), divisions);
}
}
qDebug("note %d", ticks);
#endif
Fraction f = noteDurationAsFraction(divisions, e);
typFr += f;
typFr.reduce();
tick = mtick + typFr.ticks();
if (tick > maxtick)
maxtick = tick;
}
}
//---------------------------------------------------------
// determineMeasureStart
//---------------------------------------------------------
/**
Determine the start ticks of each measure
i.e. the sum of all previous measures length
or start tick measure equals start tick previous measure plus length previous measure
*/
static void determineMeasureStart(const QVector<Fraction>& ml, QVector<int>& ms)
{
ms.resize(ml.size());
// first measure starts at tick = 0
ms[0] = 0;
// all others start at start tick previous measure plus length previous measure
for (int i = 1; i < ml.size(); i++)
ms[i] = ms.at(i - 1) + ml.at(i - 1).ticks();
#ifdef DEBUG_TICK
for (int i = 0; i < ms.size(); i++)
qDebug("measurelength ms[%d] %d", i + 1, ms.at(i));
#endif
}
//---------------------------------------------------------
// MusicXml
//---------------------------------------------------------
/**
MusicXml constructor.
*/
MusicXml::MusicXml(QDomDocument* d, MxmlReaderFirstPass const& p1)
:
lastVolta(0),
doc(d),
pass1(p1),
beamMode(BeamMode::NONE),
pageWidth(0),
pageHeight(0)
{
// Determine the start tick of each measure in the part
pass1.determineMeasureLength(measureLength);
determineMeasureStart(measureLength, measureStart);
}
//---------------------------------------------------------
// initMusicXmlSchema
// return false on error
//---------------------------------------------------------
static bool initMusicXmlSchema(QXmlSchema& schema)
{
// read the MusicXML schema from the application resources
QFile schemaFile(":/schema/musicxml.xsd");
if (!schemaFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug("initMusicXmlSchema() could not open resource musicxml.xsd");
MScore::lastError = QT_TRANSLATE_NOOP("file", "Internal error: could not open resource musicxml.xsd\n");
return false;
}
// copy the schema into a QByteArray and fixup xs:imports,
// using a path to the application resources instead of to www.musicxml.org
// to prevent downloading from the net
QByteArray schemaBa;
QTextStream schemaStream(&schemaFile);
while (!schemaStream.atEnd()) {
QString line = schemaStream.readLine();
if (line.contains("xs:import"))
line.replace("http://www.musicxml.org/xsd", "qrc:///schema");
schemaBa += line.toUtf8();
schemaBa += "\n";
}
// load and validate the schema
schema.load(schemaBa);
if (!schema.isValid()) {
qDebug("initMusicXmlSchema() internal error: MusicXML schema is invalid");
MScore::lastError = QT_TRANSLATE_NOOP("file", "Internal error: MusicXML schema is invalid\n");
return false;
}
return true;
}
//---------------------------------------------------------
// musicXMLValidationErrorDialog
//---------------------------------------------------------
/**
Show a dialog displaying the MusicXML validation error(s)
and asks the user if he wants to try to load the file anyway.
Return QMessageBox::Yes (try anyway) or QMessageBox::No (don't)
*/
static int musicXMLValidationErrorDialog(QString text, QString detailedText)
{
QMessageBox errorDialog;
errorDialog.setIcon(QMessageBox::Question);
errorDialog.setText(text);
errorDialog.setInformativeText("Do you want to try to load this file anyway?");
errorDialog.setDetailedText(detailedText);
errorDialog.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
errorDialog.setDefaultButton(QMessageBox::No);
return errorDialog.exec();
}
//---------------------------------------------------------
// extractRootfile
//---------------------------------------------------------
/**
Extract rootfile from compressed MusicXML file \a qf, return true if OK and false on error.
*/
static bool extractRootfile(QFile* qf, QByteArray& data)
{
MQZipReader f(qf->fileName());
data = f.fileData("META-INF/container.xml");
QDomDocument container;
int line, column;
QString err;
if (!container.setContent(data, false, &err, &line, &column)) {
QString s = QT_TRANSLATE_NOOP("file", "Error reading container.xml at line %1 column %2: %3\n");
MScore::lastError = s.arg(line).arg(column).arg(err);
return false;
}
// extract first rootfile
QString rootfile = "";
for (QDomElement e = container.documentElement(); !e.isNull(); e = e.nextSiblingElement()) {
if (e.tagName() == "container") {
for (QDomElement ee = e.firstChildElement(); !ee.isNull(); ee = ee.nextSiblingElement()) {
if (ee.tagName() == "rootfiles") {
for (QDomElement eee = ee.firstChildElement(); !eee.isNull(); eee = eee.nextSiblingElement()) {
if (eee.tagName() == "rootfile") {
if (rootfile == "")
rootfile = eee.attribute(QString("full-path"));
}
else
domError(eee);
}
}
else
domError(ee);
}
}
else
domError(e);
}
if (rootfile == "") {
qDebug("can't find rootfile in: %s", qPrintable(qf->fileName()));
MScore::lastError = QT_TRANSLATE_NOOP("file", "can't find rootfile\n");
return false;
}
// read the rootfile
data = f.fileData(rootfile);
return true;
}
//---------------------------------------------------------
// doValidate
//---------------------------------------------------------
/**
Validate MusicXML data from file \a name contained in QIODevice \a dev.
*/
static Score::FileError doValidate(const QString& name, QIODevice* dev)
{
QTime t;
t.start();
// initialize the schema
ValidatorMessageHandler messageHandler;
QXmlSchema schema;
schema.setMessageHandler(&messageHandler);
if (!initMusicXmlSchema(schema))
return Score::FILE_BAD_FORMAT; // appropriate error message has been printed by initMusicXmlSchema
// validate the data
QXmlSchemaValidator validator(schema);
bool valid = validator.validate(dev, QUrl::fromLocalFile(name));
qDebug("Validation time elapsed: %d ms", t.elapsed());
if (valid)
qDebug("importMusicXml() file '%s' is a valid MusicXML file", qPrintable(name));
else {
qDebug("importMusicXml() file '%s' is not a valid MusicXML file", qPrintable(name));
MScore::lastError = QT_TRANSLATE_NOOP("file", "this is not a valid MusicXML file\n");
QString text = QString("File '%1' is not a valid MusicXML file").arg(name);
if (musicXMLValidationErrorDialog(text, messageHandler.getErrors()) != QMessageBox::Yes)
return Score::FILE_USER_ABORT;
}
// return OK
return Score::FILE_NO_ERROR;
}
//---------------------------------------------------------
// doImport
//---------------------------------------------------------
/**
Import MusicXML data from file \a name contained in QIODevice \a dev into score \a score.
*/
static Score::FileError doImport(Score* score, const QString& name, QIODevice* dev, MxmlReaderFirstPass const& pass1)
{
QTime t;
t.start();
QDomDocument doc;
int line;
int column;
QString err;
if (!doc.setContent(dev, false, &err, &line, &column)) {
QString s = QT_TRANSLATE_NOOP("file", "Error at line %1 column %2: %3\n");
MScore::lastError = s.arg(line).arg(column).arg(err);
return Score::FILE_BAD_FORMAT;
}
docName = name; // set filename for domError
MusicXml musicxml(&doc, pass1);
musicxml.import(score);
qDebug("Parsing time elapsed: %d ms", t.elapsed());
return Score::FILE_NO_ERROR;
}
//---------------------------------------------------------
// doValidateAndImport
//---------------------------------------------------------
/**
Validate and import MusicXML data from file \a name contained in QIODevice \a dev into score \a score.
*/
static Score::FileError doValidateAndImport(Score* score, const QString& name, QIODevice* dev)
{
// validate the file
Score::FileError res;
res = doValidate(name, dev);
if (res != Score::FILE_NO_ERROR)
return res;
// pass 1
dev->seek(0);
MxmlReaderFirstPass pass1;
res = pass1.setContent(dev);
if (res != Score::FILE_NO_ERROR)
return res;
pass1.parseFile();
// import the file
dev->seek(0);
res = doImport(score, name, dev, pass1);
qDebug("importMusicXml() return %d", res);
return res;
}
//---------------------------------------------------------
// importMusicXml
// return Score::FILE_* errors
//---------------------------------------------------------
/**
Import MusicXML file \a name into the Score.
*/
Score::FileError importMusicXml(Score* score, const QString& name)
{
qDebug("importMusicXml(%p, %s)", score, qPrintable(name));
// open the MusicXML file
QFile xmlFile(name);
if (!xmlFile.exists())
return Score::FILE_NOT_FOUND;
if (!xmlFile.open(QIODevice::ReadOnly)) {
qDebug("importMusicXml() could not open MusicXML file '%s'", qPrintable(name));
MScore::lastError = QT_TRANSLATE_NOOP("file", "could not open MusicXML file\n");
return Score::FILE_OPEN_ERROR;
}
// and import it
return doValidateAndImport(score, name, &xmlFile);
}
//---------------------------------------------------------
// importCompressedMusicXml
// return false on error
//---------------------------------------------------------
/**
Import compressed MusicXML file \a name into the Score.
*/
Score::FileError importCompressedMusicXml(Score* score, const QString& name)
{
qDebug("importCompressedMusicXml(%p, %s)", score, qPrintable(name));
// open the compressed MusicXML file
QFile mxlFile(name);
if (!mxlFile.exists())
return Score::FILE_NOT_FOUND;
if (!mxlFile.open(QIODevice::ReadOnly)) {
qDebug("importCompressedMusicXml() could not open compressed MusicXML file '%s'", qPrintable(name));
MScore::lastError = QT_TRANSLATE_NOOP("file", "could not open compressed MusicXML file\n");
return Score::FILE_OPEN_ERROR;
}
// extract the root file
QByteArray data;
if (!extractRootfile(&mxlFile, data))
return Score::FILE_BAD_FORMAT; // appropriate error message has been printed by extractRootfile
QBuffer buffer(&data);
buffer.open(QIODevice::ReadOnly);
// and import it
return doValidateAndImport(score, name, &buffer);
}
//---------------------------------------------------------
// import
// scorePartwise
// part-list
// part
// work
// identification
//---------------------------------------------------------
static void tupletAssert();
/**
Parse the MusicXML file, which must be in score-partwise format.
*/
void MusicXml::import(Score* s)
{
tupletAssert();
score = s;
tie = 0;
for (int i = 0; i < MAX_NUMBER_LEVEL; ++i)
slur[i] = 0;
for (int i = 0; i < MAX_BRACKETS; ++i)
bracket[i] = 0;
for (int i = 0; i < MAX_DASHES; ++i)
dashes[i] = 0;
ottava = 0;
trill = 0;
pedal = 0;
harmony = 0;
tremStart = 0;
hairpin = 0;
figBass = 0;
figBassExtend = false;
// TODO only if multi-measure rests used ???
// score->style()->set(ST_createMultiMeasureRests, true);
for (QDomElement e = doc->documentElement(); !e.isNull(); e = e.nextSiblingElement()) {
if (e.tagName() == "score-partwise")
scorePartwise(e.firstChildElement());
else
domError(e);
}
}
//---------------------------------------------------------
// addText
//---------------------------------------------------------
static void addText(VBox*& vbx, Score* s, QString strTxt, int stl)
{
if (!strTxt.isEmpty()) {
Text* text = new Text(s);
text->setTextStyleType(stl);
text->setPlainText(strTxt);
if (vbx == 0)
vbx = new VBox(s);
vbx->add(text);
}
}
//---------------------------------------------------------
// doCredits
//---------------------------------------------------------
/**
Create Text elements for the credits read from MusicXML credit-words elements.
Apply simple heuristics using only default x and y to recognize the meaning of credit words
If no credits are found, create credits from meta data.
*/
void MusicXml::doCredits()
{
// IMPORT_LAYOUT
// qDebug("MusicXml::doCredits()");
/*
const PageFormat* pf = score->pageFormat();
qDebug("page format w=%g h=%g spatium=%g DPMM=%g DPI=%g",
pf->width(), pf->height(), score->spatium(), MScore::DPMM, DPI);
// page width and height in tenths
const double pw = pf->width() * 10 * DPI / score->spatium();
const double ph = pf->height() * 10 * DPI / score->spatium();
*/
const int pw1 = pageWidth / 3;
const int pw2 = pageWidth * 2 / 3;
const int ph2 = pageHeight / 2;
// qDebug("page format w=%g h=%g", pw, ph);
// qDebug("page format w=%d h=%d", pageWidth, pageHeight);
// qDebug("page format pw1=%d pw2=%d ph2=%d", pw1, pw2, ph2);
// dump the credits
/*
for (ciCreditWords ci = credits.begin(); ci != credits.end(); ++ci) {
CreditWords* w = *ci;
qDebug("credit-words defx=%g defy=%g just=%s hal=%s val=%s words=%s",
w->defaultX,
w->defaultY,
w->justify.toUtf8().data(),
w->hAlign.toUtf8().data(),
w->vAlign.toUtf8().data(),
w->words.toUtf8().data());
}
*/
CreditWords* crwTitle = 0;
CreditWords* crwSubTitle = 0;
CreditWords* crwComposer = 0;
CreditWords* crwPoet = 0;
CreditWords* crwCopyRight = 0;
QMap<int, CreditWords*> creditMap; // store credit-words sorted on y pos
int nWordsHeader = 0; // number of credit-words in the header
int nWordsFooter = 0; // number of credit-words in the footer
for (ciCreditWords ci = credits.begin(); ci != credits.end(); ++ci) {
CreditWords* w = *ci;
double defx = w->defaultX;
double defy = w->defaultY;
// composer is in the right column
if (pw2 < defx) {
// found composer
if (!crwComposer) crwComposer = w;
}
// poet is in the left column
else if (defx < pw1) {
// found poet
if (!crwPoet) crwPoet = w;
}
// save others (in the middle column) to be handled later
else {
creditMap.insert(defy, w);
// and count #words in header and footer
if (defy > ph2)
nWordsHeader++;
else
nWordsFooter++;
}
} // end for (ciCreditWords ...
/*
qDebug("header %d footer %d", nWordsHeader, nWordsFooter);
QMap<int, CreditWords*>::const_iterator ci = creditMap.constBegin();
while (ci != creditMap.constEnd()) {
CreditWords* w = ci.value();
qDebug("creditMap %d credit-words defx=%g defy=%g just=%s hal=%s val=%s words=%s",
ci.key(),
w->defaultX,
w->defaultY,
w->justify.toUtf8().data(),
w->hAlign.toUtf8().data(),
w->vAlign.toUtf8().data(),
w->words.toUtf8().data());
++ci;
}
*/
// assign title, subtitle and copyright
QList<int> keys = creditMap.uniqueKeys(); // note: ignoring credit-words at the same y pos
// if any credit-words present, the highest is the title
// note that the keys are sorted in ascending order
// -> use the last key
if (keys.size() >= 1)
crwTitle = creditMap.value(keys.at(keys.size() - 1));
// if two credit-words present and both are in the header or the footer,
// the lowest one is the subtitle, else it is the copyright
if (keys.size() == 2) {
if (nWordsHeader == 2 || nWordsFooter == 2)
crwSubTitle = creditMap.value(keys.at(0));
else
crwCopyRight = creditMap.value(keys.at(0));
}
// if three or more credit-words present
// the second-highest is the subtitle
// the lowest one is the copyright
if (keys.size() >= 3) {
crwSubTitle = creditMap.value(keys.at(keys.size() - 2));
crwCopyRight = creditMap.value(keys.at(0));
}
/*
if (crwTitle) qDebug("title='%s'", crwTitle->words.toUtf8().data());
if (crwSubTitle) qDebug("subtitle='%s'", crwSubTitle->words.toUtf8().data());
if (crwComposer) qDebug("composer='%s'", crwComposer->words.toUtf8().data());
if (crwPoet) qDebug("poet='%s'", crwPoet->words.toUtf8().data());
if (crwCopyRight) qDebug("copyright='%s'", crwCopyRight->words.toUtf8().data());
*/
QString strTitle;
QString strSubTitle;
QString strComposer;
QString strPoet;
QString strTranslator;
if (crwTitle || crwSubTitle || crwComposer || crwPoet || crwCopyRight) {
// use credits
if (crwTitle) strTitle = crwTitle->words;
if (crwSubTitle) strSubTitle = crwSubTitle->words;
if (crwComposer) strComposer = crwComposer->words;
if (crwPoet) strPoet = crwPoet->words;
}
else {
// use metadata
if (!(score->metaTag("movementTitle").isEmpty() && score->metaTag("workTitle").isEmpty())) {
strTitle = score->metaTag("movementTitle");
if (strTitle.isEmpty())
strTitle = score->metaTag("workTitle");
}
if (!(score->metaTag("movementNumber").isEmpty() && score->metaTag("workNumber").isEmpty())) {
strSubTitle = score->metaTag("movementNumber");
if (strSubTitle.isEmpty())
strSubTitle = score->metaTag("workNumber");
}
QString metaComposer = score->metaTag("composer");
QString metaPoet = score->metaTag("poet");
QString metaTranslator = score->metaTag("translator");
if (!metaComposer.isEmpty()) strComposer = metaComposer;
if (!metaPoet.isEmpty()) strPoet = metaPoet;
if (!metaTranslator.isEmpty()) strTranslator = metaTranslator;
}
VBox* vbox = 0;
addText(vbox, score, strTitle, TEXT_STYLE_TITLE);
addText(vbox, score, strSubTitle, TEXT_STYLE_SUBTITLE);
addText(vbox, score, strComposer, TEXT_STYLE_COMPOSER);
addText(vbox, score, strPoet, TEXT_STYLE_POET);
addText(vbox, score, strTranslator, TEXT_STYLE_TRANSLATOR);
if (vbox) {
vbox->setTick(0);
score->measures()->add(vbox);
}
// if no <rights> element was read and a copyright was found in the credit-words
// set the rights metadata to the value found
// note that MusicXML files can contain at least two different copyright statements:
// - in the <rights> element (metadata)
// - in the <credit-words> (the printed version)
// while MuseScore supports only the first one
if (score->metaTag("copyright") == "" && crwCopyRight)
score->setMetaTag("copyright", crwCopyRight->words);
}
//---------------------------------------------------------
// determineTimeSig
//---------------------------------------------------------
/**
Determine the time signature based on \a beats, \a beatType and \a timeSymbol.
Sets return parameters \a st, \a bts, \a btp.
Return true if OK, false on error.
*/
static bool determineTimeSig(const QString beats, const QString beatType, const QString timeSymbol,
TimeSigType& st, int& bts, int& btp)
{
// initialize
st = TSIG_NORMAL;
bts = 0; // the beats (max 4 separated by "+") as integer
btp = 0; // beat-type as integer
// determine if timesig is valid
if (beats == "2" && beatType == "2" && timeSymbol == "cut") {
st = TSIG_ALLA_BREVE;
bts = 2;
btp = 2;
return true;
}
else if (beats == "4" && beatType == "4" && timeSymbol == "common") {
st = TSIG_FOUR_FOUR;
bts = 4;
btp = 4;
return true;
}
else {
if (!timeSymbol.isEmpty()) {
qDebug("ImportMusicXml: time symbol <%s> not recognized with beats=%s and beat-type=%s",
qPrintable(timeSymbol), qPrintable(beats), qPrintable(beatType));
return false;
}
btp = beatType.toInt();
QStringList list = beats.split("+");
for (int i = 0; i < list.size(); i++)
bts += list.at(i).toInt();
}
return true;
}
//---------------------------------------------------------
// readPageFormat
//---------------------------------------------------------