InstrumentReader.ts 57 KB

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