InstrumentReader.ts 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  1. import {Instrument} from "../Instrument";
  2. import {MusicSheet} from "../MusicSheet";
  3. import {VoiceGenerator} from "./VoiceGenerator";
  4. import {Staff} from "../VoiceData/Staff";
  5. import {SourceMeasure} from "../VoiceData/SourceMeasure";
  6. import {SourceStaffEntry} from "../VoiceData/SourceStaffEntry";
  7. import {ClefInstruction} from "../VoiceData/Instructions/ClefInstruction";
  8. import {KeyInstruction} from "../VoiceData/Instructions/KeyInstruction";
  9. import {RhythmInstruction} from "../VoiceData/Instructions/RhythmInstruction";
  10. import {AbstractNotationInstruction} from "../VoiceData/Instructions/AbstractNotationInstruction";
  11. import {Fraction} from "../../Common/DataObjects/Fraction";
  12. import {IXmlElement} from "../../Common/FileIO/Xml";
  13. import {ITextTranslation} from "../Interfaces/ITextTranslation";
  14. import {MusicSheetReadingException} from "../Exceptions";
  15. import {ClefEnum} from "../VoiceData/Instructions/ClefInstruction";
  16. import {RhythmSymbolEnum} from "../VoiceData/Instructions/RhythmInstruction";
  17. import {KeyEnum} from "../VoiceData/Instructions/KeyInstruction";
  18. import {IXmlAttribute} from "../../Common/FileIO/Xml";
  19. import {ChordSymbolContainer} from "../VoiceData/ChordSymbolContainer";
  20. import log from "loglevel";
  21. import {MidiInstrument} from "../VoiceData/Instructions/ClefInstruction";
  22. import {ChordSymbolReader} from "./MusicSymbolModules/ChordSymbolReader";
  23. import {ExpressionReader} from "./MusicSymbolModules/ExpressionReader";
  24. import {RepetitionInstructionReader} from "./MusicSymbolModules/RepetitionInstructionReader";
  25. import {SlurReader} from "./MusicSymbolModules/SlurReader";
  26. import {StemDirectionType} from "../VoiceData/VoiceEntry";
  27. import {NoteType, NoteTypeHandler} from "../VoiceData";
  28. import {SystemLinesEnumHelper} from "../Graphical";
  29. //import Dictionary from "typescript-collections/dist/lib/Dictionary";
  30. // FIXME: The following classes are missing
  31. //type ChordSymbolContainer = any;
  32. //type SlurReader = any;
  33. //type RepetitionInstructionReader = any;
  34. //declare class MusicSymbolModuleFactory {
  35. // public static createSlurReader(x: any): any;
  36. //}
  37. //
  38. //class MetronomeReader {
  39. // public static addMetronomeSettings(xmlNode: IXmlElement, musicSheet: MusicSheet): void { }
  40. // public static readMetronomeInstructions(xmlNode: IXmlElement, musicSheet: MusicSheet, currentXmlMeasureIndex: number): void { }
  41. // public static readTempoInstruction(soundNode: IXmlElement, musicSheet: MusicSheet, currentXmlMeasureIndex: number): void { }
  42. //}
  43. //
  44. //class ChordSymbolReader {
  45. // public static readChordSymbol(xmlNode:IXmlElement, musicSheet:MusicSheet, activeKey:any): void {
  46. // }
  47. //}
  48. /**
  49. * An InstrumentReader is used during the reading phase to keep parsing new measures from the MusicXML file
  50. * with the readNextXmlMeasure method.
  51. */
  52. export class InstrumentReader {
  53. constructor(repetitionInstructionReader: RepetitionInstructionReader, xmlMeasureList: IXmlElement[], instrument: Instrument) {
  54. this.repetitionInstructionReader = repetitionInstructionReader;
  55. this.xmlMeasureList = xmlMeasureList;
  56. this.musicSheet = instrument.GetMusicSheet;
  57. this.instrument = instrument;
  58. this.activeClefs = new Array(instrument.Staves.length);
  59. this.activeClefsHaveBeenInitialized = new Array(instrument.Staves.length);
  60. for (let i: number = 0; i < instrument.Staves.length; i++) {
  61. this.activeClefsHaveBeenInitialized[i] = false;
  62. }
  63. this.createExpressionGenerators(instrument.Staves.length);
  64. this.slurReader = new SlurReader(this.musicSheet);
  65. }
  66. private repetitionInstructionReader: RepetitionInstructionReader;
  67. private xmlMeasureList: IXmlElement[];
  68. private musicSheet: MusicSheet;
  69. private slurReader: SlurReader;
  70. private instrument: Instrument;
  71. private voiceGeneratorsDict: { [n: number]: VoiceGenerator; } = {};
  72. private staffMainVoiceGeneratorDict: { [staffId: number]: VoiceGenerator } = {};
  73. private inSourceMeasureInstrumentIndex: number;
  74. private divisions: number = 0;
  75. private currentMeasure: SourceMeasure;
  76. private previousMeasure: SourceMeasure;
  77. private currentClefNumber: number = 1;
  78. private currentXmlMeasureIndex: number = 0;
  79. private currentStaff: Staff;
  80. private currentStaffEntry: SourceStaffEntry;
  81. private activeClefs: ClefInstruction[];
  82. private activeKey: KeyInstruction;
  83. private activeRhythm: RhythmInstruction;
  84. private activeClefsHaveBeenInitialized: boolean[];
  85. private activeKeyHasBeenInitialized: boolean = false;
  86. private abstractInstructions: [number, AbstractNotationInstruction][] = [];
  87. private openChordSymbolContainers: ChordSymbolContainer[] = [];
  88. private expressionReaders: ExpressionReader[];
  89. private currentVoiceGenerator: VoiceGenerator;
  90. //private openSlurDict: { [n: number]: Slur; } = {};
  91. private maxTieNoteFraction: Fraction;
  92. public get ActiveKey(): KeyInstruction {
  93. return this.activeKey;
  94. }
  95. public get MaxTieNoteFraction(): Fraction {
  96. return this.maxTieNoteFraction;
  97. }
  98. public get ActiveRhythm(): RhythmInstruction {
  99. return this.activeRhythm;
  100. }
  101. public set ActiveRhythm(value: RhythmInstruction) {
  102. this.activeRhythm = value;
  103. }
  104. /**
  105. * Main CreateSheet: read the next XML Measure and save all data to the given [[SourceMeasure]].
  106. * @param currentMeasure
  107. * @param measureStartAbsoluteTimestamp - Using this instead of currentMeasure.AbsoluteTimestamp as it isn't set yet
  108. * @param guitarPro
  109. * @returns {boolean}
  110. */
  111. public readNextXmlMeasure(currentMeasure: SourceMeasure, measureStartAbsoluteTimestamp: Fraction, guitarPro: boolean): boolean {
  112. if (this.currentXmlMeasureIndex >= this.xmlMeasureList.length) {
  113. return false;
  114. }
  115. this.currentMeasure = currentMeasure;
  116. this.inSourceMeasureInstrumentIndex = this.musicSheet.getGlobalStaffIndexOfFirstStaff(this.instrument);
  117. if (this.repetitionInstructionReader !== undefined) {
  118. this.repetitionInstructionReader.prepareReadingMeasure(currentMeasure, this.currentXmlMeasureIndex);
  119. }
  120. let currentFraction: Fraction = new Fraction(0, 1);
  121. let previousFraction: Fraction = new Fraction(0, 1);
  122. let divisionsException: boolean = false;
  123. this.maxTieNoteFraction = new Fraction(0, 1);
  124. let lastNoteWasGrace: boolean = false;
  125. try {
  126. const xmlMeasureListArr: IXmlElement[] = this.xmlMeasureList[this.currentXmlMeasureIndex].elements();
  127. for (const xmlNode of xmlMeasureListArr) {
  128. if (xmlNode.name === "print") {
  129. const newSystemAttr: IXmlAttribute = xmlNode.attribute("new-system");
  130. if (newSystemAttr?.value === "yes") {
  131. currentMeasure.printNewSystemXml = true;
  132. }
  133. const newPageAttr: IXmlAttribute = xmlNode.attribute("new-page");
  134. if (newPageAttr?.value === "yes") {
  135. currentMeasure.printNewPageXml = true;
  136. }
  137. } else if (xmlNode.name === "note") {
  138. let printObject: boolean = true;
  139. if (xmlNode.hasAttributes && xmlNode.attribute("print-object") &&
  140. xmlNode.attribute("print-object").value === "no") {
  141. printObject = false; // note will not be rendered, but still parsed for Playback etc.
  142. // if (xmlNode.attribute("print-spacing")) {
  143. // if (xmlNode.attribute("print-spacing").value === "yes" {
  144. // // TODO give spacing for invisible notes even when not displayed. might be hard with Vexflow formatting
  145. }
  146. let noteStaff: number = 1;
  147. if (this.instrument.Staves.length > 1) {
  148. if (xmlNode.element("staff") !== undefined) {
  149. noteStaff = parseInt(xmlNode.element("staff").value, 10);
  150. if (isNaN(noteStaff)) {
  151. log.debug("InstrumentReader.readNextXmlMeasure.get staff number");
  152. noteStaff = 1;
  153. }
  154. }
  155. }
  156. this.currentStaff = this.instrument.Staves[noteStaff - 1];
  157. const isChord: boolean = xmlNode.element("chord") !== undefined;
  158. if (xmlNode.element("voice") !== undefined) {
  159. const noteVoice: number = parseInt(xmlNode.element("voice").value, 10);
  160. this.currentVoiceGenerator = this.getOrCreateVoiceGenerator(noteVoice, noteStaff - 1);
  161. } else {
  162. if (!isChord || this.currentVoiceGenerator === undefined) {
  163. this.currentVoiceGenerator = this.getOrCreateVoiceGenerator(1, noteStaff - 1);
  164. }
  165. }
  166. let noteDivisions: number = 0;
  167. let noteDuration: Fraction = new Fraction(0, 1);
  168. let normalNotes: number = 2;
  169. let typeDuration: Fraction = undefined;
  170. let isTuplet: boolean = false;
  171. if (xmlNode.element("duration") !== undefined) {
  172. noteDivisions = parseInt(xmlNode.element("duration").value, 10);
  173. if (!isNaN(noteDivisions)) {
  174. noteDuration = new Fraction(noteDivisions, 4 * this.divisions);
  175. if (noteDivisions === 0) {
  176. noteDuration = this.getNoteDurationFromTypeNode(xmlNode);
  177. } else {
  178. typeDuration = this.getNoteDurationFromTypeNode(xmlNode);
  179. }
  180. if (xmlNode.element("time-modification") !== undefined) {
  181. noteDuration = this.getNoteDurationForTuplet(xmlNode);
  182. const time: IXmlElement = xmlNode.element("time-modification");
  183. if (time !== undefined) {
  184. if (time.element("normal-notes") !== undefined) {
  185. normalNotes = parseInt(time.element("normal-notes").value, 10);
  186. }
  187. }
  188. isTuplet = true;
  189. }
  190. } else {
  191. const errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/NoteDurationError", "Invalid Note Duration.");
  192. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  193. log.debug("InstrumentReader.readNextXmlMeasure", errorMsg);
  194. continue;
  195. }
  196. }
  197. const restNote: boolean = xmlNode.element("rest") !== undefined;
  198. //log.info("New note found!", noteDivisions, noteDuration.toString(), restNote);
  199. const notationsNode: IXmlElement = xmlNode.element("notations"); // used for multiple checks further on
  200. const isGraceNote: boolean = xmlNode.element("grace") !== undefined || noteDivisions === 0 || isChord && lastNoteWasGrace;
  201. let graceNoteSlash: boolean = false;
  202. let graceSlur: boolean = false;
  203. if (isGraceNote) {
  204. const graceNode: IXmlElement = xmlNode.element("grace");
  205. if (graceNode && graceNode.attributes()) {
  206. if (graceNode.attribute("slash")) {
  207. const slash: string = graceNode.attribute("slash").value;
  208. if (slash === "yes") {
  209. graceNoteSlash = true;
  210. }
  211. }
  212. }
  213. noteDuration = this.getNoteDurationFromTypeNode(xmlNode);
  214. const notationNode: IXmlElement = xmlNode.element("notations");
  215. if (notationNode !== undefined) {
  216. if (notationNode.element("slur") !== undefined) {
  217. graceSlur = true;
  218. // grace slurs could be non-binary, but VexFlow.GraceNoteGroup modifier system is currently only boolean for slurs.
  219. }
  220. }
  221. }
  222. // check for cue note
  223. let isCueNote: boolean = false;
  224. const cueNode: IXmlElement = xmlNode.element("cue");
  225. if (cueNode !== undefined) {
  226. isCueNote = true;
  227. }
  228. // alternative: check for <type size="cue">
  229. const typeNode: IXmlElement = xmlNode.element("type");
  230. let noteTypeXml: NoteType = NoteType.UNDEFINED;
  231. if (typeNode !== undefined) {
  232. const sizeAttr: Attr = typeNode.attribute("size");
  233. if (sizeAttr !== undefined && sizeAttr !== null) {
  234. if (sizeAttr.value === "cue") {
  235. isCueNote = true;
  236. }
  237. }
  238. noteTypeXml = NoteTypeHandler.StringToNoteType(typeNode.value);
  239. }
  240. // check stem element
  241. let stemDirectionXml: StemDirectionType = StemDirectionType.Undefined;
  242. let stemColorXml: string;
  243. const stemNode: IXmlElement = xmlNode.element("stem");
  244. if (stemNode !== undefined) {
  245. switch (stemNode.value) {
  246. case "down":
  247. stemDirectionXml = StemDirectionType.Down;
  248. break;
  249. case "up":
  250. stemDirectionXml = StemDirectionType.Up;
  251. break;
  252. case "double":
  253. stemDirectionXml = StemDirectionType.Double;
  254. break;
  255. case "none":
  256. stemDirectionXml = StemDirectionType.None;
  257. break;
  258. default:
  259. stemDirectionXml = StemDirectionType.Undefined;
  260. }
  261. const stemColorAttr: Attr = stemNode.attribute("color");
  262. if (stemColorAttr) { // can be null, maybe also undefined
  263. stemColorXml = this.parseXmlColor(stemColorAttr.value);
  264. }
  265. }
  266. // check Tremolo
  267. let tremoloStrokes: number = 0;
  268. if (notationsNode !== undefined) {
  269. const ornamentsNode: IXmlElement = notationsNode.element("ornaments");
  270. if (ornamentsNode !== undefined) {
  271. const tremoloNode: IXmlElement = ornamentsNode.element("tremolo");
  272. if (tremoloNode !== undefined) {
  273. const tremoloType: Attr = tremoloNode.attribute("type");
  274. if (tremoloType && tremoloType.value === "single") {
  275. const tremoloStrokesGiven: number = parseInt(tremoloNode.value, 10);
  276. if (tremoloStrokesGiven > 0) {
  277. tremoloStrokes = tremoloStrokesGiven;
  278. }
  279. }
  280. // TODO implement type "start". Vexflow doesn't have tremolo beams yet though (shorter than normal beams)
  281. }
  282. }
  283. }
  284. // check notehead/color
  285. let noteheadColorXml: string;
  286. const noteheadNode: IXmlElement = xmlNode.element("notehead");
  287. if (noteheadNode) {
  288. const colorAttr: Attr = noteheadNode.attribute("color");
  289. if (colorAttr) {
  290. noteheadColorXml = this.parseXmlColor(colorAttr.value);
  291. }
  292. }
  293. let noteColorXml: string;
  294. const noteColorAttr: Attr = xmlNode.attribute("color");
  295. if (noteColorAttr) { // can be undefined
  296. noteColorXml = this.parseXmlColor(noteColorAttr.value);
  297. if (noteheadColorXml === undefined) {
  298. noteheadColorXml = noteColorXml;
  299. }
  300. if (stemColorXml === undefined) {
  301. stemColorXml = noteColorXml;
  302. }
  303. }
  304. let musicTimestamp: Fraction = currentFraction.clone();
  305. if (isChord) {
  306. musicTimestamp = previousFraction.clone();
  307. }
  308. this.currentStaffEntry = this.currentMeasure.findOrCreateStaffEntry(
  309. musicTimestamp,
  310. this.inSourceMeasureInstrumentIndex + noteStaff - 1,
  311. this.currentStaff
  312. ).staffEntry;
  313. //log.info("currentStaffEntry", this.currentStaffEntry, this.currentMeasure.VerticalSourceStaffEntryContainers.length);
  314. if (!this.currentVoiceGenerator.hasVoiceEntry()
  315. || (!isChord && !isGraceNote && !lastNoteWasGrace)
  316. || (isGraceNote && !lastNoteWasGrace)
  317. || (isGraceNote && !isChord)
  318. || (!isGraceNote && lastNoteWasGrace)
  319. ) {
  320. this.currentVoiceGenerator.createVoiceEntry(musicTimestamp, this.currentStaffEntry, !restNote && !isGraceNote,
  321. isGraceNote, graceNoteSlash, graceSlur);
  322. }
  323. if (!isGraceNote && !isChord) {
  324. previousFraction = currentFraction.clone();
  325. currentFraction.Add(noteDuration);
  326. }
  327. if (
  328. isChord &&
  329. this.currentStaffEntry !== undefined &&
  330. this.currentStaffEntry.ParentStaff !== this.currentStaff
  331. ) {
  332. this.currentStaffEntry = this.currentVoiceGenerator.checkForStaffEntryLink(
  333. this.inSourceMeasureInstrumentIndex + noteStaff - 1, this.currentStaff, this.currentStaffEntry, this.currentMeasure
  334. );
  335. }
  336. const beginOfMeasure: boolean = (
  337. this.currentStaffEntry !== undefined &&
  338. this.currentStaffEntry.Timestamp !== undefined &&
  339. this.currentStaffEntry.Timestamp.Equals(new Fraction(0, 1)) && !this.currentStaffEntry.hasNotes()
  340. );
  341. this.saveAbstractInstructionList(this.instrument.Staves.length, beginOfMeasure);
  342. if (this.openChordSymbolContainers.length !== 0) {
  343. this.currentStaffEntry.ChordContainers = this.openChordSymbolContainers;
  344. // TODO handle multiple chords on one note/staffentry
  345. this.openChordSymbolContainers = [];
  346. }
  347. if (this.activeRhythm !== undefined) {
  348. // (*) this.musicSheet.SheetPlaybackSetting.Rhythm = this.activeRhythm.Rhythm;
  349. }
  350. if (!isTuplet && !isGraceNote) {
  351. noteDuration = new Fraction(noteDivisions, 4 * this.divisions);
  352. }
  353. this.currentVoiceGenerator.read(
  354. xmlNode, noteDuration, typeDuration, noteTypeXml, normalNotes, restNote,
  355. this.currentStaffEntry, this.currentMeasure,
  356. measureStartAbsoluteTimestamp,
  357. this.maxTieNoteFraction, isChord, guitarPro,
  358. printObject, isCueNote, stemDirectionXml, tremoloStrokes, stemColorXml, noteheadColorXml
  359. );
  360. // notationsNode created further up for multiple checks
  361. if (notationsNode !== undefined && notationsNode.element("dynamics") !== undefined) {
  362. const expressionReader: ExpressionReader = this.expressionReaders[this.readExpressionStaffNumber(xmlNode) - 1];
  363. if (expressionReader !== undefined) {
  364. expressionReader.readExpressionParameters(
  365. xmlNode, this.instrument, this.divisions, currentFraction, previousFraction, this.currentMeasure.MeasureNumber, false
  366. );
  367. expressionReader.read(
  368. xmlNode, this.currentMeasure, previousFraction
  369. );
  370. }
  371. }
  372. lastNoteWasGrace = isGraceNote;
  373. } else if (xmlNode.name === "attributes") {
  374. const divisionsNode: IXmlElement = xmlNode.element("divisions");
  375. if (divisionsNode !== undefined) {
  376. this.divisions = parseInt(divisionsNode.value, 10);
  377. if (isNaN(this.divisions)) {
  378. const errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/DivisionError",
  379. "Invalid divisions value at Instrument: ");
  380. log.debug("InstrumentReader.readNextXmlMeasure", errorMsg);
  381. this.divisions = this.readDivisionsFromNotes();
  382. if (this.divisions > 0) {
  383. this.musicSheet.SheetErrors.push(errorMsg + this.instrument.Name);
  384. } else {
  385. divisionsException = true;
  386. throw new MusicSheetReadingException(errorMsg + this.instrument.Name);
  387. }
  388. }
  389. }
  390. if (
  391. xmlNode.element("divisions") === undefined &&
  392. this.divisions === 0 &&
  393. this.currentXmlMeasureIndex === 0
  394. ) {
  395. const errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/DivisionError", "Invalid divisions value at Instrument: ");
  396. this.divisions = this.readDivisionsFromNotes();
  397. if (this.divisions > 0) {
  398. this.musicSheet.SheetErrors.push(errorMsg + this.instrument.Name);
  399. } else {
  400. divisionsException = true;
  401. throw new MusicSheetReadingException(errorMsg + this.instrument.Name);
  402. }
  403. }
  404. this.addAbstractInstruction(xmlNode, guitarPro);
  405. if (currentFraction.Equals(new Fraction(0, 1)) &&
  406. this.isAttributesNodeAtBeginOfMeasure(this.xmlMeasureList[this.currentXmlMeasureIndex], xmlNode)) {
  407. this.saveAbstractInstructionList(this.instrument.Staves.length, true);
  408. }
  409. if (this.isAttributesNodeAtEndOfMeasure(this.xmlMeasureList[this.currentXmlMeasureIndex], xmlNode)) {
  410. this.saveClefInstructionAtEndOfMeasure();
  411. }
  412. } else if (xmlNode.name === "forward") {
  413. const forFraction: number = parseInt(xmlNode.element("duration").value, 10);
  414. currentFraction.Add(new Fraction(forFraction, 4 * this.divisions));
  415. } else if (xmlNode.name === "backup") {
  416. const backFraction: number = parseInt(xmlNode.element("duration").value, 10);
  417. currentFraction.Sub(new Fraction(backFraction, 4 * this.divisions));
  418. if (currentFraction.IsNegative()) {
  419. currentFraction = new Fraction(0, 1);
  420. }
  421. previousFraction.Sub(new Fraction(backFraction, 4 * this.divisions));
  422. if (previousFraction.IsNegative()) {
  423. previousFraction = new Fraction(0, 1);
  424. }
  425. } else if (xmlNode.name === "direction") {
  426. const directionTypeNode: IXmlElement = xmlNode.element("direction-type");
  427. // (*) MetronomeReader.readMetronomeInstructions(xmlNode, this.musicSheet, this.currentXmlMeasureIndex);
  428. let relativePositionInMeasure: number = Math.min(1, currentFraction.RealValue);
  429. if (this.activeRhythm !== undefined && this.activeRhythm.Rhythm !== undefined) {
  430. relativePositionInMeasure /= this.activeRhythm.Rhythm.RealValue;
  431. }
  432. let handeled: boolean = false;
  433. if (this.repetitionInstructionReader !== undefined) {
  434. handeled = this.repetitionInstructionReader.handleRepetitionInstructionsFromWordsOrSymbols( directionTypeNode,
  435. relativePositionInMeasure);
  436. }
  437. if (!handeled) {
  438. let expressionReader: ExpressionReader = this.expressionReaders[0];
  439. const staffIndex: number = this.readExpressionStaffNumber(xmlNode) - 1;
  440. if (staffIndex < this.expressionReaders.length) {
  441. expressionReader = this.expressionReaders[staffIndex];
  442. }
  443. if (expressionReader !== undefined) {
  444. if (directionTypeNode.element("octave-shift") !== undefined) {
  445. expressionReader.readExpressionParameters(
  446. xmlNode, this.instrument, this.divisions, currentFraction, previousFraction, this.currentMeasure.MeasureNumber, true
  447. );
  448. expressionReader.addOctaveShift(xmlNode, this.currentMeasure, previousFraction.clone());
  449. }
  450. expressionReader.readExpressionParameters(
  451. xmlNode, this.instrument, this.divisions, currentFraction, previousFraction, this.currentMeasure.MeasureNumber, false
  452. );
  453. expressionReader.read(xmlNode, this.currentMeasure, currentFraction);
  454. }
  455. }
  456. } else if (xmlNode.name === "barline") {
  457. if (this.repetitionInstructionReader !== undefined) {
  458. const measureEndsSystem: boolean = false;
  459. this.repetitionInstructionReader.handleLineRepetitionInstructions(xmlNode, measureEndsSystem);
  460. if (measureEndsSystem) {
  461. this.currentMeasure.BreakSystemAfter = true;
  462. this.currentMeasure.endsPiece = true;
  463. }
  464. }
  465. const location: IXmlAttribute = xmlNode.attribute("location");
  466. if (location && location.value === "right") {
  467. const stringValue: string = xmlNode.element("bar-style")?.value;
  468. // TODO apparently we didn't anticipate bar-style not existing (the ? above was missing). how to handle?
  469. if (stringValue) {
  470. this.currentMeasure.endingBarStyleXml = stringValue;
  471. this.currentMeasure.endingBarStyleEnum = SystemLinesEnumHelper.xmlBarlineStyleToSystemLinesEnum(stringValue);
  472. }
  473. }
  474. // TODO do we need to process bars with left location too?
  475. } else if (xmlNode.name === "sound") {
  476. // (*) MetronomeReader.readTempoInstruction(xmlNode, this.musicSheet, this.currentXmlMeasureIndex);
  477. } else if (xmlNode.name === "harmony") {
  478. // new chord, could be second chord on same staffentry/note
  479. this.openChordSymbolContainers.push(ChordSymbolReader.readChordSymbol(xmlNode, this.musicSheet, this.activeKey));
  480. }
  481. }
  482. for (const j in this.voiceGeneratorsDict) {
  483. if (this.voiceGeneratorsDict.hasOwnProperty(j)) {
  484. const voiceGenerator: VoiceGenerator = this.voiceGeneratorsDict[j];
  485. voiceGenerator.checkForOpenBeam();
  486. }
  487. }
  488. if (this.currentXmlMeasureIndex === this.xmlMeasureList.length - 1) {
  489. for (let i: number = 0; i < this.instrument.Staves.length; i++) {
  490. if (!this.activeClefsHaveBeenInitialized[i]) {
  491. this.createDefaultClefInstruction(this.musicSheet.getGlobalStaffIndexOfFirstStaff(this.instrument) + i);
  492. }
  493. }
  494. if (!this.activeKeyHasBeenInitialized) {
  495. this.createDefaultKeyInstruction();
  496. }
  497. for (let i: number = 0; i < this.expressionReaders.length; i++) {
  498. const reader: ExpressionReader = this.expressionReaders[i];
  499. if (reader !== undefined) {
  500. reader.checkForOpenExpressions(this.currentMeasure, currentFraction);
  501. }
  502. }
  503. }
  504. // if this is the first measure and no BPM info found, we set it to 120
  505. // next measures will automatically inherit that value
  506. if (!this.musicSheet.HasBPMInfo) {
  507. this.currentMeasure.TempoInBPM = 120;
  508. } else if (currentMeasure.TempoInBPM === 0) {
  509. this.currentMeasure.TempoInBPM = this.previousMeasure.TempoInBPM;
  510. }
  511. } catch (e) {
  512. if (divisionsException) {
  513. throw new MusicSheetReadingException(e.Message);
  514. }
  515. const errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/MeasureError", "Error while reading Measure.");
  516. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  517. log.debug("InstrumentReader.readNextXmlMeasure", errorMsg, e);
  518. }
  519. this.previousMeasure = this.currentMeasure;
  520. this.currentXmlMeasureIndex += 1;
  521. return true;
  522. }
  523. /** Parse a color in XML format. Can be #ARGB or #RGB format, colors as byte hex values.
  524. * @return color in Vexflow format #[A]RGB or undefined for invalid xmlColorString
  525. */
  526. public parseXmlColor(xmlColorString: string): string {
  527. if (!xmlColorString) {
  528. return undefined;
  529. }
  530. if (xmlColorString.length === 7) { // #RGB
  531. return xmlColorString;
  532. } else if (xmlColorString.length === 9) { // #ARGB
  533. return "#" + xmlColorString.substr(3); // cut away alpha channel
  534. } else {
  535. return undefined; // invalid xml color
  536. }
  537. }
  538. public doCalculationsAfterDurationHasBeenSet(): void {
  539. for (const j in this.voiceGeneratorsDict) {
  540. if (this.voiceGeneratorsDict.hasOwnProperty(j)) {
  541. this.voiceGeneratorsDict[j].checkOpenTies();
  542. }
  543. }
  544. }
  545. /**
  546. * Get or create the passing [[VoiceGenerator]].
  547. * @param voiceId
  548. * @param staffId
  549. * @returns {VoiceGenerator}
  550. */
  551. private getOrCreateVoiceGenerator(voiceId: number, staffId: number): VoiceGenerator {
  552. const staff: Staff = this.instrument.Staves[staffId];
  553. let voiceGenerator: VoiceGenerator = this.voiceGeneratorsDict[voiceId];
  554. if (voiceGenerator !== undefined) {
  555. if (staff.Voices.indexOf(voiceGenerator.GetVoice) === -1) {
  556. staff.Voices.push(voiceGenerator.GetVoice);
  557. }
  558. } else {
  559. const mainVoiceGenerator: VoiceGenerator = this.staffMainVoiceGeneratorDict[staffId];
  560. if (mainVoiceGenerator !== undefined) {
  561. voiceGenerator = new VoiceGenerator(this.instrument, voiceId, this.slurReader, mainVoiceGenerator.GetVoice);
  562. staff.Voices.push(voiceGenerator.GetVoice);
  563. this.voiceGeneratorsDict[voiceId] = voiceGenerator;
  564. } else {
  565. voiceGenerator = new VoiceGenerator(this.instrument, voiceId, this.slurReader);
  566. staff.Voices.push(voiceGenerator.GetVoice);
  567. this.voiceGeneratorsDict[voiceId] = voiceGenerator;
  568. this.staffMainVoiceGeneratorDict[staffId] = voiceGenerator;
  569. }
  570. }
  571. return voiceGenerator;
  572. }
  573. private createExpressionGenerators(numberOfStaves: number): void {
  574. this.expressionReaders = new Array(numberOfStaves);
  575. for (let i: number = 0; i < numberOfStaves; i++) {
  576. this.expressionReaders[i] = new ExpressionReader(this.musicSheet, this.instrument, i + 1);
  577. }
  578. }
  579. /**
  580. * Create the default [[ClefInstruction]] for the given staff index.
  581. * @param staffIndex
  582. */
  583. private createDefaultClefInstruction(staffIndex: number): void {
  584. let first: SourceMeasure;
  585. if (this.musicSheet.SourceMeasures.length > 0) {
  586. first = this.musicSheet.SourceMeasures[0];
  587. } else {
  588. first = this.currentMeasure;
  589. }
  590. const clefInstruction: ClefInstruction = new ClefInstruction(ClefEnum.G, 0, 2);
  591. let firstStaffEntry: SourceStaffEntry;
  592. if (first.FirstInstructionsStaffEntries[staffIndex] === undefined) {
  593. firstStaffEntry = new SourceStaffEntry(undefined, undefined);
  594. first.FirstInstructionsStaffEntries[staffIndex] = firstStaffEntry;
  595. } else {
  596. firstStaffEntry = first.FirstInstructionsStaffEntries[staffIndex];
  597. firstStaffEntry.removeFirstInstructionOfTypeClefInstruction();
  598. }
  599. clefInstruction.Parent = firstStaffEntry;
  600. firstStaffEntry.Instructions.splice(0, 0, clefInstruction);
  601. }
  602. /**
  603. * Create the default [[KeyInstruction]] in case no [[KeyInstruction]] is given in the whole [[Instrument]].
  604. */
  605. private createDefaultKeyInstruction(): void {
  606. let first: SourceMeasure;
  607. if (this.musicSheet.SourceMeasures.length > 0) {
  608. first = this.musicSheet.SourceMeasures[0];
  609. } else {
  610. first = this.currentMeasure;
  611. }
  612. const keyInstruction: KeyInstruction = new KeyInstruction(undefined, 0, KeyEnum.major);
  613. for (let j: number = this.inSourceMeasureInstrumentIndex; j < this.inSourceMeasureInstrumentIndex + this.instrument.Staves.length; j++) {
  614. if (first.FirstInstructionsStaffEntries[j] === undefined) {
  615. const firstStaffEntry: SourceStaffEntry = new SourceStaffEntry(undefined, undefined);
  616. first.FirstInstructionsStaffEntries[j] = firstStaffEntry;
  617. keyInstruction.Parent = firstStaffEntry;
  618. firstStaffEntry.Instructions.push(keyInstruction);
  619. } else {
  620. const firstStaffEntry: SourceStaffEntry = first.FirstInstructionsStaffEntries[j];
  621. keyInstruction.Parent = firstStaffEntry;
  622. firstStaffEntry.removeFirstInstructionOfTypeKeyInstruction();
  623. if (firstStaffEntry.Instructions[0] instanceof ClefInstruction) {
  624. firstStaffEntry.Instructions.splice(1, 0, keyInstruction);
  625. } else {
  626. firstStaffEntry.Instructions.splice(0, 0, keyInstruction);
  627. }
  628. }
  629. }
  630. }
  631. /**
  632. * Check if the given attributesNode is at the begin of a XmlMeasure.
  633. * @param parentNode
  634. * @param attributesNode
  635. * @returns {boolean}
  636. */
  637. private isAttributesNodeAtBeginOfMeasure(parentNode: IXmlElement, attributesNode: IXmlElement): boolean {
  638. const children: IXmlElement[] = parentNode.elements();
  639. const attributesNodeIndex: number = children.indexOf(attributesNode); // FIXME | 0
  640. if (attributesNodeIndex > 0 && children[attributesNodeIndex - 1].name === "backup") {
  641. return true;
  642. }
  643. let firstNoteNodeIndex: number = -1;
  644. for (let i: number = 0; i < children.length; i++) {
  645. if (children[i].name === "note") {
  646. firstNoteNodeIndex = i;
  647. break;
  648. }
  649. }
  650. return (attributesNodeIndex < firstNoteNodeIndex && firstNoteNodeIndex > 0) || (firstNoteNodeIndex < 0);
  651. }
  652. /**
  653. * Check if the given attributesNode is at the end of a XmlMeasure.
  654. * @param parentNode
  655. * @param attributesNode
  656. * @returns {boolean}
  657. */
  658. private isAttributesNodeAtEndOfMeasure(parentNode: IXmlElement, attributesNode: IXmlElement): boolean {
  659. const childs: IXmlElement[] = parentNode.elements().slice(); // slice=arrayCopy
  660. let attributesNodeIndex: number = 0;
  661. for (let i: number = 0; i < childs.length; i++) {
  662. if (childs[i] === attributesNode) {
  663. attributesNodeIndex = i;
  664. break;
  665. }
  666. }
  667. let nextNoteNodeIndex: number = 0;
  668. for (let i: number = attributesNodeIndex; i < childs.length; i++) {
  669. if (childs[i].name === "note") {
  670. nextNoteNodeIndex = i;
  671. break;
  672. }
  673. }
  674. return attributesNodeIndex > nextNoteNodeIndex;
  675. }
  676. /**
  677. * Called only when no noteDuration is given in XML.
  678. * @param xmlNode
  679. * @returns {Fraction}
  680. */
  681. private getNoteDurationFromTypeNode(xmlNode: IXmlElement): Fraction {
  682. const typeNode: IXmlElement = xmlNode.element("type");
  683. if (typeNode !== undefined) {
  684. const type: string = typeNode.value;
  685. return this.currentVoiceGenerator.getNoteDurationFromType(type);
  686. }
  687. return new Fraction(0, 4 * this.divisions);
  688. }
  689. /**
  690. * Add (the three basic) Notation Instructions to a list
  691. * @param node
  692. * @param guitarPro
  693. */
  694. private addAbstractInstruction(node: IXmlElement, guitarPro: boolean): void {
  695. if (node.element("divisions") !== undefined) {
  696. if (node.elements().length === 1) {
  697. return;
  698. }
  699. }
  700. const transposeNode: IXmlElement = node.element("transpose");
  701. if (transposeNode !== undefined) {
  702. const chromaticNode: IXmlElement = transposeNode.element("chromatic");
  703. if (chromaticNode !== undefined) {
  704. this.instrument.PlaybackTranspose = parseInt(chromaticNode.value, 10);
  705. }
  706. }
  707. const clefList: IXmlElement[] = node.elements("clef");
  708. let errorMsg: string;
  709. if (clefList.length > 0) {
  710. for (let idx: number = 0, len: number = clefList.length; idx < len; ++idx) {
  711. const nodeList: IXmlElement = clefList[idx];
  712. let clefEnum: ClefEnum = ClefEnum.G;
  713. let line: number = 2;
  714. let staffNumber: number = 1;
  715. let clefOctaveOffset: number = 0;
  716. const lineNode: IXmlElement = nodeList.element("line");
  717. if (lineNode !== undefined) {
  718. try {
  719. line = parseInt(lineNode.value, 10);
  720. } catch (ex) {
  721. errorMsg = ITextTranslation.translateText(
  722. "ReaderErrorMessages/ClefLineError",
  723. "Invalid clef line given -> using default clef line."
  724. );
  725. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  726. line = 2;
  727. log.debug("InstrumentReader.addAbstractInstruction", errorMsg, ex);
  728. }
  729. }
  730. const signNode: IXmlElement = nodeList.element("sign");
  731. if (signNode !== undefined) {
  732. try {
  733. clefEnum = ClefEnum[signNode.value];
  734. if (!ClefInstruction.isSupportedClef(clefEnum)) {
  735. errorMsg = ITextTranslation.translateText(
  736. "ReaderErrorMessages/ClefError",
  737. "Unsupported clef found -> using default clef."
  738. );
  739. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  740. clefEnum = ClefEnum.G;
  741. line = 2;
  742. }
  743. if (clefEnum === ClefEnum.TAB) {
  744. clefOctaveOffset = -1;
  745. }
  746. } catch (e) {
  747. errorMsg = ITextTranslation.translateText(
  748. "ReaderErrorMessages/ClefError",
  749. "Invalid clef found -> using default clef."
  750. );
  751. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  752. clefEnum = ClefEnum.G;
  753. line = 2;
  754. log.debug("InstrumentReader.addAbstractInstruction", errorMsg, e);
  755. }
  756. }
  757. const clefOctaveNode: IXmlElement = nodeList.element("clef-octave-change");
  758. if (clefOctaveNode !== undefined) {
  759. try {
  760. clefOctaveOffset = parseInt(clefOctaveNode.value, 10);
  761. } catch (e) {
  762. errorMsg = ITextTranslation.translateText(
  763. "ReaderErrorMessages/ClefOctaveError",
  764. "Invalid clef octave found -> using default clef octave."
  765. );
  766. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  767. clefOctaveOffset = 0;
  768. }
  769. }
  770. if (nodeList.hasAttributes && nodeList.attributes()[0].name === "number") {
  771. try {
  772. staffNumber = parseInt(nodeList.attributes()[0].value, 10);
  773. if (staffNumber > this.currentClefNumber) {
  774. staffNumber = this.currentClefNumber;
  775. }
  776. this.currentClefNumber = staffNumber + 1;
  777. } catch (err) {
  778. errorMsg = ITextTranslation.translateText(
  779. "ReaderErrorMessages/ClefError",
  780. "Invalid clef found -> using default clef."
  781. );
  782. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  783. staffNumber = 1;
  784. this.currentClefNumber = staffNumber + 1;
  785. }
  786. }
  787. const clefInstruction: ClefInstruction = new ClefInstruction(clefEnum, clefOctaveOffset, line);
  788. this.abstractInstructions.push([staffNumber, clefInstruction]);
  789. }
  790. }
  791. if (node.element("key") !== undefined && this.instrument.MidiInstrumentId !== MidiInstrument.Percussion) {
  792. let key: number = 0;
  793. const keyNode: IXmlElement = node.element("key").element("fifths");
  794. if (keyNode !== undefined) {
  795. try {
  796. key = parseInt(keyNode.value, 10);
  797. } catch (ex) {
  798. errorMsg = ITextTranslation.translateText(
  799. "ReaderErrorMessages/KeyError",
  800. "Invalid key found -> set to default."
  801. );
  802. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  803. key = 0;
  804. log.debug("InstrumentReader.addAbstractInstruction", errorMsg, ex);
  805. }
  806. }
  807. let keyEnum: KeyEnum = KeyEnum.none;
  808. let modeNode: IXmlElement = node.element("key");
  809. if (modeNode !== undefined) {
  810. modeNode = modeNode.element("mode");
  811. }
  812. if (modeNode !== undefined) {
  813. try {
  814. keyEnum = KeyEnum[modeNode.value];
  815. } catch (ex) {
  816. errorMsg = ITextTranslation.translateText(
  817. "ReaderErrorMessages/KeyError",
  818. "Invalid key found -> set to default."
  819. );
  820. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  821. keyEnum = KeyEnum.major;
  822. log.debug("InstrumentReader.addAbstractInstruction", errorMsg, ex);
  823. }
  824. }
  825. const keyInstruction: KeyInstruction = new KeyInstruction(undefined, key, keyEnum);
  826. this.abstractInstructions.push([1, keyInstruction]);
  827. }
  828. if (node.element("time") !== undefined) {
  829. const timeNode: IXmlElement = node.element("time");
  830. let symbolEnum: RhythmSymbolEnum = RhythmSymbolEnum.NONE;
  831. let timePrintObject: boolean = true;
  832. if (timeNode !== undefined && timeNode.hasAttributes) {
  833. const symbolAttribute: IXmlAttribute = timeNode.attribute("symbol");
  834. if (symbolAttribute) {
  835. if (symbolAttribute.value === "common") {
  836. symbolEnum = RhythmSymbolEnum.COMMON;
  837. } else if (symbolAttribute.value === "cut") {
  838. symbolEnum = RhythmSymbolEnum.CUT;
  839. }
  840. }
  841. const printObjectAttribute: IXmlAttribute = timeNode.attribute("print-object");
  842. if (printObjectAttribute) {
  843. if (printObjectAttribute.value === "no") {
  844. timePrintObject = false;
  845. }
  846. }
  847. }
  848. let num: number = 0;
  849. let denom: number = 0;
  850. const senzaMisura: boolean = (timeNode !== undefined && timeNode.element("senza-misura") !== undefined);
  851. const timeList: IXmlElement[] = node.elements("time");
  852. const beatsList: IXmlElement[] = [];
  853. const typeList: IXmlElement[] = [];
  854. for (let idx: number = 0, len: number = timeList.length; idx < len; ++idx) {
  855. const xmlNode: IXmlElement = timeList[idx];
  856. beatsList.push.apply(beatsList, xmlNode.elements("beats"));
  857. typeList.push.apply(typeList, xmlNode.elements("beat-type"));
  858. }
  859. if (!senzaMisura) {
  860. try {
  861. if (beatsList !== undefined && beatsList.length > 0 && typeList !== undefined && beatsList.length === typeList.length) {
  862. const length: number = beatsList.length;
  863. const fractions: Fraction[] = new Array(length);
  864. let maxDenom: number = 0;
  865. for (let i: number = 0; i < length; i++) {
  866. const s: string = beatsList[i].value;
  867. let n: number = 0;
  868. let d: number = 0;
  869. if (s.indexOf("+") !== -1) {
  870. const numbers: string[] = s.split("+");
  871. for (let idx: number = 0, len: number = numbers.length; idx < len; ++idx) {
  872. n += parseInt(numbers[idx], 10);
  873. }
  874. } else {
  875. n = parseInt(s, 10);
  876. }
  877. d = parseInt(typeList[i].value, 10);
  878. maxDenom = Math.max(maxDenom, d);
  879. fractions[i] = new Fraction(n, d, 0, false);
  880. }
  881. for (let i: number = 0; i < length; i++) {
  882. if (fractions[i].Denominator === maxDenom) {
  883. num += fractions[i].Numerator;
  884. } else {
  885. num += (maxDenom / fractions[i].Denominator) * fractions[i].Numerator;
  886. }
  887. }
  888. denom = maxDenom;
  889. } else {
  890. num = parseInt(node.element("time").element("beats").value, 10);
  891. denom = parseInt(node.element("time").element("beat-type").value, 10);
  892. }
  893. } catch (ex) {
  894. errorMsg = ITextTranslation.translateText("ReaderErrorMessages/RhythmError", "Invalid rhythm found -> set to default.");
  895. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  896. num = 4;
  897. denom = 4;
  898. log.debug("InstrumentReader.addAbstractInstruction", errorMsg, ex);
  899. }
  900. const newRhythmInstruction: RhythmInstruction = new RhythmInstruction(
  901. new Fraction(num, denom, 0, false), symbolEnum
  902. );
  903. newRhythmInstruction.PrintObject = timePrintObject;
  904. this.abstractInstructions.push([1, newRhythmInstruction]);
  905. } else {
  906. this.abstractInstructions.push([1, new RhythmInstruction(new Fraction(4, 4, 0, false), RhythmSymbolEnum.NONE)]);
  907. }
  908. }
  909. }
  910. /**
  911. * Save the current AbstractInstructions to the corresponding [[StaffEntry]]s.
  912. * @param numberOfStaves
  913. * @param beginOfMeasure
  914. */
  915. private saveAbstractInstructionList(numberOfStaves: number, beginOfMeasure: boolean): void {
  916. for (let i: number = this.abstractInstructions.length - 1; i >= 0; i--) {
  917. const pair: [number, AbstractNotationInstruction] = this.abstractInstructions[i];
  918. const key: number = pair[0];
  919. const value: AbstractNotationInstruction = pair[1];
  920. if (value instanceof ClefInstruction) {
  921. const clefInstruction: ClefInstruction = <ClefInstruction>value;
  922. if (this.currentXmlMeasureIndex === 0 || (key <= this.activeClefs.length && clefInstruction !== this.activeClefs[key - 1])) {
  923. if (!beginOfMeasure && this.currentStaffEntry !== undefined && !this.currentStaffEntry.hasNotes() && key - 1
  924. === this.instrument.Staves.indexOf(this.currentStaffEntry.ParentStaff)) {
  925. const newClefInstruction: ClefInstruction = clefInstruction;
  926. newClefInstruction.Parent = this.currentStaffEntry;
  927. this.currentStaffEntry.removeFirstInstructionOfTypeClefInstruction();
  928. this.currentStaffEntry.Instructions.push(newClefInstruction);
  929. this.activeClefs[key - 1] = clefInstruction;
  930. this.abstractInstructions.splice(i, 1);
  931. } else if (beginOfMeasure) {
  932. let firstStaffEntry: SourceStaffEntry;
  933. if (this.currentMeasure !== undefined) {
  934. const newClefInstruction: ClefInstruction = clefInstruction;
  935. const sseIndex: number = this.inSourceMeasureInstrumentIndex + key - 1;
  936. const firstSse: SourceStaffEntry = this.currentMeasure.FirstInstructionsStaffEntries[sseIndex];
  937. if (this.currentXmlMeasureIndex === 0) {
  938. if (firstSse === undefined) {
  939. firstStaffEntry = new SourceStaffEntry(undefined, undefined);
  940. this.currentMeasure.FirstInstructionsStaffEntries[sseIndex] = firstStaffEntry;
  941. newClefInstruction.Parent = firstStaffEntry;
  942. firstStaffEntry.Instructions.push(newClefInstruction);
  943. this.activeClefsHaveBeenInitialized[key - 1] = true;
  944. } else if (this.currentMeasure.FirstInstructionsStaffEntries[sseIndex]
  945. !==
  946. undefined && !(firstSse.Instructions[0] instanceof ClefInstruction)) {
  947. firstStaffEntry = firstSse;
  948. newClefInstruction.Parent = firstStaffEntry;
  949. firstStaffEntry.removeFirstInstructionOfTypeClefInstruction();
  950. firstStaffEntry.Instructions.splice(0, 0, newClefInstruction);
  951. this.activeClefsHaveBeenInitialized[key - 1] = true;
  952. } else {
  953. const lastStaffEntry: SourceStaffEntry = new SourceStaffEntry(undefined, undefined);
  954. this.currentMeasure.LastInstructionsStaffEntries[sseIndex] = lastStaffEntry;
  955. newClefInstruction.Parent = lastStaffEntry;
  956. lastStaffEntry.Instructions.push(newClefInstruction);
  957. }
  958. } else if (!this.activeClefsHaveBeenInitialized[key - 1]) {
  959. const first: SourceMeasure = this.musicSheet.SourceMeasures[0];
  960. if (first.FirstInstructionsStaffEntries[sseIndex] === undefined) {
  961. firstStaffEntry = new SourceStaffEntry(undefined, undefined);
  962. } else {
  963. firstStaffEntry = first.FirstInstructionsStaffEntries[sseIndex];
  964. firstStaffEntry.removeFirstInstructionOfTypeClefInstruction();
  965. }
  966. newClefInstruction.Parent = firstStaffEntry;
  967. firstStaffEntry.Instructions.splice(0, 0, newClefInstruction);
  968. this.activeClefsHaveBeenInitialized[key - 1] = true;
  969. } else {
  970. const lastStaffEntry: SourceStaffEntry = new SourceStaffEntry(undefined, undefined);
  971. this.previousMeasure.LastInstructionsStaffEntries[sseIndex] = lastStaffEntry;
  972. newClefInstruction.Parent = lastStaffEntry;
  973. lastStaffEntry.Instructions.push(newClefInstruction);
  974. }
  975. this.activeClefs[key - 1] = clefInstruction;
  976. this.abstractInstructions.splice(i, 1);
  977. }
  978. }
  979. } else if (key <= this.activeClefs.length && clefInstruction === this.activeClefs[key - 1]) {
  980. this.abstractInstructions.splice(i, 1);
  981. }
  982. }
  983. if (value instanceof KeyInstruction) {
  984. const keyInstruction: KeyInstruction = <KeyInstruction>value;
  985. if (this.activeKey === undefined || this.activeKey.Key !== keyInstruction.Key) {
  986. this.activeKey = keyInstruction;
  987. this.abstractInstructions.splice(i, 1);
  988. let sourceMeasure: SourceMeasure;
  989. if (!this.activeKeyHasBeenInitialized) {
  990. this.activeKeyHasBeenInitialized = true;
  991. if (this.currentXmlMeasureIndex > 0) {
  992. sourceMeasure = this.musicSheet.SourceMeasures[0];
  993. } else {
  994. sourceMeasure = this.currentMeasure;
  995. }
  996. } else {
  997. sourceMeasure = this.currentMeasure;
  998. }
  999. if (sourceMeasure !== undefined) {
  1000. for (let j: number = this.inSourceMeasureInstrumentIndex; j < this.inSourceMeasureInstrumentIndex + numberOfStaves; j++) {
  1001. const newKeyInstruction: KeyInstruction = keyInstruction;
  1002. if (sourceMeasure.FirstInstructionsStaffEntries[j] === undefined) {
  1003. const firstStaffEntry: SourceStaffEntry = new SourceStaffEntry(undefined, undefined);
  1004. sourceMeasure.FirstInstructionsStaffEntries[j] = firstStaffEntry;
  1005. newKeyInstruction.Parent = firstStaffEntry;
  1006. firstStaffEntry.Instructions.push(newKeyInstruction);
  1007. } else {
  1008. const firstStaffEntry: SourceStaffEntry = sourceMeasure.FirstInstructionsStaffEntries[j];
  1009. newKeyInstruction.Parent = firstStaffEntry;
  1010. firstStaffEntry.removeFirstInstructionOfTypeKeyInstruction();
  1011. if (firstStaffEntry.Instructions.length === 0) {
  1012. firstStaffEntry.Instructions.push(newKeyInstruction);
  1013. } else {
  1014. if (firstStaffEntry.Instructions[0] instanceof ClefInstruction) {
  1015. firstStaffEntry.Instructions.splice(1, 0, newKeyInstruction);
  1016. } else {
  1017. firstStaffEntry.Instructions.splice(0, 0, newKeyInstruction);
  1018. }
  1019. }
  1020. }
  1021. }
  1022. }
  1023. } else {
  1024. this.abstractInstructions.splice(i, 1);
  1025. }
  1026. }
  1027. if (value instanceof RhythmInstruction) {
  1028. const rhythmInstruction: RhythmInstruction = <RhythmInstruction>value;
  1029. if (this.activeRhythm === undefined || this.activeRhythm !== rhythmInstruction) {
  1030. this.activeRhythm = rhythmInstruction;
  1031. this.abstractInstructions.splice(i, 1);
  1032. if (this.currentMeasure !== undefined) {
  1033. for (let j: number = this.inSourceMeasureInstrumentIndex; j < this.inSourceMeasureInstrumentIndex + numberOfStaves; j++) {
  1034. const newRhythmInstruction: RhythmInstruction = rhythmInstruction;
  1035. let firstStaffEntry: SourceStaffEntry;
  1036. if (this.currentMeasure.FirstInstructionsStaffEntries[j] === undefined) {
  1037. firstStaffEntry = new SourceStaffEntry(undefined, undefined);
  1038. this.currentMeasure.FirstInstructionsStaffEntries[j] = firstStaffEntry;
  1039. } else {
  1040. firstStaffEntry = this.currentMeasure.FirstInstructionsStaffEntries[j];
  1041. firstStaffEntry.removeFirstInstructionOfTypeRhythmInstruction();
  1042. }
  1043. newRhythmInstruction.Parent = firstStaffEntry;
  1044. firstStaffEntry.Instructions.push(newRhythmInstruction);
  1045. }
  1046. }
  1047. } else {
  1048. this.abstractInstructions.splice(i, 1);
  1049. }
  1050. }
  1051. }
  1052. }
  1053. /**
  1054. * Save any ClefInstruction given - exceptionally - at the end of the currentMeasure.
  1055. */
  1056. private saveClefInstructionAtEndOfMeasure(): void {
  1057. for (let i: number = this.abstractInstructions.length - 1; i >= 0; i--) {
  1058. const key: number = this.abstractInstructions[i][0];
  1059. const value: AbstractNotationInstruction = this.abstractInstructions[i][1];
  1060. if (value instanceof ClefInstruction) {
  1061. const clefInstruction: ClefInstruction = <ClefInstruction>value;
  1062. if (
  1063. (this.activeClefs[key - 1] === undefined) ||
  1064. (clefInstruction.ClefType !== this.activeClefs[key - 1].ClefType || (
  1065. clefInstruction.ClefType === this.activeClefs[key - 1].ClefType &&
  1066. clefInstruction.Line !== this.activeClefs[key - 1].Line
  1067. ))) {
  1068. const lastStaffEntry: SourceStaffEntry = new SourceStaffEntry(undefined, undefined);
  1069. this.currentMeasure.LastInstructionsStaffEntries[this.inSourceMeasureInstrumentIndex + key - 1] = lastStaffEntry;
  1070. const newClefInstruction: ClefInstruction = clefInstruction;
  1071. newClefInstruction.Parent = lastStaffEntry;
  1072. lastStaffEntry.Instructions.push(newClefInstruction);
  1073. this.activeClefs[key - 1] = clefInstruction;
  1074. this.abstractInstructions.splice(i, 1);
  1075. }
  1076. }
  1077. }
  1078. }
  1079. /**
  1080. * In case of a [[Tuplet]], read NoteDuration from type.
  1081. * @param xmlNode
  1082. * @returns {Fraction}
  1083. */
  1084. private getNoteDurationForTuplet(xmlNode: IXmlElement): Fraction {
  1085. let duration: Fraction = new Fraction(0, 1);
  1086. const typeDuration: Fraction = this.getNoteDurationFromTypeNode(xmlNode);
  1087. if (xmlNode.element("time-modification") !== undefined) {
  1088. const time: IXmlElement = xmlNode.element("time-modification");
  1089. if (time !== undefined) {
  1090. if (time.element("actual-notes") !== undefined && time.element("normal-notes") !== undefined) {
  1091. const actualNotes: IXmlElement = time.element("actual-notes");
  1092. const normalNotes: IXmlElement = time.element("normal-notes");
  1093. if (actualNotes !== undefined && normalNotes !== undefined) {
  1094. const actual: number = parseInt(actualNotes.value, 10);
  1095. const normal: number = parseInt(normalNotes.value, 10);
  1096. duration = new Fraction(normal * typeDuration.Numerator, actual * typeDuration.Denominator);
  1097. }
  1098. }
  1099. }
  1100. }
  1101. return duration;
  1102. }
  1103. private readExpressionStaffNumber(xmlNode: IXmlElement): number {
  1104. let directionStaffNumber: number = 1;
  1105. if (xmlNode.element("staff") !== undefined) {
  1106. const staffNode: IXmlElement = xmlNode.element("staff");
  1107. if (staffNode !== undefined) {
  1108. try {
  1109. directionStaffNumber = parseInt(staffNode.value, 10);
  1110. } catch (ex) {
  1111. const errorMsg: string = ITextTranslation.translateText(
  1112. "ReaderErrorMessages/ExpressionStaffError", "Invalid Expression staff number -> set to default."
  1113. );
  1114. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  1115. directionStaffNumber = 1;
  1116. log.debug("InstrumentReader.readExpressionStaffNumber", errorMsg, ex);
  1117. }
  1118. }
  1119. }
  1120. return directionStaffNumber;
  1121. }
  1122. /**
  1123. * Calculate the divisions value from the type and duration of the first MeasureNote that makes sense
  1124. * (meaning itself hasn't any errors and it doesn't belong to a [[Tuplet]]).
  1125. *
  1126. * If all the MeasureNotes belong to a [[Tuplet]], then we read the next XmlMeasure (and so on...).
  1127. * If we have reached the end of the [[Instrument]] and still the divisions aren't set, we throw an exception
  1128. * @returns {number}
  1129. */
  1130. private readDivisionsFromNotes(): number {
  1131. let divisionsFromNote: number = 0;
  1132. let xmlMeasureIndex: number = this.currentXmlMeasureIndex;
  1133. let read: boolean = false;
  1134. while (!read) {
  1135. const xmlMeasureListArr: IXmlElement[] = this.xmlMeasureList[xmlMeasureIndex].elements();
  1136. for (let idx: number = 0, len: number = xmlMeasureListArr.length; idx < len; ++idx) {
  1137. const xmlNode: IXmlElement = xmlMeasureListArr[idx];
  1138. if (xmlNode.name === "note" && xmlNode.element("time-modification") === undefined) {
  1139. const durationNode: IXmlElement = xmlNode.element("duration");
  1140. const typeNode: IXmlElement = xmlNode.element("type");
  1141. if (durationNode !== undefined && typeNode !== undefined) {
  1142. const type: string = typeNode.value;
  1143. let noteDuration: number = 0;
  1144. try {
  1145. noteDuration = parseInt(durationNode.value, 10);
  1146. } catch (ex) {
  1147. log.debug("InstrumentReader.readDivisionsFromNotes", ex);
  1148. continue;
  1149. }
  1150. switch (type) {
  1151. case "1024th":
  1152. divisionsFromNote = (noteDuration / 4) * 1024;
  1153. break;
  1154. case "512th":
  1155. divisionsFromNote = (noteDuration / 4) * 512;
  1156. break;
  1157. case "256th":
  1158. divisionsFromNote = (noteDuration / 4) * 256;
  1159. break;
  1160. case "128th":
  1161. divisionsFromNote = (noteDuration / 4) * 128;
  1162. break;
  1163. case "64th":
  1164. divisionsFromNote = (noteDuration / 4) * 64;
  1165. break;
  1166. case "32nd":
  1167. divisionsFromNote = (noteDuration / 4) * 32;
  1168. break;
  1169. case "16th":
  1170. divisionsFromNote = (noteDuration / 4) * 16;
  1171. break;
  1172. case "eighth":
  1173. divisionsFromNote = (noteDuration / 4) * 8;
  1174. break;
  1175. case "quarter":
  1176. divisionsFromNote = (noteDuration / 4) * 4;
  1177. break;
  1178. case "half":
  1179. divisionsFromNote = (noteDuration / 4) * 2;
  1180. break;
  1181. case "whole":
  1182. divisionsFromNote = (noteDuration / 4);
  1183. break;
  1184. case "breve":
  1185. divisionsFromNote = (noteDuration / 4) / 2;
  1186. break;
  1187. case "long":
  1188. divisionsFromNote = (noteDuration / 4) / 4;
  1189. break;
  1190. case "maxima":
  1191. divisionsFromNote = (noteDuration / 4) / 8;
  1192. break;
  1193. default:
  1194. break;
  1195. }
  1196. }
  1197. }
  1198. if (divisionsFromNote > 0) {
  1199. read = true;
  1200. break;
  1201. }
  1202. }
  1203. if (divisionsFromNote === 0) {
  1204. xmlMeasureIndex++;
  1205. if (xmlMeasureIndex === this.xmlMeasureList.length) {
  1206. const errorMsg: string = ITextTranslation.translateText("ReaderErrorMEssages/DivisionsError", "Invalid divisions value at Instrument: ");
  1207. throw new MusicSheetReadingException(errorMsg + this.instrument.Name);
  1208. }
  1209. }
  1210. }
  1211. return divisionsFromNote;
  1212. }
  1213. }