VoiceGenerator.ts 37 KB

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