VoiceGenerator.ts 33 KB

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