InstrumentReader.ts 49 KB

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