InstrumentReader.ts 50 KB

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