VoiceGenerator.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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, 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, 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, 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.PrintObject = printObject;
  401. note.IsCueNote = isCueNote;
  402. note.StemDirectionXml = stemDirectionXml; // maybe unnecessary, also in VoiceEntry
  403. if ((noteheadShapeXml !== undefined && noteheadShapeXml !== "normal") || noteheadFilledXml !== undefined) {
  404. note.Notehead = new Notehead(note, noteheadShapeXml, noteheadFilledXml);
  405. } // if normal, leave note head undefined to save processing/runtime
  406. note.NoteheadColorXml = noteheadColorXml; // color set in Xml, shouldn't be changed.
  407. note.NoteheadColor = noteheadColorXml; // color currently used
  408. note.PlaybackInstrumentId = playbackInstrumentId;
  409. this.currentVoiceEntry.Notes.push(note);
  410. this.currentVoiceEntry.StemDirectionXml = stemDirectionXml;
  411. if (stemColorXml) {
  412. this.currentVoiceEntry.StemColorXml = stemColorXml;
  413. this.currentVoiceEntry.StemColor = stemColorXml;
  414. note.StemColorXml = stemColorXml;
  415. }
  416. if (node.elements("beam") && !chord) {
  417. this.createBeam(node, note);
  418. }
  419. return note;
  420. }
  421. /**
  422. * Create a new rest note and add it to the currentVoiceEntry.
  423. * @param noteDuration
  424. * @param divisions
  425. * @returns {Note}
  426. */
  427. private addRestNote(noteDuration: Fraction, printObject: boolean, isCueNote: boolean, noteheadColorXml: string): Note {
  428. const restFraction: Fraction = Fraction.createFromFraction(noteDuration);
  429. const restNote: Note = new Note(this.currentVoiceEntry, this.currentStaffEntry, restFraction, undefined);
  430. restNote.PrintObject = printObject;
  431. restNote.IsCueNote = isCueNote;
  432. restNote.NoteheadColorXml = noteheadColorXml;
  433. restNote.NoteheadColor = noteheadColorXml;
  434. this.currentVoiceEntry.Notes.push(restNote);
  435. if (this.openBeam !== undefined) {
  436. this.openBeam.ExtendedNoteList.push(restNote);
  437. }
  438. return restNote;
  439. }
  440. /**
  441. * Handle the currentVoiceBeam.
  442. * @param node
  443. * @param note
  444. */
  445. private createBeam(node: IXmlElement, note: Note): void {
  446. try {
  447. const beamNode: IXmlElement = node.element("beam");
  448. let beamAttr: IXmlAttribute = undefined;
  449. if (beamNode !== undefined && beamNode.hasAttributes) {
  450. beamAttr = beamNode.attribute("number");
  451. }
  452. if (beamAttr !== undefined) {
  453. const beamNumber: number = parseInt(beamAttr.value, 10);
  454. const mainBeamNode: IXmlElement[] = node.elements("beam");
  455. const currentBeamTag: string = mainBeamNode[0].value;
  456. if (beamNumber === 1 && mainBeamNode !== undefined) {
  457. if (currentBeamTag === "begin" && this.lastBeamTag !== currentBeamTag) {
  458. if (this.openBeam !== undefined) {
  459. this.handleOpenBeam();
  460. }
  461. this.openBeam = new Beam();
  462. }
  463. this.lastBeamTag = currentBeamTag;
  464. }
  465. let sameVoiceEntry: boolean = false;
  466. if (this.openBeam === undefined) {
  467. return;
  468. }
  469. for (let idx: number = 0, len: number = this.openBeam.Notes.length; idx < len; ++idx) {
  470. const beamNote: Note = this.openBeam.Notes[idx];
  471. if (this.currentVoiceEntry === beamNote.ParentVoiceEntry) {
  472. sameVoiceEntry = true;
  473. }
  474. }
  475. if (!sameVoiceEntry) {
  476. this.openBeam.addNoteToBeam(note);
  477. if (currentBeamTag === "end" && beamNumber === 1) {
  478. this.openBeam = undefined;
  479. }
  480. }
  481. }
  482. } catch (e) {
  483. const errorMsg: string = ITextTranslation.translateText(
  484. "ReaderErrorMessages/BeamError", "Error while reading beam."
  485. );
  486. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  487. throw new MusicSheetReadingException("", e);
  488. }
  489. }
  490. /**
  491. * Check for open [[Beam]]s at end of [[SourceMeasure]] and closes them explicity.
  492. */
  493. private handleOpenBeam(): void {
  494. if (this.openBeam.Notes.length === 1) {
  495. const beamNote: Note = this.openBeam.Notes[0];
  496. beamNote.NoteBeam = undefined;
  497. this.openBeam = undefined;
  498. return;
  499. }
  500. if (this.currentNote === CollectionUtil.last(this.openBeam.Notes)) {
  501. this.openBeam = undefined;
  502. } else {
  503. const beamLastNote: Note = CollectionUtil.last(this.openBeam.Notes);
  504. const beamLastNoteStaffEntry: SourceStaffEntry = beamLastNote.ParentStaffEntry;
  505. const horizontalIndex: number = this.currentMeasure.getVerticalContainerIndexByTimestamp(beamLastNoteStaffEntry.Timestamp);
  506. const verticalIndex: number = beamLastNoteStaffEntry.VerticalContainerParent.StaffEntries.indexOf(beamLastNoteStaffEntry);
  507. if (horizontalIndex < this.currentMeasure.VerticalSourceStaffEntryContainers.length - 1) {
  508. const nextStaffEntry: SourceStaffEntry = this.currentMeasure
  509. .VerticalSourceStaffEntryContainers[horizontalIndex + 1]
  510. .StaffEntries[verticalIndex];
  511. if (nextStaffEntry !== undefined) {
  512. for (let idx: number = 0, len: number = nextStaffEntry.VoiceEntries.length; idx < len; ++idx) {
  513. const voiceEntry: VoiceEntry = nextStaffEntry.VoiceEntries[idx];
  514. if (voiceEntry.ParentVoice === this.voice) {
  515. const candidateNote: Note = voiceEntry.Notes[0];
  516. if (candidateNote.Length.lte(new Fraction(1, 8))) {
  517. this.openBeam.addNoteToBeam(candidateNote);
  518. this.openBeam = undefined;
  519. } else {
  520. this.openBeam = undefined;
  521. }
  522. }
  523. }
  524. }
  525. } else {
  526. this.openBeam = undefined;
  527. }
  528. }
  529. }
  530. /**
  531. * Create a [[Tuplet]].
  532. * @param node
  533. * @param tupletNodeList
  534. * @returns {number}
  535. */
  536. private addTuplet(node: IXmlElement, tupletNodeList: IXmlElement[]): number {
  537. let bracketed: boolean = false; // xml bracket attribute value
  538. if (tupletNodeList !== undefined && tupletNodeList.length > 1) {
  539. let timeModNode: IXmlElement = node.element("time-modification");
  540. if (timeModNode !== undefined) {
  541. timeModNode = timeModNode.element("actual-notes");
  542. }
  543. const tupletNodeListArr: IXmlElement[] = tupletNodeList;
  544. for (let idx: number = 0, len: number = tupletNodeListArr.length; idx < len; ++idx) {
  545. const tupletNode: IXmlElement = tupletNodeListArr[idx];
  546. if (tupletNode !== undefined && tupletNode.attributes()) {
  547. const bracketAttr: Attr = tupletNode.attribute("bracket");
  548. if (bracketAttr && bracketAttr.value === "yes") {
  549. bracketed = true;
  550. }
  551. const type: Attr = tupletNode.attribute("type");
  552. if (type && type.value === "start") {
  553. let tupletNumber: number = 1;
  554. if (tupletNode.attribute("number")) {
  555. tupletNumber = parseInt(tupletNode.attribute("number").value, 10);
  556. }
  557. let tupletLabelNumber: number = 0;
  558. if (timeModNode !== undefined) {
  559. tupletLabelNumber = parseInt(timeModNode.value, 10);
  560. if (isNaN(tupletLabelNumber)) {
  561. const errorMsg: string = ITextTranslation.translateText(
  562. "ReaderErrorMessages/TupletNoteDurationError", "Invalid tuplet note duration."
  563. );
  564. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  565. throw new MusicSheetReadingException(errorMsg, undefined);
  566. }
  567. }
  568. const tuplet: Tuplet = new Tuplet(tupletLabelNumber, bracketed);
  569. if (this.tupletDict[tupletNumber] !== undefined) {
  570. delete this.tupletDict[tupletNumber];
  571. if (Object.keys(this.tupletDict).length === 0) {
  572. this.openTupletNumber = 0;
  573. } else if (Object.keys(this.tupletDict).length > 1) {
  574. this.openTupletNumber--;
  575. }
  576. }
  577. this.tupletDict[tupletNumber] = tuplet;
  578. const subnotelist: Note[] = [];
  579. subnotelist.push(this.currentNote);
  580. tuplet.Notes.push(subnotelist);
  581. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  582. this.currentNote.NoteTuplet = tuplet;
  583. this.openTupletNumber = tupletNumber;
  584. } else if (type.value === "stop") {
  585. let tupletNumber: number = 1;
  586. if (tupletNode.attribute("number")) {
  587. tupletNumber = parseInt(tupletNode.attribute("number").value, 10);
  588. }
  589. const tuplet: Tuplet = this.tupletDict[tupletNumber];
  590. if (tuplet !== undefined) {
  591. const subnotelist: Note[] = [];
  592. subnotelist.push(this.currentNote);
  593. tuplet.Notes.push(subnotelist);
  594. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  595. this.currentNote.NoteTuplet = tuplet;
  596. delete this.tupletDict[tupletNumber];
  597. if (Object.keys(this.tupletDict).length === 0) {
  598. this.openTupletNumber = 0;
  599. } else if (Object.keys(this.tupletDict).length > 1) {
  600. this.openTupletNumber--;
  601. }
  602. }
  603. }
  604. }
  605. }
  606. } else if (tupletNodeList[0] !== undefined) {
  607. const n: IXmlElement = tupletNodeList[0];
  608. if (n.hasAttributes) {
  609. const type: string = n.attribute("type").value;
  610. let tupletnumber: number = 1;
  611. if (n.attribute("number")) {
  612. tupletnumber = parseInt(n.attribute("number").value, 10);
  613. }
  614. const noTupletNumbering: boolean = isNaN(tupletnumber);
  615. const bracketAttr: Attr = n.attribute("bracket");
  616. if (bracketAttr && bracketAttr.value === "yes") {
  617. bracketed = true;
  618. }
  619. if (type === "start") {
  620. let tupletLabelNumber: number = 0;
  621. let timeModNode: IXmlElement = node.element("time-modification");
  622. if (timeModNode !== undefined) {
  623. timeModNode = timeModNode.element("actual-notes");
  624. }
  625. if (timeModNode !== undefined) {
  626. tupletLabelNumber = parseInt(timeModNode.value, 10);
  627. if (isNaN(tupletLabelNumber)) {
  628. const errorMsg: string = ITextTranslation.translateText(
  629. "ReaderErrorMessages/TupletNoteDurationError", "Invalid tuplet note duration."
  630. );
  631. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  632. throw new MusicSheetReadingException(errorMsg);
  633. }
  634. }
  635. if (noTupletNumbering) {
  636. this.openTupletNumber++;
  637. tupletnumber = this.openTupletNumber;
  638. }
  639. let tuplet: Tuplet = this.tupletDict[tupletnumber];
  640. if (tuplet === undefined) {
  641. tuplet = this.tupletDict[tupletnumber] = new Tuplet(tupletLabelNumber, bracketed);
  642. }
  643. const subnotelist: Note[] = [];
  644. subnotelist.push(this.currentNote);
  645. tuplet.Notes.push(subnotelist);
  646. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  647. this.currentNote.NoteTuplet = tuplet;
  648. this.openTupletNumber = tupletnumber;
  649. } else if (type === "stop") {
  650. if (noTupletNumbering) {
  651. tupletnumber = this.openTupletNumber;
  652. }
  653. const tuplet: Tuplet = this.tupletDict[this.openTupletNumber];
  654. if (tuplet !== undefined) {
  655. const subnotelist: Note[] = [];
  656. subnotelist.push(this.currentNote);
  657. tuplet.Notes.push(subnotelist);
  658. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  659. this.currentNote.NoteTuplet = tuplet;
  660. if (Object.keys(this.tupletDict).length === 0) {
  661. this.openTupletNumber = 0;
  662. } else if (Object.keys(this.tupletDict).length > 1) {
  663. this.openTupletNumber--;
  664. }
  665. delete this.tupletDict[tupletnumber];
  666. }
  667. }
  668. }
  669. }
  670. return this.openTupletNumber;
  671. }
  672. /**
  673. * This method handles the time-modification IXmlElement for the Tuplet case (tupletNotes not at begin/end of Tuplet).
  674. * @param noteNode
  675. */
  676. private handleTimeModificationNode(noteNode: IXmlElement): void {
  677. if (this.tupletDict[this.openTupletNumber] !== undefined) {
  678. try {
  679. // Tuplet should already be created
  680. const tuplet: Tuplet = this.tupletDict[this.openTupletNumber];
  681. const notes: Note[] = CollectionUtil.last(tuplet.Notes);
  682. const lastTupletVoiceEntry: VoiceEntry = notes[0].ParentVoiceEntry;
  683. let noteList: Note[];
  684. if (lastTupletVoiceEntry.Timestamp.Equals(this.currentVoiceEntry.Timestamp)) {
  685. noteList = notes;
  686. } else {
  687. noteList = [];
  688. tuplet.Notes.push(noteList);
  689. tuplet.Fractions.push(this.getTupletNoteDurationFromType(noteNode));
  690. }
  691. noteList.push(this.currentNote);
  692. this.currentNote.NoteTuplet = tuplet;
  693. } catch (ex) {
  694. const errorMsg: string = ITextTranslation.translateText(
  695. "ReaderErrorMessages/TupletNumberError", "Invalid tuplet number."
  696. );
  697. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  698. throw ex;
  699. }
  700. } else if (this.currentVoiceEntry.Notes.length > 0) {
  701. const firstNote: Note = this.currentVoiceEntry.Notes[0];
  702. if (firstNote.NoteTuplet !== undefined) {
  703. const tuplet: Tuplet = firstNote.NoteTuplet;
  704. const notes: Note[] = CollectionUtil.last(tuplet.Notes);
  705. notes.push(this.currentNote);
  706. this.currentNote.NoteTuplet = tuplet;
  707. }
  708. }
  709. }
  710. private addTie(tieNodeList: IXmlElement[], measureStartAbsoluteTimestamp: Fraction, maxTieNoteFraction: Fraction): void {
  711. if (tieNodeList !== undefined) {
  712. if (tieNodeList.length === 1) {
  713. const tieNode: IXmlElement = tieNodeList[0];
  714. if (tieNode !== undefined && tieNode.attributes()) {
  715. const type: string = tieNode.attribute("type").value;
  716. try {
  717. if (type === "start") {
  718. const num: number = this.findCurrentNoteInTieDict(this.currentNote);
  719. if (num < 0) {
  720. delete this.openTieDict[num];
  721. }
  722. const newTieNumber: number = this.getNextAvailableNumberForTie();
  723. const tie: Tie = new Tie(this.currentNote);
  724. this.openTieDict[newTieNumber] = tie;
  725. } else if (type === "stop") {
  726. const tieNumber: number = this.findCurrentNoteInTieDict(this.currentNote);
  727. const tie: Tie = this.openTieDict[tieNumber];
  728. if (tie !== undefined) {
  729. tie.AddNote(this.currentNote);
  730. if (maxTieNoteFraction.lt(Fraction.plus(this.currentStaffEntry.Timestamp, this.currentNote.Length))) {
  731. maxTieNoteFraction = Fraction.plus(this.currentStaffEntry.Timestamp, this.currentNote.Length);
  732. }
  733. delete this.openTieDict[tieNumber];
  734. }
  735. }
  736. } catch (err) {
  737. const errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/TieError", "Error while reading tie.");
  738. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  739. }
  740. }
  741. } else if (tieNodeList.length === 2) {
  742. const tieNumber: number = this.findCurrentNoteInTieDict(this.currentNote);
  743. if (tieNumber >= 0) {
  744. const tie: Tie = this.openTieDict[tieNumber];
  745. tie.AddNote(this.currentNote);
  746. if (maxTieNoteFraction.lt(Fraction.plus(this.currentStaffEntry.Timestamp, this.currentNote.Length))) {
  747. maxTieNoteFraction = Fraction.plus(this.currentStaffEntry.Timestamp, this.currentNote.Length);
  748. }
  749. }
  750. }
  751. }
  752. }
  753. /**
  754. * Find the next free int (starting from 0) to use as key in TieDict.
  755. * @returns {number}
  756. */
  757. private getNextAvailableNumberForTie(): number {
  758. const keys: string[] = Object.keys(this.openTieDict);
  759. if (keys.length === 0) {
  760. return 1;
  761. }
  762. keys.sort((a, b) => (+a - +b)); // FIXME Andrea: test
  763. for (let i: number = 0; i < keys.length; i++) {
  764. if ("" + (i + 1) !== keys[i]) {
  765. return i + 1;
  766. }
  767. }
  768. return +(keys[keys.length - 1]) + 1;
  769. }
  770. /**
  771. * Search the tieDictionary for the corresponding candidateNote to the currentNote (same FundamentalNote && Octave).
  772. * @param candidateNote
  773. * @returns {number}
  774. */
  775. private findCurrentNoteInTieDict(candidateNote: Note): number {
  776. const openTieDict: { [_: number]: Tie; } = this.openTieDict;
  777. for (const key in openTieDict) {
  778. if (openTieDict.hasOwnProperty(key)) {
  779. const tie: Tie = openTieDict[key];
  780. if (tie.Pitch.FundamentalNote === candidateNote.Pitch.FundamentalNote && tie.Pitch.Octave === candidateNote.Pitch.Octave) {
  781. return +key;
  782. }
  783. }
  784. }
  785. return -1;
  786. }
  787. /**
  788. * Calculate the normal duration of a [[Tuplet]] note.
  789. * @param xmlNode
  790. * @returns {any}
  791. */
  792. private getTupletNoteDurationFromType(xmlNode: IXmlElement): Fraction {
  793. if (xmlNode.element("type") !== undefined) {
  794. const typeNode: IXmlElement = xmlNode.element("type");
  795. if (typeNode !== undefined) {
  796. const type: string = typeNode.value;
  797. try {
  798. return this.getNoteDurationFromType(type);
  799. } catch (e) {
  800. const errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/NoteDurationError", "Invalid note duration.");
  801. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  802. throw new MusicSheetReadingException("", e);
  803. }
  804. }
  805. }
  806. return undefined;
  807. }
  808. }