VoiceGenerator.ts 35 KB

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