VoiceGenerator.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. import { Instrument } from "../Instrument";
  2. import { LinkedVoice } from "../VoiceData/LinkedVoice";
  3. import { Voice } from "../VoiceData/Voice";
  4. import { MusicSheet } from "../MusicSheet";
  5. import { VoiceEntry, StemDirectionType } from "../VoiceData/VoiceEntry";
  6. import { Note } from "../VoiceData/Note";
  7. import { SourceMeasure } from "../VoiceData/SourceMeasure";
  8. import { SourceStaffEntry } from "../VoiceData/SourceStaffEntry";
  9. import { Beam } from "../VoiceData/Beam";
  10. import { Tie } from "../VoiceData/Tie";
  11. import { Tuplet } from "../VoiceData/Tuplet";
  12. import { Fraction } from "../../Common/DataObjects/Fraction";
  13. import { IXmlElement } from "../../Common/FileIO/Xml";
  14. import { ITextTranslation } from "../Interfaces/ITextTranslation";
  15. import { LyricsReader } from "../ScoreIO/MusicSymbolModules/LyricsReader";
  16. import { MusicSheetReadingException } from "../Exceptions";
  17. import { AccidentalEnum } from "../../Common/DataObjects/Pitch";
  18. import { NoteEnum } from "../../Common/DataObjects/Pitch";
  19. import { Staff } from "../VoiceData/Staff";
  20. import { StaffEntryLink } from "../VoiceData/StaffEntryLink";
  21. import { VerticalSourceStaffEntryContainer } from "../VoiceData/VerticalSourceStaffEntryContainer";
  22. import * as log from "loglevel";
  23. import { Pitch } from "../../Common/DataObjects/Pitch";
  24. import { IXmlAttribute } from "../../Common/FileIO/Xml";
  25. import { CollectionUtil } from "../../Util/CollectionUtil";
  26. import { ArticulationReader } from "./MusicSymbolModules/ArticulationReader";
  27. import { SlurReader } from "./MusicSymbolModules/SlurReader";
  28. import { Notehead } from "../VoiceData/Notehead";
  29. import { Arpeggio, ArpeggioType } from "../VoiceData/Arpeggio";
  30. export class VoiceGenerator {
  31. constructor(instrument: Instrument, voiceId: number, slurReader: SlurReader, mainVoice: Voice = undefined) {
  32. this.musicSheet = instrument.GetMusicSheet;
  33. this.slurReader = slurReader;
  34. if (mainVoice !== undefined) {
  35. this.voice = new LinkedVoice(instrument, voiceId, mainVoice);
  36. } else {
  37. this.voice = new Voice(instrument, voiceId);
  38. }
  39. instrument.Voices.push(this.voice);
  40. this.lyricsReader = new LyricsReader(this.musicSheet);
  41. this.articulationReader = new ArticulationReader();
  42. }
  43. private slurReader: SlurReader;
  44. private lyricsReader: LyricsReader;
  45. private articulationReader: ArticulationReader;
  46. private musicSheet: MusicSheet;
  47. private voice: Voice;
  48. private currentVoiceEntry: VoiceEntry;
  49. private currentNote: Note;
  50. private currentMeasure: SourceMeasure;
  51. private currentStaffEntry: SourceStaffEntry;
  52. private lastBeamTag: string = "";
  53. private openBeam: Beam;
  54. private openTieDict: { [_: number]: Tie; } = {};
  55. private currentOctaveShift: number = 0;
  56. private tupletDict: { [_: number]: Tuplet; } = {};
  57. private openTupletNumber: number = 0;
  58. public get GetVoice(): Voice {
  59. return this.voice;
  60. }
  61. public get OctaveShift(): number {
  62. return this.currentOctaveShift;
  63. }
  64. public set OctaveShift(value: number) {
  65. this.currentOctaveShift = value;
  66. }
  67. /**
  68. * Create new [[VoiceEntry]], add it to given [[SourceStaffEntry]] and if given so, to [[Voice]].
  69. * @param musicTimestamp
  70. * @param parentStaffEntry
  71. * @param addToVoice
  72. * @param isGrace States whether the new VoiceEntry (only) has grace notes
  73. */
  74. public createVoiceEntry(musicTimestamp: Fraction, parentStaffEntry: SourceStaffEntry, addToVoice: boolean,
  75. isGrace: boolean = false, graceNoteSlash: boolean = false, graceSlur: boolean = false): void {
  76. this.currentVoiceEntry = new VoiceEntry(musicTimestamp.clone(), this.voice, parentStaffEntry, isGrace, graceNoteSlash, graceSlur);
  77. if (addToVoice) {
  78. this.voice.VoiceEntries.push(this.currentVoiceEntry);
  79. }
  80. if (parentStaffEntry.VoiceEntries.indexOf(this.currentVoiceEntry) === -1) {
  81. parentStaffEntry.VoiceEntries.push(this.currentVoiceEntry);
  82. }
  83. }
  84. /**
  85. * Create [[Note]]s and handle Lyrics, Articulations, Beams, Ties, Slurs, Tuplets.
  86. * @param noteNode
  87. * @param noteDuration
  88. * @param divisions
  89. * @param restNote
  90. * @param parentStaffEntry
  91. * @param parentMeasure
  92. * @param measureStartAbsoluteTimestamp
  93. * @param maxTieNoteFraction
  94. * @param chord
  95. * @param guitarPro
  96. * @param printObject whether the note should be rendered (true) or invisible (false)
  97. * @returns {Note}
  98. */
  99. public read(noteNode: IXmlElement, noteDuration: Fraction, typeDuration: Fraction, normalNotes: number, restNote: boolean,
  100. parentStaffEntry: SourceStaffEntry, parentMeasure: SourceMeasure,
  101. measureStartAbsoluteTimestamp: Fraction, maxTieNoteFraction: Fraction, chord: boolean, guitarPro: boolean,
  102. printObject: boolean, isCueNote: boolean, stemDirectionXml: StemDirectionType,
  103. stemColorXml: string, noteheadColorXml: string): Note {
  104. this.currentStaffEntry = parentStaffEntry;
  105. this.currentMeasure = parentMeasure;
  106. //log.debug("read called:", restNote);
  107. try {
  108. this.currentNote = restNote
  109. ? this.addRestNote(noteDuration, printObject, isCueNote, noteheadColorXml)
  110. : this.addSingleNote(noteNode, noteDuration, typeDuration, normalNotes, chord, guitarPro,
  111. printObject, isCueNote, stemDirectionXml, stemColorXml, noteheadColorXml);
  112. // read lyrics
  113. const lyricElements: IXmlElement[] = noteNode.elements("lyric");
  114. if (this.lyricsReader !== undefined && lyricElements !== undefined) {
  115. this.lyricsReader.addLyricEntry(lyricElements, this.currentVoiceEntry);
  116. this.voice.Parent.HasLyrics = true;
  117. }
  118. let hasTupletCommand: boolean = false;
  119. const notationNode: IXmlElement = noteNode.element("notations");
  120. if (notationNode !== undefined) {
  121. // read articulations
  122. if (this.articulationReader !== undefined) {
  123. this.readArticulations(notationNode, this.currentVoiceEntry);
  124. }
  125. // read slurs
  126. const slurElements: IXmlElement[] = notationNode.elements("slur");
  127. if (this.slurReader !== undefined &&
  128. slurElements.length > 0 &&
  129. !this.currentNote.ParentVoiceEntry.IsGrace) {
  130. this.slurReader.addSlur(slurElements, this.currentNote);
  131. }
  132. // read Tuplets
  133. const tupletElements: IXmlElement[] = notationNode.elements("tuplet");
  134. if (tupletElements.length > 0) {
  135. this.openTupletNumber = this.addTuplet(noteNode, tupletElements);
  136. hasTupletCommand = true;
  137. }
  138. // check for Arpeggios
  139. const arpeggioNode: IXmlElement = notationNode.element("arpeggiate");
  140. if (arpeggioNode !== undefined && !this.currentVoiceEntry.IsGrace) {
  141. let currentArpeggio: Arpeggio;
  142. if (this.currentVoiceEntry.Arpeggio !== undefined) { // add note to existing Arpeggio
  143. currentArpeggio = this.currentVoiceEntry.Arpeggio;
  144. } else { // create new Arpeggio
  145. let arpeggioType: ArpeggioType;
  146. const directionAttr: Attr = arpeggioNode.attribute("direction");
  147. if (directionAttr !== null) {
  148. switch (directionAttr.value) {
  149. case "up":
  150. arpeggioType = ArpeggioType.ROLL_UP;
  151. break;
  152. case "down":
  153. arpeggioType = ArpeggioType.ROLL_DOWN;
  154. break;
  155. default:
  156. arpeggioType = ArpeggioType.ARPEGGIO_DIRECTIONLESS;
  157. }
  158. }
  159. currentArpeggio = new Arpeggio(this.currentVoiceEntry, arpeggioType);
  160. this.currentVoiceEntry.Arpeggio = currentArpeggio;
  161. }
  162. currentArpeggio.addNote(this.currentNote);
  163. }
  164. // check for Ties - must be the last check
  165. const tiedNodeList: IXmlElement[] = notationNode.elements("tied");
  166. if (tiedNodeList.length > 0) {
  167. this.addTie(tiedNodeList, measureStartAbsoluteTimestamp, maxTieNoteFraction);
  168. }
  169. // remove open ties, if there is already a gap between the last tie note and now.
  170. const openTieDict: { [_: number]: Tie; } = this.openTieDict;
  171. for (const key in openTieDict) {
  172. if (openTieDict.hasOwnProperty(key)) {
  173. const tie: Tie = openTieDict[key];
  174. if (Fraction.plus(tie.StartNote.ParentStaffEntry.Timestamp, tie.Duration).lt(this.currentStaffEntry.Timestamp)) {
  175. delete openTieDict[key];
  176. }
  177. }
  178. }
  179. }
  180. // time-modification yields tuplet in currentNote
  181. // mustn't execute method, if this is the Note where the Tuplet has been created
  182. if (noteNode.element("time-modification") !== undefined && !hasTupletCommand) {
  183. this.handleTimeModificationNode(noteNode);
  184. }
  185. } catch (err) {
  186. const errorMsg: string = ITextTranslation.translateText(
  187. "ReaderErrorMessages/NoteError", "Ignored erroneous Note."
  188. );
  189. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  190. }
  191. return this.currentNote;
  192. }
  193. /**
  194. * Create a new [[StaffEntryLink]] and sets the currenstStaffEntry accordingly.
  195. * @param index
  196. * @param currentStaff
  197. * @param currentStaffEntry
  198. * @param currentMeasure
  199. * @returns {SourceStaffEntry}
  200. */
  201. public checkForStaffEntryLink(index: number, currentStaff: Staff, currentStaffEntry: SourceStaffEntry, currentMeasure: SourceMeasure): SourceStaffEntry {
  202. const staffEntryLink: StaffEntryLink = new StaffEntryLink(this.currentVoiceEntry);
  203. staffEntryLink.LinkStaffEntries.push(currentStaffEntry);
  204. currentStaffEntry.Link = staffEntryLink;
  205. const linkMusicTimestamp: Fraction = this.currentVoiceEntry.Timestamp.clone();
  206. const verticalSourceStaffEntryContainer: VerticalSourceStaffEntryContainer = currentMeasure.getVerticalContainerByTimestamp(linkMusicTimestamp);
  207. currentStaffEntry = verticalSourceStaffEntryContainer.StaffEntries[index];
  208. if (currentStaffEntry === undefined) {
  209. currentStaffEntry = new SourceStaffEntry(verticalSourceStaffEntryContainer, currentStaff);
  210. verticalSourceStaffEntryContainer.StaffEntries[index] = currentStaffEntry;
  211. }
  212. currentStaffEntry.VoiceEntries.push(this.currentVoiceEntry);
  213. staffEntryLink.LinkStaffEntries.push(currentStaffEntry);
  214. currentStaffEntry.Link = staffEntryLink;
  215. return currentStaffEntry;
  216. }
  217. public checkForOpenBeam(): void {
  218. if (this.openBeam !== undefined && this.currentNote !== undefined) {
  219. this.handleOpenBeam();
  220. }
  221. }
  222. public checkOpenTies(): void {
  223. const openTieDict: { [key: number]: Tie } = this.openTieDict;
  224. for (const key in openTieDict) {
  225. if (openTieDict.hasOwnProperty(key)) {
  226. const tie: Tie = openTieDict[key];
  227. if (Fraction.plus(tie.StartNote.ParentStaffEntry.Timestamp, tie.Duration)
  228. .lt(tie.StartNote.ParentStaffEntry.VerticalContainerParent.ParentMeasure.Duration)) {
  229. delete openTieDict[key];
  230. }
  231. }
  232. }
  233. }
  234. public hasVoiceEntry(): boolean {
  235. return this.currentVoiceEntry !== undefined;
  236. }
  237. /**
  238. *
  239. * @param type
  240. * @returns {Fraction} - a Note's Duration from a given type (type must be valid).
  241. */
  242. public getNoteDurationFromType(type: string): Fraction {
  243. switch (type) {
  244. case "1024th":
  245. return new Fraction(1, 1024);
  246. case "512th":
  247. return new Fraction(1, 512);
  248. case "256th":
  249. return new Fraction(1, 256);
  250. case "128th":
  251. return new Fraction(1, 128);
  252. case "64th":
  253. return new Fraction(1, 64);
  254. case "32th":
  255. case "32nd":
  256. return new Fraction(1, 32);
  257. case "16th":
  258. return new Fraction(1, 16);
  259. case "eighth":
  260. return new Fraction(1, 8);
  261. case "quarter":
  262. return new Fraction(1, 4);
  263. case "half":
  264. return new Fraction(1, 2);
  265. case "whole":
  266. return new Fraction(1, 1);
  267. case "breve":
  268. return new Fraction(2, 1);
  269. case "long":
  270. return new Fraction(4, 1);
  271. case "maxima":
  272. return new Fraction(8, 1);
  273. default: {
  274. const errorMsg: string = ITextTranslation.translateText(
  275. "ReaderErrorMessages/NoteDurationError", "Invalid note duration."
  276. );
  277. throw new MusicSheetReadingException(errorMsg);
  278. }
  279. }
  280. }
  281. private readArticulations(notationNode: IXmlElement, currentVoiceEntry: VoiceEntry): void {
  282. const articNode: IXmlElement = notationNode.element("articulations");
  283. if (articNode !== undefined) {
  284. this.articulationReader.addArticulationExpression(articNode, currentVoiceEntry);
  285. }
  286. const fermaNode: IXmlElement = notationNode.element("fermata");
  287. if (fermaNode !== undefined) {
  288. this.articulationReader.addFermata(fermaNode, currentVoiceEntry);
  289. }
  290. const tecNode: IXmlElement = notationNode.element("technical");
  291. if (tecNode !== undefined) {
  292. this.articulationReader.addTechnicalArticulations(tecNode, currentVoiceEntry);
  293. }
  294. const ornaNode: IXmlElement = notationNode.element("ornaments");
  295. if (ornaNode !== undefined) {
  296. this.articulationReader.addOrnament(ornaNode, currentVoiceEntry);
  297. }
  298. }
  299. /**
  300. * Create a new [[Note]] and adds it to the currentVoiceEntry
  301. * @param node
  302. * @param noteDuration
  303. * @param divisions
  304. * @param chord
  305. * @param guitarPro
  306. * @returns {Note}
  307. */
  308. private addSingleNote(node: IXmlElement, noteDuration: Fraction, typeDuration: Fraction, normalNotes: number, chord: boolean, guitarPro: boolean,
  309. printObject: boolean, isCueNote: boolean, stemDirectionXml: StemDirectionType,
  310. stemColorXml: string, noteheadColorXml: string): Note {
  311. //log.debug("addSingleNote called");
  312. let noteAlter: number = 0;
  313. let noteAccidental: AccidentalEnum = AccidentalEnum.NONE;
  314. let noteStep: NoteEnum = NoteEnum.C;
  315. let noteOctave: number = 0;
  316. let playbackInstrumentId: string = undefined;
  317. let noteheadShapeXml: string = undefined;
  318. let noteheadFilledXml: boolean = undefined; // if undefined, the final filled parameter will be calculated from duration
  319. const xmlnodeElementsArr: IXmlElement[] = node.elements();
  320. for (let idx: number = 0, len: number = xmlnodeElementsArr.length; idx < len; ++idx) {
  321. const noteElement: IXmlElement = xmlnodeElementsArr[idx];
  322. try {
  323. if (noteElement.name === "pitch") {
  324. const noteElementsArr: IXmlElement[] = noteElement.elements();
  325. for (let idx2: number = 0, len2: number = noteElementsArr.length; idx2 < len2; ++idx2) {
  326. const pitchElement: IXmlElement = noteElementsArr[idx2];
  327. noteheadShapeXml = undefined; // reinitialize for each pitch
  328. noteheadFilledXml = undefined;
  329. try {
  330. if (pitchElement.name === "step") {
  331. noteStep = NoteEnum[pitchElement.value];
  332. if (noteStep === undefined) {
  333. const errorMsg: string = ITextTranslation.translateText(
  334. "ReaderErrorMessages/NotePitchError",
  335. "Invalid pitch while reading note."
  336. );
  337. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  338. throw new MusicSheetReadingException(errorMsg, undefined);
  339. }
  340. } else if (pitchElement.name === "alter") {
  341. noteAlter = parseFloat(pitchElement.value);
  342. if (isNaN(noteAlter)) {
  343. const errorMsg: string = ITextTranslation.translateText(
  344. "ReaderErrorMessages/NoteAlterationError", "Invalid alteration while reading note."
  345. );
  346. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  347. throw new MusicSheetReadingException(errorMsg, undefined);
  348. }
  349. noteAccidental = Pitch.AccidentalFromHalfTones(noteAlter); // potentially overwritten by "accidental" noteElement
  350. } else if (pitchElement.name === "octave") {
  351. noteOctave = parseInt(pitchElement.value, 10);
  352. if (isNaN(noteOctave)) {
  353. const errorMsg: string = ITextTranslation.translateText(
  354. "ReaderErrorMessages/NoteOctaveError", "Invalid octave value while reading note."
  355. );
  356. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  357. throw new MusicSheetReadingException(errorMsg, undefined);
  358. }
  359. }
  360. } catch (ex) {
  361. log.info("VoiceGenerator.addSingleNote read Step: ", ex.message);
  362. }
  363. }
  364. } else if (noteElement.name === "accidental") {
  365. const accidentalValue: string = noteElement.value;
  366. if (accidentalValue === "natural") {
  367. noteAccidental = AccidentalEnum.NATURAL;
  368. }
  369. } else if (noteElement.name === "unpitched") {
  370. const displayStep: IXmlElement = noteElement.element("display-step");
  371. if (displayStep !== undefined) {
  372. noteStep = NoteEnum[displayStep.value.toUpperCase()];
  373. }
  374. const octave: IXmlElement = noteElement.element("display-octave");
  375. if (octave !== undefined) {
  376. noteOctave = parseInt(octave.value, 10);
  377. if (guitarPro) {
  378. noteOctave += 1;
  379. }
  380. }
  381. } else if (noteElement.name === "instrument") {
  382. if (noteElement.firstAttribute !== undefined) {
  383. playbackInstrumentId = noteElement.firstAttribute.value;
  384. }
  385. } else if (noteElement.name === "notehead") {
  386. noteheadShapeXml = noteElement.value;
  387. if (noteElement.attribute("filled") !== null) {
  388. noteheadFilledXml = noteElement.attribute("filled").value === "yes";
  389. }
  390. }
  391. } catch (ex) {
  392. log.info("VoiceGenerator.addSingleNote: ", ex);
  393. }
  394. }
  395. noteOctave -= Pitch.OctaveXmlDifference;
  396. const pitch: Pitch = new Pitch(noteStep, noteOctave, noteAccidental);
  397. const noteLength: Fraction = Fraction.createFromFraction(noteDuration);
  398. const note: Note = new Note(this.currentVoiceEntry, this.currentStaffEntry, noteLength, pitch);
  399. note.TypeLength = typeDuration;
  400. note.NormalNotes = normalNotes;
  401. note.PrintObject = printObject;
  402. note.IsCueNote = isCueNote;
  403. note.StemDirectionXml = stemDirectionXml; // maybe unnecessary, also in VoiceEntry
  404. if ((noteheadShapeXml !== undefined && noteheadShapeXml !== "normal") || noteheadFilledXml !== undefined) {
  405. note.Notehead = new Notehead(note, noteheadShapeXml, noteheadFilledXml);
  406. } // if normal, leave note head undefined to save processing/runtime
  407. note.NoteheadColorXml = noteheadColorXml; // color set in Xml, shouldn't be changed.
  408. note.NoteheadColor = noteheadColorXml; // color currently used
  409. note.PlaybackInstrumentId = playbackInstrumentId;
  410. this.currentVoiceEntry.Notes.push(note);
  411. this.currentVoiceEntry.StemDirectionXml = stemDirectionXml;
  412. if (stemColorXml) {
  413. this.currentVoiceEntry.StemColorXml = stemColorXml;
  414. this.currentVoiceEntry.StemColor = stemColorXml;
  415. note.StemColorXml = stemColorXml;
  416. }
  417. if (node.elements("beam") && !chord) {
  418. this.createBeam(node, note);
  419. }
  420. return note;
  421. }
  422. /**
  423. * Create a new rest note and add it to the currentVoiceEntry.
  424. * @param noteDuration
  425. * @param divisions
  426. * @returns {Note}
  427. */
  428. private addRestNote(noteDuration: Fraction, printObject: boolean, isCueNote: boolean, noteheadColorXml: string): Note {
  429. const restFraction: Fraction = Fraction.createFromFraction(noteDuration);
  430. const restNote: Note = new Note(this.currentVoiceEntry, this.currentStaffEntry, restFraction, undefined);
  431. restNote.PrintObject = printObject;
  432. restNote.IsCueNote = isCueNote;
  433. restNote.NoteheadColorXml = noteheadColorXml;
  434. restNote.NoteheadColor = noteheadColorXml;
  435. this.currentVoiceEntry.Notes.push(restNote);
  436. if (this.openBeam !== undefined) {
  437. this.openBeam.ExtendedNoteList.push(restNote);
  438. }
  439. return restNote;
  440. }
  441. /**
  442. * Handle the currentVoiceBeam.
  443. * @param node
  444. * @param note
  445. */
  446. private createBeam(node: IXmlElement, note: Note): void {
  447. try {
  448. const beamNode: IXmlElement = node.element("beam");
  449. let beamAttr: IXmlAttribute = undefined;
  450. if (beamNode !== undefined && beamNode.hasAttributes) {
  451. beamAttr = beamNode.attribute("number");
  452. }
  453. if (beamAttr !== undefined) {
  454. const beamNumber: number = parseInt(beamAttr.value, 10);
  455. const mainBeamNode: IXmlElement[] = node.elements("beam");
  456. const currentBeamTag: string = mainBeamNode[0].value;
  457. if (beamNumber === 1 && mainBeamNode !== undefined) {
  458. if (currentBeamTag === "begin" && this.lastBeamTag !== currentBeamTag) {
  459. if (this.openBeam !== undefined) {
  460. this.handleOpenBeam();
  461. }
  462. this.openBeam = new Beam();
  463. }
  464. this.lastBeamTag = currentBeamTag;
  465. }
  466. let sameVoiceEntry: boolean = false;
  467. if (this.openBeam === undefined) {
  468. return;
  469. }
  470. for (let idx: number = 0, len: number = this.openBeam.Notes.length; idx < len; ++idx) {
  471. const beamNote: Note = this.openBeam.Notes[idx];
  472. if (this.currentVoiceEntry === beamNote.ParentVoiceEntry) {
  473. sameVoiceEntry = true;
  474. }
  475. }
  476. if (!sameVoiceEntry) {
  477. this.openBeam.addNoteToBeam(note);
  478. if (currentBeamTag === "end" && beamNumber === 1) {
  479. this.openBeam = undefined;
  480. }
  481. }
  482. }
  483. } catch (e) {
  484. const errorMsg: string = ITextTranslation.translateText(
  485. "ReaderErrorMessages/BeamError", "Error while reading beam."
  486. );
  487. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  488. throw new MusicSheetReadingException("", e);
  489. }
  490. }
  491. /**
  492. * Check for open [[Beam]]s at end of [[SourceMeasure]] and closes them explicity.
  493. */
  494. private handleOpenBeam(): void {
  495. if (this.openBeam.Notes.length === 1) {
  496. const beamNote: Note = this.openBeam.Notes[0];
  497. beamNote.NoteBeam = undefined;
  498. this.openBeam = undefined;
  499. return;
  500. }
  501. if (this.currentNote === CollectionUtil.last(this.openBeam.Notes)) {
  502. this.openBeam = undefined;
  503. } else {
  504. const beamLastNote: Note = CollectionUtil.last(this.openBeam.Notes);
  505. const beamLastNoteStaffEntry: SourceStaffEntry = beamLastNote.ParentStaffEntry;
  506. const horizontalIndex: number = this.currentMeasure.getVerticalContainerIndexByTimestamp(beamLastNoteStaffEntry.Timestamp);
  507. const verticalIndex: number = beamLastNoteStaffEntry.VerticalContainerParent.StaffEntries.indexOf(beamLastNoteStaffEntry);
  508. if (horizontalIndex < this.currentMeasure.VerticalSourceStaffEntryContainers.length - 1) {
  509. const nextStaffEntry: SourceStaffEntry = this.currentMeasure
  510. .VerticalSourceStaffEntryContainers[horizontalIndex + 1]
  511. .StaffEntries[verticalIndex];
  512. if (nextStaffEntry !== undefined) {
  513. for (let idx: number = 0, len: number = nextStaffEntry.VoiceEntries.length; idx < len; ++idx) {
  514. const voiceEntry: VoiceEntry = nextStaffEntry.VoiceEntries[idx];
  515. if (voiceEntry.ParentVoice === this.voice) {
  516. const candidateNote: Note = voiceEntry.Notes[0];
  517. if (candidateNote.Length.lte(new Fraction(1, 8))) {
  518. this.openBeam.addNoteToBeam(candidateNote);
  519. this.openBeam = undefined;
  520. } else {
  521. this.openBeam = undefined;
  522. }
  523. }
  524. }
  525. }
  526. } else {
  527. this.openBeam = undefined;
  528. }
  529. }
  530. }
  531. /**
  532. * Create a [[Tuplet]].
  533. * @param node
  534. * @param tupletNodeList
  535. * @returns {number}
  536. */
  537. private addTuplet(node: IXmlElement, tupletNodeList: IXmlElement[]): number {
  538. let bracketed: boolean = false; // xml bracket attribute value
  539. if (tupletNodeList !== undefined && tupletNodeList.length > 1) {
  540. let timeModNode: IXmlElement = node.element("time-modification");
  541. if (timeModNode !== undefined) {
  542. timeModNode = timeModNode.element("actual-notes");
  543. }
  544. const tupletNodeListArr: IXmlElement[] = tupletNodeList;
  545. for (let idx: number = 0, len: number = tupletNodeListArr.length; idx < len; ++idx) {
  546. const tupletNode: IXmlElement = tupletNodeListArr[idx];
  547. if (tupletNode !== undefined && tupletNode.attributes()) {
  548. const bracketAttr: Attr = tupletNode.attribute("bracket");
  549. if (bracketAttr && bracketAttr.value === "yes") {
  550. bracketed = true;
  551. }
  552. const type: Attr = tupletNode.attribute("type");
  553. if (type && type.value === "start") {
  554. let tupletNumber: number = 1;
  555. if (tupletNode.attribute("number")) {
  556. tupletNumber = parseInt(tupletNode.attribute("number").value, 10);
  557. }
  558. let tupletLabelNumber: number = 0;
  559. if (timeModNode !== undefined) {
  560. tupletLabelNumber = parseInt(timeModNode.value, 10);
  561. if (isNaN(tupletLabelNumber)) {
  562. const errorMsg: string = ITextTranslation.translateText(
  563. "ReaderErrorMessages/TupletNoteDurationError", "Invalid tuplet note duration."
  564. );
  565. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  566. throw new MusicSheetReadingException(errorMsg, undefined);
  567. }
  568. }
  569. const tuplet: Tuplet = new Tuplet(tupletLabelNumber, bracketed);
  570. if (this.tupletDict[tupletNumber] !== undefined) {
  571. delete this.tupletDict[tupletNumber];
  572. if (Object.keys(this.tupletDict).length === 0) {
  573. this.openTupletNumber = 0;
  574. } else if (Object.keys(this.tupletDict).length > 1) {
  575. this.openTupletNumber--;
  576. }
  577. }
  578. this.tupletDict[tupletNumber] = tuplet;
  579. const subnotelist: Note[] = [];
  580. subnotelist.push(this.currentNote);
  581. tuplet.Notes.push(subnotelist);
  582. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  583. this.currentNote.NoteTuplet = tuplet;
  584. this.openTupletNumber = tupletNumber;
  585. } else if (type.value === "stop") {
  586. let tupletNumber: number = 1;
  587. if (tupletNode.attribute("number")) {
  588. tupletNumber = parseInt(tupletNode.attribute("number").value, 10);
  589. }
  590. const tuplet: Tuplet = this.tupletDict[tupletNumber];
  591. if (tuplet !== undefined) {
  592. const subnotelist: Note[] = [];
  593. subnotelist.push(this.currentNote);
  594. tuplet.Notes.push(subnotelist);
  595. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  596. this.currentNote.NoteTuplet = tuplet;
  597. delete this.tupletDict[tupletNumber];
  598. if (Object.keys(this.tupletDict).length === 0) {
  599. this.openTupletNumber = 0;
  600. } else if (Object.keys(this.tupletDict).length > 1) {
  601. this.openTupletNumber--;
  602. }
  603. }
  604. }
  605. }
  606. }
  607. } else if (tupletNodeList[0] !== undefined) {
  608. const n: IXmlElement = tupletNodeList[0];
  609. if (n.hasAttributes) {
  610. const type: string = n.attribute("type").value;
  611. let tupletnumber: number = 1;
  612. if (n.attribute("number")) {
  613. tupletnumber = parseInt(n.attribute("number").value, 10);
  614. }
  615. const noTupletNumbering: boolean = isNaN(tupletnumber);
  616. const bracketAttr: Attr = n.attribute("bracket");
  617. if (bracketAttr && bracketAttr.value === "yes") {
  618. bracketed = true;
  619. }
  620. if (type === "start") {
  621. let tupletLabelNumber: number = 0;
  622. let timeModNode: IXmlElement = node.element("time-modification");
  623. if (timeModNode !== undefined) {
  624. timeModNode = timeModNode.element("actual-notes");
  625. }
  626. if (timeModNode !== undefined) {
  627. tupletLabelNumber = parseInt(timeModNode.value, 10);
  628. if (isNaN(tupletLabelNumber)) {
  629. const errorMsg: string = ITextTranslation.translateText(
  630. "ReaderErrorMessages/TupletNoteDurationError", "Invalid tuplet note duration."
  631. );
  632. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  633. throw new MusicSheetReadingException(errorMsg);
  634. }
  635. }
  636. if (noTupletNumbering) {
  637. this.openTupletNumber++;
  638. tupletnumber = this.openTupletNumber;
  639. }
  640. let tuplet: Tuplet = this.tupletDict[tupletnumber];
  641. if (tuplet === undefined) {
  642. tuplet = this.tupletDict[tupletnumber] = new Tuplet(tupletLabelNumber, bracketed);
  643. }
  644. const subnotelist: Note[] = [];
  645. subnotelist.push(this.currentNote);
  646. tuplet.Notes.push(subnotelist);
  647. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  648. this.currentNote.NoteTuplet = tuplet;
  649. this.openTupletNumber = tupletnumber;
  650. } else if (type === "stop") {
  651. if (noTupletNumbering) {
  652. tupletnumber = this.openTupletNumber;
  653. }
  654. const tuplet: Tuplet = this.tupletDict[this.openTupletNumber];
  655. if (tuplet !== undefined) {
  656. const subnotelist: Note[] = [];
  657. subnotelist.push(this.currentNote);
  658. tuplet.Notes.push(subnotelist);
  659. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  660. this.currentNote.NoteTuplet = tuplet;
  661. if (Object.keys(this.tupletDict).length === 0) {
  662. this.openTupletNumber = 0;
  663. } else if (Object.keys(this.tupletDict).length > 1) {
  664. this.openTupletNumber--;
  665. }
  666. delete this.tupletDict[tupletnumber];
  667. }
  668. }
  669. }
  670. }
  671. return this.openTupletNumber;
  672. }
  673. /**
  674. * This method handles the time-modification IXmlElement for the Tuplet case (tupletNotes not at begin/end of Tuplet).
  675. * @param noteNode
  676. */
  677. private handleTimeModificationNode(noteNode: IXmlElement): void {
  678. if (this.tupletDict[this.openTupletNumber] !== undefined) {
  679. try {
  680. // Tuplet should already be created
  681. const tuplet: Tuplet = this.tupletDict[this.openTupletNumber];
  682. const notes: Note[] = CollectionUtil.last(tuplet.Notes);
  683. const lastTupletVoiceEntry: VoiceEntry = notes[0].ParentVoiceEntry;
  684. let noteList: Note[];
  685. if (lastTupletVoiceEntry.Timestamp.Equals(this.currentVoiceEntry.Timestamp)) {
  686. noteList = notes;
  687. } else {
  688. noteList = [];
  689. tuplet.Notes.push(noteList);
  690. tuplet.Fractions.push(this.getTupletNoteDurationFromType(noteNode));
  691. }
  692. noteList.push(this.currentNote);
  693. this.currentNote.NoteTuplet = tuplet;
  694. } catch (ex) {
  695. const errorMsg: string = ITextTranslation.translateText(
  696. "ReaderErrorMessages/TupletNumberError", "Invalid tuplet number."
  697. );
  698. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  699. throw ex;
  700. }
  701. } else if (this.currentVoiceEntry.Notes.length > 0) {
  702. const firstNote: Note = this.currentVoiceEntry.Notes[0];
  703. if (firstNote.NoteTuplet !== undefined) {
  704. const tuplet: Tuplet = firstNote.NoteTuplet;
  705. const notes: Note[] = CollectionUtil.last(tuplet.Notes);
  706. notes.push(this.currentNote);
  707. this.currentNote.NoteTuplet = tuplet;
  708. }
  709. }
  710. }
  711. private addTie(tieNodeList: IXmlElement[], measureStartAbsoluteTimestamp: Fraction, maxTieNoteFraction: Fraction): void {
  712. if (tieNodeList !== undefined) {
  713. if (tieNodeList.length === 1) {
  714. const tieNode: IXmlElement = tieNodeList[0];
  715. if (tieNode !== undefined && tieNode.attributes()) {
  716. const type: string = tieNode.attribute("type").value;
  717. try {
  718. if (type === "start") {
  719. const num: number = this.findCurrentNoteInTieDict(this.currentNote);
  720. if (num < 0) {
  721. delete this.openTieDict[num];
  722. }
  723. const newTieNumber: number = this.getNextAvailableNumberForTie();
  724. const tie: Tie = new Tie(this.currentNote);
  725. this.openTieDict[newTieNumber] = tie;
  726. } else if (type === "stop") {
  727. const tieNumber: number = this.findCurrentNoteInTieDict(this.currentNote);
  728. const tie: Tie = this.openTieDict[tieNumber];
  729. if (tie !== undefined) {
  730. tie.AddNote(this.currentNote);
  731. if (maxTieNoteFraction.lt(Fraction.plus(this.currentStaffEntry.Timestamp, this.currentNote.Length))) {
  732. maxTieNoteFraction = Fraction.plus(this.currentStaffEntry.Timestamp, this.currentNote.Length);
  733. }
  734. delete this.openTieDict[tieNumber];
  735. }
  736. }
  737. } catch (err) {
  738. const errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/TieError", "Error while reading tie.");
  739. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  740. }
  741. }
  742. } else if (tieNodeList.length === 2) {
  743. const tieNumber: number = this.findCurrentNoteInTieDict(this.currentNote);
  744. if (tieNumber >= 0) {
  745. const tie: Tie = this.openTieDict[tieNumber];
  746. tie.AddNote(this.currentNote);
  747. if (maxTieNoteFraction.lt(Fraction.plus(this.currentStaffEntry.Timestamp, this.currentNote.Length))) {
  748. maxTieNoteFraction = Fraction.plus(this.currentStaffEntry.Timestamp, this.currentNote.Length);
  749. }
  750. }
  751. }
  752. }
  753. }
  754. /**
  755. * Find the next free int (starting from 0) to use as key in TieDict.
  756. * @returns {number}
  757. */
  758. private getNextAvailableNumberForTie(): number {
  759. const keys: string[] = Object.keys(this.openTieDict);
  760. if (keys.length === 0) {
  761. return 1;
  762. }
  763. keys.sort((a, b) => (+a - +b)); // FIXME Andrea: test
  764. for (let i: number = 0; i < keys.length; i++) {
  765. if ("" + (i + 1) !== keys[i]) {
  766. return i + 1;
  767. }
  768. }
  769. return +(keys[keys.length - 1]) + 1;
  770. }
  771. /**
  772. * Search the tieDictionary for the corresponding candidateNote to the currentNote (same FundamentalNote && Octave).
  773. * @param candidateNote
  774. * @returns {number}
  775. */
  776. private findCurrentNoteInTieDict(candidateNote: Note): number {
  777. const openTieDict: { [_: number]: Tie; } = this.openTieDict;
  778. for (const key in openTieDict) {
  779. if (openTieDict.hasOwnProperty(key)) {
  780. const tie: Tie = openTieDict[key];
  781. if (tie.Pitch.FundamentalNote === candidateNote.Pitch.FundamentalNote && tie.Pitch.Octave === candidateNote.Pitch.Octave) {
  782. return +key;
  783. }
  784. }
  785. }
  786. return -1;
  787. }
  788. /**
  789. * Calculate the normal duration of a [[Tuplet]] note.
  790. * @param xmlNode
  791. * @returns {any}
  792. */
  793. private getTupletNoteDurationFromType(xmlNode: IXmlElement): Fraction {
  794. if (xmlNode.element("type") !== undefined) {
  795. const typeNode: IXmlElement = xmlNode.element("type");
  796. if (typeNode !== undefined) {
  797. const type: string = typeNode.value;
  798. try {
  799. return this.getNoteDurationFromType(type);
  800. } catch (e) {
  801. const errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/NoteDurationError", "Invalid note duration.");
  802. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  803. throw new MusicSheetReadingException("", e);
  804. }
  805. }
  806. }
  807. return undefined;
  808. }
  809. }