VoiceGenerator.ts 49 KB

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