InstrumentReader.ts 58 KB

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