InstrumentReader.ts 60 KB

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