Ver código fonte

Fixing xml tests

Andrea Condoluci 9 anos atrás
pai
commit
bd3c4bcec8

+ 4 - 1
Gruntfile.js

@@ -101,7 +101,10 @@ module.exports = function (grunt) {
         },
         // JsHint setup
         jshint: {
-            all: ['Gruntfile.js', 'karma.conf.js']
+            all: [
+                'Gruntfile.js', 'karma.conf.js',
+                'node_modules/karma-musicxml2js-preprocessor/package.json', 'node_modules/karma-musicxml2js-preprocessor/lib/index.js'
+            ]
         },
         // TypeScript Type Definitions
         typings: {

+ 1 - 1
karma.conf.js

@@ -30,7 +30,7 @@ module.exports = function (config) {
         // preprocess matching files before serving them to the browser
         // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
         preprocessors: {
-            'test/data/*.xml': ['xml2js']
+            'test/data/*.xml': ['musicxml2js']
         },
 
         // test results reporter to use

+ 1 - 2
package.json

@@ -52,7 +52,6 @@
         "karma-mocha-reporter": "",
         "karma-chrome-launcher": "",
         "karma-firefox-launcher": "",
-        "karma-phantomjs-launcher": "",
-        "karma-xml2js-preprocessor": ""
+        "karma-phantomjs-launcher": ""
     }
 }

+ 1 - 1
src/Common/FileIO/Xml.ts

@@ -58,7 +58,7 @@ export class IXmlElement {
     // }
     for (let i: number = 0; i < nodes.length; i += 1) {
       let node: Node = nodes[i];
-      console.log("node: ", this.elem.nodeName, ">>", node.nodeName, node.nodeType === Node.ELEMENT_NODE);
+      //console.log("node: ", this.elem.nodeName, ">>", node.nodeName, node.nodeType === Node.ELEMENT_NODE);
       if (node.nodeType === Node.ELEMENT_NODE &&
         (nameUnset || node.nodeName.toLowerCase() === nodeName)) {
           ret.push(new IXmlElement(node as Element));

+ 7 - 10
src/MusicalScore/ScoreIO/InstrumentReader.ts

@@ -48,7 +48,7 @@ type repetitionInstructionReader = any;
 export class InstrumentReader {
   constructor(repetitionInstructionReader: repetitionInstructionReader, xmlMeasureList: IXmlElement[], instrument: Instrument) {
     // (*) this.repetitionInstructionReader = repetitionInstructionReader;
-    this.xmlMeasureList = xmlMeasureList.slice(); // FIXME .ToArray();
+    this.xmlMeasureList = xmlMeasureList;
     this.musicSheet = instrument.GetMusicSheet;
     this.instrument = instrument;
     this.activeClefs = new Array(instrument.Staves.length);
@@ -115,10 +115,9 @@ export class InstrumentReader {
       let xmlMeasureListArr: IXmlElement[] = this.xmlMeasureList[this.currentXmlMeasureIndex].elements();
       for (let xmlNode of xmlMeasureListArr) {
         if (xmlNode.name === "note") {
-          if (xmlNode.hasAttributes && xmlNode.attribute("print-object") !== undefined && xmlNode.attribute("print-spacing") !== undefined) {
+          if (xmlNode.hasAttributes && xmlNode.attribute("print-object") && xmlNode.attribute("print-spacing")) {
             continue;
           }
-          Logging.log("New Note: ", (xmlNode as any).elem.innerHTML);
           let noteStaff: number = 1;
           if (this.instrument.Staves.length > 1) {
             if (xmlNode.element("staff") !== undefined) {
@@ -143,7 +142,6 @@ export class InstrumentReader {
           let noteDivisions: number = 0;
           let noteDuration: Fraction = new Fraction(0, 1);
           let isTuplet: boolean = false;
-          // Logging.debug("NOTE", (xmlNode as any).elem.innerHTML, xmlNode.element("duration"));
           if (xmlNode.element("duration") !== undefined) {
             noteDivisions = parseInt(xmlNode.element("duration").value, 10);
             if (!isNaN(noteDivisions)) {
@@ -164,21 +162,20 @@ export class InstrumentReader {
           }
 
           let restNote: boolean = xmlNode.element("rest") !== undefined;
-          Logging.log("New note found!", (xmlNode.element("duration") as any).elem, noteDivisions, noteDuration.toString(), restNote);
+          Logging.log("New note found!", noteDivisions, noteDuration.toString(), restNote);
           let isGraceNote: boolean = xmlNode.element("grace") !== undefined || noteDivisions === 0 || isChord && lastNoteWasGrace;
           let musicTimestamp: Fraction = currentFraction.clone();
           if (isChord) {
             musicTimestamp = previousFraction.clone();
           }
-          let out: {createdNewContainer: boolean, staffEntry: SourceStaffEntry} = this.currentMeasure.findOrCreateStaffEntry(
+          this.currentStaffEntry = this.currentMeasure.findOrCreateStaffEntry(
             musicTimestamp,
             this.inSourceMeasureInstrumentIndex + noteStaff - 1,
             this.currentStaff
-          );
-          this.currentStaffEntry = out.staffEntry;
-          //let newContainerCreated: boolean = out.createdNewContainer;
+          ).staffEntry;
+          Logging.log("currentStaffEntry", this.currentStaffEntry, this.currentMeasure.VerticalSourceStaffEntryContainers.length);
 
-          if (!this.currentVoiceGenerator.hasVoiceEntry() || !isChord && !isGraceNote && !lastNoteWasGrace || !lastNoteWasGrace && isGraceNote) {
+          if (!this.currentVoiceGenerator.hasVoiceEntry() || (!isChord && !isGraceNote && !lastNoteWasGrace) || (!lastNoteWasGrace && isGraceNote)) {
             this.currentVoiceGenerator.createVoiceEntry(musicTimestamp, this.currentStaffEntry, !restNote);
           }
           if (!isGraceNote && !isChord) {

+ 16 - 16
src/MusicalScore/ScoreIO/MusicSheetReader.ts

@@ -19,6 +19,7 @@ import {AbstractNotationInstruction} from "../VoiceData/Instructions/AbstractNot
 import {Label} from "../Label";
 
 type RepetitionInstructionReader = any;
+type RepetitionCalculator = any;
 
 export class MusicSheetReader /*implements IMusicSheetReader*/ {
 
@@ -33,7 +34,7 @@ export class MusicSheetReader /*implements IMusicSheetReader*/ {
   //}
 
   private repetitionInstructionReader: RepetitionInstructionReader;
-  // private repetitionCalculator: RepetitionCalculator;
+  private repetitionCalculator: RepetitionCalculator;
   // private afterSheetReadingModules: IAfterSheetReadingModule[];
   private musicSheet: MusicSheet;
   private completeNumberOfStaves: number = 0;
@@ -168,12 +169,12 @@ export class MusicSheetReader /*implements IMusicSheetReader*/ {
       }
     }
 
-    //if (this.repetitionInstructionReader !== undefined) {
-    //  this.repetitionInstructionReader.removeRedundantInstructions();
-    //  if (this.repetitionCalculator !== undefined) {
-    //    this.repetitionCalculator.calculateRepetitions(this.musicSheet, this.repetitionInstructionReader.RepetitionInstructions);
-    //  }
-    //}
+    if (this.repetitionInstructionReader !== undefined) {
+      this.repetitionInstructionReader.removeRedundantInstructions();
+      if (this.repetitionCalculator !== undefined) {
+        this.repetitionCalculator.calculateRepetitions(this.musicSheet, this.repetitionInstructionReader.RepetitionInstructions);
+      }
+    }
     this.musicSheet.checkForInstrumentWithNoVoice();
     this.musicSheet.fillStaffList();
     //this.musicSheet.DefaultStartTempoInBpm = this.musicSheet.SheetPlaybackSetting.BeatsPerMinute;
@@ -199,10 +200,9 @@ export class MusicSheetReader /*implements IMusicSheetReader*/ {
     let counter: number = 0;
     for (let node of partInst) {
       let idNode: IXmlAttribute = node.attribute("id");
-      if (idNode !== undefined) {
+      if (idNode) {
         let currentInstrument: Instrument = instrumentDict[idNode.value];
         let xmlMeasureList: IXmlElement[] = node.elements("measure");
-        console.log("Measures; ", xmlMeasureList.length);
         let instrumentNumberOfStaves: number = 1;
         try {
           instrumentNumberOfStaves = this.getInstrumentNumberOfStavesFromXml(node);
@@ -217,9 +217,9 @@ export class MusicSheetReader /*implements IMusicSheetReader*/ {
 
         currentInstrument.createStaves(instrumentNumberOfStaves);
         instrumentReaders.push(new InstrumentReader(this.repetitionInstructionReader, xmlMeasureList, currentInstrument));
-        //if (this.repetitionInstructionReader !== undefined) {
-        //  this.repetitionInstructionReader.XmlMeasureList[counter] = xmlMeasureList;
-        //}
+        if (this.repetitionInstructionReader !== undefined) {
+          this.repetitionInstructionReader.XmlMeasureList[counter] = xmlMeasureList;
+        }
         counter++;
       }
     }
@@ -481,12 +481,12 @@ export class MusicSheetReader /*implements IMusicSheetReader*/ {
     let creditElements: IXmlElement[] = root.elements("credit");
     for (let idx: number = 0, len: number = creditElements.length; idx < len; ++idx) {
       let credit: IXmlElement = creditElements[idx];
-      if (credit.attribute("page") === undefined) { return; }
+      if (!credit.attribute("page")) { return; }
       if (credit.attribute("page").value === "1") {
         let creditChild: IXmlElement = undefined;
         if (credit !== undefined) {
           creditChild = credit.element("credit-words");
-          if (creditChild.attribute("justify") === undefined) {
+          if (!creditChild.attribute("justify")) {
             break;
           }
           let creditJustify: string = creditChild.attribute("justify").value;
@@ -616,7 +616,7 @@ export class MusicSheetReader /*implements IMusicSheetReader*/ {
   private createInstrumentGroups(entryList: IXmlElement[]): { [_: string]: Instrument; } {
     let instrumentId: number = 0;
     let instrumentDict: { [_: string]: Instrument; } = {};
-    let currentGroup: InstrumentalGroup = undefined;
+    let currentGroup: InstrumentalGroup;
     try {
       let entryArray: IXmlElement[] = entryList;
       for (let idx: number = 0, len: number = entryArray.length; idx < len; ++idx) {
@@ -750,7 +750,7 @@ export class MusicSheetReader /*implements IMusicSheetReader*/ {
     let num: number = 0;
     for (let partNode of partInst) {
       let xmlMeasureList: IXmlElement[] = partNode.elements("measure");
-      if (xmlMeasureList !== undefined) {
+      if (xmlMeasureList.length > 0) {
         let xmlMeasure: IXmlElement = xmlMeasureList[0];
         if (xmlMeasure !== undefined) {
           let stavesNode: IXmlElement = xmlMeasure.element("attributes");

+ 6 - 6
src/MusicalScore/ScoreIO/VoiceGenerator.ts

@@ -178,10 +178,10 @@ export class VoiceGenerator {
         currentStaffEntry.Link = staffEntryLink;
         let linkMusicTimestamp: Fraction = this.currentVoiceEntry.Timestamp.clone();
         let verticalSourceStaffEntryContainer: VerticalSourceStaffEntryContainer = currentMeasure.getVerticalContainerByTimestamp(linkMusicTimestamp);
-        currentStaffEntry = verticalSourceStaffEntryContainer[index];
+        currentStaffEntry = verticalSourceStaffEntryContainer.StaffEntries[index];
         if (currentStaffEntry === undefined) {
             currentStaffEntry = new SourceStaffEntry(verticalSourceStaffEntryContainer, currentStaff);
-            verticalSourceStaffEntryContainer[index] = currentStaffEntry;
+            verticalSourceStaffEntryContainer.StaffEntries[index] = currentStaffEntry;
         }
         currentStaffEntry.VoiceEntries.push(this.currentVoiceEntry);
         staffEntryLink.LinkStaffEntries.push(currentStaffEntry);
@@ -484,7 +484,7 @@ export class VoiceGenerator {
         }
         let graceNode: IXmlElement = node.element("grace");
         if (graceNode !== undefined && graceNode.attributes()) {
-            if (graceNode.attribute("slash") !== undefined) {
+            if (graceNode.attribute("slash")) {
                 let slash: string = graceNode.attribute("slash").value;
                 if (slash === "yes") {
                     note.GraceNoteSlash = true;
@@ -529,7 +529,7 @@ export class VoiceGenerator {
                     let type: string = tupletNode.attribute("type").value;
                     if (type === "start") {
                         let tupletNumber: number = 1;
-                        if (tupletNode.attribute("nummber") !== undefined) {
+                        if (tupletNode.attribute("number")) {
                             tupletNumber = parseInt(tupletNode.attribute("number").value, 10);
                         }
                         let tupletLabelNumber: number = 0;
@@ -562,7 +562,7 @@ export class VoiceGenerator {
                         this.openTupletNumber = tupletNumber;
                     } else if (type === "stop") {
                         let tupletNumber: number = 1;
-                        if (tupletNode.attribute("number") !== undefined) {
+                        if (tupletNode.attribute("number")) {
                             tupletNumber = parseInt(tupletNode.attribute("number").value, 10);
                         }
                         let tuplet: Tuplet = this.tupletDict[tupletNumber];
@@ -587,7 +587,7 @@ export class VoiceGenerator {
             if (n.hasAttributes) {
                 let type: string = n.attribute("type").value;
                 let tupletnumber: number = 1;
-                if (n.attribute("number") !== undefined) {
+                if (n.attribute("number")) {
                     tupletnumber = parseInt(n.attribute("number").value, 10);
                 }
                 let noTupletNumbering: boolean = isNaN(tupletnumber);

+ 15 - 15
src/MusicalScore/VoiceData/SourceMeasure.ts

@@ -6,6 +6,7 @@ import {Staff} from "./Staff";
 import {VoiceEntry} from "./VoiceEntry";
 import {Voice} from "./Voice";
 import {MusicSheet} from "../MusicSheet";
+//import {Logging} from "../../Common/logging";
 
 type MultiExpression = any;
 type MultiTempoExpression = any;
@@ -116,26 +117,24 @@ export class SourceMeasure {
         inMeasureTimestamp: Fraction, inSourceMeasureStaffIndex: number, staff: Staff
     ): {createdNewContainer: boolean, staffEntry: SourceStaffEntry} {
         // FIXME Andrea: debug & Test
-        let createdNewContainer: boolean = false;
         let staffEntry: SourceStaffEntry = undefined;
         // Find:
-        let existingVerticalSourceStaffEntryContainer: VerticalSourceStaffEntryContainer = undefined;
-        for (let k: number = 0; k < this.verticalSourceStaffEntryContainers.length; k++) {
-            if (this.verticalSourceStaffEntryContainers[k].Timestamp.Equals(inMeasureTimestamp)) {
-                existingVerticalSourceStaffEntryContainer = this.verticalSourceStaffEntryContainers[k];
+        let existingVerticalSourceStaffEntryContainer: VerticalSourceStaffEntryContainer;
+        for (let container of this.verticalSourceStaffEntryContainers) {
+            if (container.Timestamp.Equals(inMeasureTimestamp)) {
+                existingVerticalSourceStaffEntryContainer = container;
                 break;
             }
         }
         if (existingVerticalSourceStaffEntryContainer !== undefined) {
-            if (existingVerticalSourceStaffEntryContainer[inSourceMeasureStaffIndex] !== undefined) {
-                staffEntry = existingVerticalSourceStaffEntryContainer[inSourceMeasureStaffIndex];
+            if (existingVerticalSourceStaffEntryContainer.StaffEntries[inSourceMeasureStaffIndex] !== undefined) {
+                staffEntry = existingVerticalSourceStaffEntryContainer.StaffEntries[inSourceMeasureStaffIndex];
             } else {
                 staffEntry = new SourceStaffEntry(existingVerticalSourceStaffEntryContainer, staff);
-                existingVerticalSourceStaffEntryContainer[inSourceMeasureStaffIndex] = staffEntry;
+                existingVerticalSourceStaffEntryContainer.StaffEntries[inSourceMeasureStaffIndex] = staffEntry;
             }
-            return {createdNewContainer: createdNewContainer, staffEntry: staffEntry};
+            return {createdNewContainer: false, staffEntry: staffEntry};
         }
-        createdNewContainer = true;
         let last: VerticalSourceStaffEntryContainer = this.verticalSourceStaffEntryContainers[this.verticalSourceStaffEntryContainers.length - 1];
         if (this.verticalSourceStaffEntryContainers.length === 0 || last.Timestamp.lt(inMeasureTimestamp)) {
             let container: VerticalSourceStaffEntryContainer = new VerticalSourceStaffEntryContainer(
@@ -143,7 +142,7 @@ export class SourceMeasure {
             );
             this.verticalSourceStaffEntryContainers.push(container);
             staffEntry = new SourceStaffEntry(container, staff);
-            container[inSourceMeasureStaffIndex] = staffEntry;
+            container.StaffEntries[inSourceMeasureStaffIndex] = staffEntry;
         } else {
             for (
                 let i: number = this.verticalSourceStaffEntryContainers.length - 1;
@@ -155,7 +154,7 @@ export class SourceMeasure {
                     );
                     this.verticalSourceStaffEntryContainers.splice(i + 1, 0, container);
                     staffEntry = new SourceStaffEntry(container, staff);
-                    container[inSourceMeasureStaffIndex] = staffEntry;
+                    container.StaffEntries[inSourceMeasureStaffIndex] = staffEntry;
                     break;
                 }
                 if (i === 0) {
@@ -164,12 +163,13 @@ export class SourceMeasure {
                     );
                     this.verticalSourceStaffEntryContainers.splice(i, 0, container);
                     staffEntry = new SourceStaffEntry(container, staff);
-                    container[inSourceMeasureStaffIndex] = staffEntry;
+                    container.StaffEntries[inSourceMeasureStaffIndex] = staffEntry;
                     break;
                 }
             }
         }
-        return {createdNewContainer: createdNewContainer, staffEntry: staffEntry};
+        //Logging.debug("created new container: ", staffEntry, this.verticalSourceStaffEntryContainers);
+        return {createdNewContainer: true, staffEntry: staffEntry};
     }
     public findOrCreateVoiceEntry(sse: SourceStaffEntry, voice: Voice): { createdVoiceEntry: boolean, voiceEntry: VoiceEntry } {
         let ve: VoiceEntry = undefined;
@@ -279,7 +279,7 @@ export class SourceMeasure {
     public getEntriesPerStaff(staffIndex: number): SourceStaffEntry[] {
         let sourceStaffEntries: SourceStaffEntry[] = [];
         for (let container of this.VerticalSourceStaffEntryContainers) {
-            let sse: SourceStaffEntry = container[staffIndex];
+            let sse: SourceStaffEntry = container.StaffEntries[staffIndex];
             if (sse !== undefined) { sourceStaffEntries.push(sse); }
         }
         return sourceStaffEntries;

+ 13 - 15
test/MusicalScore/ScoreIO/MusicSheetReader.ts

@@ -2,9 +2,11 @@ import {MusicSheetReader} from "../../../src/MusicalScore/ScoreIO/MusicSheetRead
 import {MusicSheet} from "../../../src/MusicalScore/MusicSheet";
 import {IXmlElement} from "../../../src/Common/FileIO/Xml";
 
+
+
 describe("Music Sheet Reader Tests", () => {
     // Initialize variables
-    let path: string = "/test/data/MuzioClementi_SonatinaOpus36No1_Part1.xml";
+    let path: string = "test/data/MuzioClementi_SonatinaOpus36No1_Part1.xml";
     let reader: MusicSheetReader = new MusicSheetReader();
     let score: IXmlElement;
     let sheet: MusicSheet;
@@ -14,15 +16,8 @@ describe("Music Sheet Reader Tests", () => {
     }
 
     before((): void => {
-        let parser: DOMParser = new DOMParser();
-        let dict: { [filename: string]: any; } = (window as any).__xml__;
-        for (let filename in dict) {
-          if (dict.hasOwnProperty(filename)) {
-            dict[filename] = parser.parseFromString(dict[filename], "text/xml");
-          }
-        }
         // Load the xml file
-        let doc: Document = getSheet("MuzioClementi_SonatinaOpus36No1_Part1.xml");
+        let doc: Document = getSheet(path);
         chai.expect(doc).to.not.be.undefined;
         score = new IXmlElement(doc.getElementsByTagName("score-partwise")[0]);
         // chai.expect(score).to.not.be.undefined;
@@ -37,6 +32,10 @@ describe("Music Sheet Reader Tests", () => {
       // cleanup?
     });
 
+    it("Check XML", (done: MochaDone) => {
+      done();
+    });
+
     it("Read title and composer", (done: MochaDone) => {
         chai.expect(sheet.TitleString).to.equal("Sonatina Op.36 No 1 Teil 1 Allegro");
         chai.expect(sheet.ComposerString).to.equal("Muzio Clementi");
@@ -44,24 +43,23 @@ describe("Music Sheet Reader Tests", () => {
     });
 
     it("Measures", (done: MochaDone) => {
-        // chai.expect(root.element("part").elements("measure").length).to.equal(38);
         chai.expect(sheet.SourceMeasures.length).to.equal(38);
         console.log("First Measure: ", sheet.SourceMeasures[0]);
-        // console.log("Notes on first Measure: ", sheet.SourceMeasures[0].VerticalSourceStaffEntryContainers[0].StaffEntries[0]);
-        // chai.expect(sheet.)
         done();
     });
 
     it("Instruments", (done: MochaDone) => {
-        // chai.expect(root.elements("part").length).to.equal(2);
         chai.expect(reader.CompleteNumberOfStaves).to.equal(2);
         chai.expect(sheet.Instruments.length).to.equal(2);
         chai.expect(sheet.InstrumentalGroups.length).to.equal(2);
-        console.log("SheetErrors: ", sheet.SheetErrors);
-        console.log("Sheet", sheet);
         chai.expect(sheet.Instruments[0].Name).to.equal("Piano (right)");
         chai.expect(sheet.Instruments[1].Name).to.equal("Piano (left)");
         done();
     });
 
+    it("Notes", (done: MochaDone) => {
+        // Staff Entries on first measure
+        // chai.expect(sheet.SourceMeasures[0].VerticalSourceStaffEntryContainers[0].StaffEntries.length).to.equal(4);
+        done();
+    })
 });