VoiceGenerator.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. import { Instrument } from "../Instrument";
  2. import { LinkedVoice } from "../VoiceData/LinkedVoice";
  3. import { Voice } from "../VoiceData/Voice";
  4. import { MusicSheet } from "../MusicSheet";
  5. import { VoiceEntry } 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 openTieDict: { [_: number]: Tie; } = {};
  56. private currentOctaveShift: number = 0;
  57. private tupletDict: { [_: number]: Tuplet; } = {};
  58. private openTupletNumber: number = 0;
  59. public get GetVoice(): Voice {
  60. return this.voice;
  61. }
  62. public get OctaveShift(): number {
  63. return this.currentOctaveShift;
  64. }
  65. public set OctaveShift(value: number) {
  66. this.currentOctaveShift = value;
  67. }
  68. /**
  69. * Create new [[VoiceEntry]], add it to given [[SourceStaffEntry]] and if given so, to [[Voice]].
  70. * @param musicTimestamp
  71. * @param parentStaffEntry
  72. * @param addToVoice
  73. * @param isGrace States whether the new VoiceEntry (only) has grace notes
  74. */
  75. public createVoiceEntry(musicTimestamp: Fraction, parentStaffEntry: SourceStaffEntry, addToVoice: boolean, isGrace: boolean = false): void {
  76. this.currentVoiceEntry = new VoiceEntry(musicTimestamp.clone(), this.voice, parentStaffEntry, isGrace);
  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);
  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): 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 (this.openBeam !== undefined) {
  433. this.handleOpenBeam();
  434. }
  435. this.openBeam = new Beam();
  436. }
  437. this.lastBeamTag = currentBeamTag;
  438. }
  439. let sameVoiceEntry: boolean = false;
  440. if (this.openBeam === undefined) {
  441. return;
  442. }
  443. for (let idx: number = 0, len: number = this.openBeam.Notes.length; idx < len; ++idx) {
  444. const beamNote: Note = this.openBeam.Notes[idx];
  445. if (this.currentVoiceEntry === beamNote.ParentVoiceEntry) {
  446. sameVoiceEntry = true;
  447. }
  448. }
  449. if (!sameVoiceEntry) {
  450. this.openBeam.addNoteToBeam(note);
  451. if (currentBeamTag === "end" && beamNumber === 1) {
  452. this.openBeam = undefined;
  453. }
  454. }
  455. }
  456. } catch (e) {
  457. const errorMsg: string = ITextTranslation.translateText(
  458. "ReaderErrorMessages/BeamError", "Error while reading beam."
  459. );
  460. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  461. throw new MusicSheetReadingException("", e);
  462. }
  463. }
  464. /**
  465. * Check for open [[Beam]]s at end of [[SourceMeasure]] and closes them explicity.
  466. */
  467. private handleOpenBeam(): void {
  468. if (this.openBeam.Notes.length === 1) {
  469. const beamNote: Note = this.openBeam.Notes[0];
  470. beamNote.NoteBeam = undefined;
  471. this.openBeam = undefined;
  472. return;
  473. }
  474. if (this.currentNote === CollectionUtil.last(this.openBeam.Notes)) {
  475. this.openBeam = undefined;
  476. } else {
  477. const beamLastNote: Note = CollectionUtil.last(this.openBeam.Notes);
  478. const beamLastNoteStaffEntry: SourceStaffEntry = beamLastNote.ParentStaffEntry;
  479. const horizontalIndex: number = this.currentMeasure.getVerticalContainerIndexByTimestamp(beamLastNoteStaffEntry.Timestamp);
  480. const verticalIndex: number = beamLastNoteStaffEntry.VerticalContainerParent.StaffEntries.indexOf(beamLastNoteStaffEntry);
  481. if (horizontalIndex < this.currentMeasure.VerticalSourceStaffEntryContainers.length - 1) {
  482. const nextStaffEntry: SourceStaffEntry = this.currentMeasure
  483. .VerticalSourceStaffEntryContainers[horizontalIndex + 1]
  484. .StaffEntries[verticalIndex];
  485. if (nextStaffEntry !== undefined) {
  486. for (let idx: number = 0, len: number = nextStaffEntry.VoiceEntries.length; idx < len; ++idx) {
  487. const voiceEntry: VoiceEntry = nextStaffEntry.VoiceEntries[idx];
  488. if (voiceEntry.ParentVoice === this.voice) {
  489. const candidateNote: Note = voiceEntry.Notes[0];
  490. if (candidateNote.Length.lte(new Fraction(1, 8))) {
  491. this.openBeam.addNoteToBeam(candidateNote);
  492. this.openBeam = undefined;
  493. } else {
  494. this.openBeam = undefined;
  495. }
  496. }
  497. }
  498. }
  499. } else {
  500. this.openBeam = undefined;
  501. }
  502. }
  503. }
  504. private handleGraceNote(node: IXmlElement, note: Note): void {
  505. let graceChord: boolean = false;
  506. let type: string = "";
  507. if (node.elements("type")) {
  508. const typeNode: IXmlElement[] = node.elements("type");
  509. if (typeNode) {
  510. type = typeNode[0].value;
  511. try {
  512. note.Length = this.getNoteDurationFromType(type);
  513. note.Length.Numerator = 1;
  514. } catch (e) {
  515. const errorMsg: string = ITextTranslation.translateText(
  516. "ReaderErrorMessages/NoteDurationError", "Invalid note duration."
  517. );
  518. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  519. throw new MusicSheetReadingException(errorMsg, e);
  520. }
  521. }
  522. }
  523. const graceNode: IXmlElement = node.element("grace");
  524. let graceNoteSlash: boolean = false;
  525. // TODO overlap with InstrumentReader.readNextXmlMeasure, which also checks whether there's a grace node in XML
  526. if (graceNode !== undefined && graceNode.attributes()) {
  527. if (graceNode.attribute("slash")) {
  528. const slash: string = graceNode.attribute("slash").value;
  529. if (slash === "yes") {
  530. graceNoteSlash = true;
  531. }
  532. }
  533. }
  534. if (node.element("chord") !== undefined) {
  535. graceChord = true;
  536. }
  537. let graceVoiceEntry: VoiceEntry = undefined;
  538. if (!graceChord) {
  539. graceVoiceEntry = new VoiceEntry(
  540. new Fraction(0, 1), this.currentVoiceEntry.ParentVoice, this.currentStaffEntry, true, graceNoteSlash
  541. );
  542. if (this.currentVoiceEntry.graceVoiceEntriesBefore === undefined) {
  543. this.currentVoiceEntry.graceVoiceEntriesBefore = [];
  544. }
  545. this.currentVoiceEntry.graceVoiceEntriesBefore.push(graceVoiceEntry);
  546. } else {
  547. if (
  548. this.currentVoiceEntry.graceVoiceEntriesBefore !== undefined
  549. && this.currentVoiceEntry.graceVoiceEntriesBefore.length > 0
  550. ) {
  551. graceVoiceEntry = CollectionUtil.last(this.currentVoiceEntry.graceVoiceEntriesBefore);
  552. }
  553. }
  554. if (graceVoiceEntry !== undefined) {
  555. graceVoiceEntry.Notes.push(note);
  556. note.ParentVoiceEntry = graceVoiceEntry;
  557. }
  558. }
  559. /**
  560. * Create a [[Tuplet]].
  561. * @param node
  562. * @param tupletNodeList
  563. * @returns {number}
  564. */
  565. private addTuplet(node: IXmlElement, tupletNodeList: IXmlElement[]): number {
  566. if (tupletNodeList !== undefined && tupletNodeList.length > 1) {
  567. let timeModNode: IXmlElement = node.element("time-modification");
  568. if (timeModNode !== undefined) {
  569. timeModNode = timeModNode.element("actual-notes");
  570. }
  571. const tupletNodeListArr: IXmlElement[] = tupletNodeList;
  572. for (let idx: number = 0, len: number = tupletNodeListArr.length; idx < len; ++idx) {
  573. const tupletNode: IXmlElement = tupletNodeListArr[idx];
  574. if (tupletNode !== undefined && tupletNode.attributes()) {
  575. const type: string = tupletNode.attribute("type").value;
  576. if (type === "start") {
  577. let tupletNumber: number = 1;
  578. if (tupletNode.attribute("number")) {
  579. tupletNumber = parseInt(tupletNode.attribute("number").value, 10);
  580. }
  581. let tupletLabelNumber: number = 0;
  582. if (timeModNode !== undefined) {
  583. tupletLabelNumber = parseInt(timeModNode.value, 10);
  584. if (isNaN(tupletLabelNumber)) {
  585. const errorMsg: string = ITextTranslation.translateText(
  586. "ReaderErrorMessages/TupletNoteDurationError", "Invalid tuplet note duration."
  587. );
  588. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  589. throw new MusicSheetReadingException(errorMsg, undefined);
  590. }
  591. }
  592. const tuplet: Tuplet = new Tuplet(tupletLabelNumber);
  593. if (this.tupletDict[tupletNumber] !== undefined) {
  594. delete this.tupletDict[tupletNumber];
  595. if (Object.keys(this.tupletDict).length === 0) {
  596. this.openTupletNumber = 0;
  597. } else if (Object.keys(this.tupletDict).length > 1) {
  598. this.openTupletNumber--;
  599. }
  600. }
  601. this.tupletDict[tupletNumber] = tuplet;
  602. const subnotelist: Note[] = [];
  603. subnotelist.push(this.currentNote);
  604. tuplet.Notes.push(subnotelist);
  605. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  606. this.currentNote.NoteTuplet = tuplet;
  607. this.openTupletNumber = tupletNumber;
  608. } else if (type === "stop") {
  609. let tupletNumber: number = 1;
  610. if (tupletNode.attribute("number")) {
  611. tupletNumber = parseInt(tupletNode.attribute("number").value, 10);
  612. }
  613. const tuplet: Tuplet = this.tupletDict[tupletNumber];
  614. if (tuplet !== undefined) {
  615. const subnotelist: Note[] = [];
  616. subnotelist.push(this.currentNote);
  617. tuplet.Notes.push(subnotelist);
  618. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  619. this.currentNote.NoteTuplet = tuplet;
  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. }
  628. }
  629. }
  630. } else if (tupletNodeList[0] !== undefined) {
  631. const n: IXmlElement = tupletNodeList[0];
  632. if (n.hasAttributes) {
  633. const type: string = n.attribute("type").value;
  634. let tupletnumber: number = 1;
  635. if (n.attribute("number")) {
  636. tupletnumber = parseInt(n.attribute("number").value, 10);
  637. }
  638. const noTupletNumbering: boolean = isNaN(tupletnumber);
  639. if (type === "start") {
  640. let tupletLabelNumber: number = 0;
  641. let timeModNode: IXmlElement = node.element("time-modification");
  642. if (timeModNode !== undefined) {
  643. timeModNode = timeModNode.element("actual-notes");
  644. }
  645. if (timeModNode !== undefined) {
  646. tupletLabelNumber = parseInt(timeModNode.value, 10);
  647. if (isNaN(tupletLabelNumber)) {
  648. const errorMsg: string = ITextTranslation.translateText(
  649. "ReaderErrorMessages/TupletNoteDurationError", "Invalid tuplet note duration."
  650. );
  651. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  652. throw new MusicSheetReadingException(errorMsg);
  653. }
  654. }
  655. if (noTupletNumbering) {
  656. this.openTupletNumber++;
  657. tupletnumber = this.openTupletNumber;
  658. }
  659. let tuplet: Tuplet = this.tupletDict[tupletnumber];
  660. if (tuplet === undefined) {
  661. tuplet = this.tupletDict[tupletnumber] = new Tuplet(tupletLabelNumber);
  662. }
  663. const subnotelist: Note[] = [];
  664. subnotelist.push(this.currentNote);
  665. tuplet.Notes.push(subnotelist);
  666. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  667. this.currentNote.NoteTuplet = tuplet;
  668. this.openTupletNumber = tupletnumber;
  669. } else if (type === "stop") {
  670. if (noTupletNumbering) {
  671. tupletnumber = this.openTupletNumber;
  672. }
  673. const tuplet: Tuplet = this.tupletDict[this.openTupletNumber];
  674. if (tuplet !== undefined) {
  675. const subnotelist: Note[] = [];
  676. subnotelist.push(this.currentNote);
  677. tuplet.Notes.push(subnotelist);
  678. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  679. this.currentNote.NoteTuplet = tuplet;
  680. if (Object.keys(this.tupletDict).length === 0) {
  681. this.openTupletNumber = 0;
  682. } else if (Object.keys(this.tupletDict).length > 1) {
  683. this.openTupletNumber--;
  684. }
  685. delete this.tupletDict[tupletnumber];
  686. }
  687. }
  688. }
  689. }
  690. return this.openTupletNumber;
  691. }
  692. /**
  693. * This method handles the time-modification IXmlElement for the Tuplet case (tupletNotes not at begin/end of Tuplet).
  694. * @param noteNode
  695. */
  696. private handleTimeModificationNode(noteNode: IXmlElement): void {
  697. if (this.tupletDict[this.openTupletNumber] !== undefined) {
  698. try {
  699. // Tuplet should already be created
  700. const tuplet: Tuplet = this.tupletDict[this.openTupletNumber];
  701. const notes: Note[] = CollectionUtil.last(tuplet.Notes);
  702. const lastTupletVoiceEntry: VoiceEntry = notes[0].ParentVoiceEntry;
  703. let noteList: Note[];
  704. if (lastTupletVoiceEntry.Timestamp.Equals(this.currentVoiceEntry.Timestamp)) {
  705. noteList = notes;
  706. } else {
  707. noteList = [];
  708. tuplet.Notes.push(noteList);
  709. tuplet.Fractions.push(this.getTupletNoteDurationFromType(noteNode));
  710. }
  711. noteList.push(this.currentNote);
  712. this.currentNote.NoteTuplet = tuplet;
  713. } catch (ex) {
  714. const errorMsg: string = ITextTranslation.translateText(
  715. "ReaderErrorMessages/TupletNumberError", "Invalid tuplet number."
  716. );
  717. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  718. throw ex;
  719. }
  720. } else if (this.currentVoiceEntry.Notes.length > 0) {
  721. const firstNote: Note = this.currentVoiceEntry.Notes[0];
  722. if (firstNote.NoteTuplet !== undefined) {
  723. const tuplet: Tuplet = firstNote.NoteTuplet;
  724. const notes: Note[] = CollectionUtil.last(tuplet.Notes);
  725. notes.push(this.currentNote);
  726. this.currentNote.NoteTuplet = tuplet;
  727. }
  728. }
  729. }
  730. private addTie(tieNodeList: IXmlElement[], measureStartAbsoluteTimestamp: Fraction, maxTieNoteFraction: Fraction): void {
  731. if (tieNodeList !== undefined) {
  732. if (tieNodeList.length === 1) {
  733. const tieNode: IXmlElement = tieNodeList[0];
  734. if (tieNode !== undefined && tieNode.attributes()) {
  735. const type: string = tieNode.attribute("type").value;
  736. try {
  737. if (type === "start") {
  738. const num: number = this.findCurrentNoteInTieDict(this.currentNote);
  739. if (num < 0) {
  740. delete this.openTieDict[num];
  741. }
  742. const newTieNumber: number = this.getNextAvailableNumberForTie();
  743. const tie: Tie = new Tie(this.currentNote);
  744. this.openTieDict[newTieNumber] = tie;
  745. } else if (type === "stop") {
  746. const tieNumber: number = this.findCurrentNoteInTieDict(this.currentNote);
  747. const tie: Tie = this.openTieDict[tieNumber];
  748. if (tie !== undefined) {
  749. tie.AddNote(this.currentNote);
  750. if (maxTieNoteFraction.lt(Fraction.plus(this.currentStaffEntry.Timestamp, this.currentNote.Length))) {
  751. maxTieNoteFraction = Fraction.plus(this.currentStaffEntry.Timestamp, this.currentNote.Length);
  752. }
  753. delete this.openTieDict[tieNumber];
  754. }
  755. }
  756. } catch (err) {
  757. const errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/TieError", "Error while reading tie.");
  758. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  759. }
  760. }
  761. } else if (tieNodeList.length === 2) {
  762. const tieNumber: number = this.findCurrentNoteInTieDict(this.currentNote);
  763. if (tieNumber >= 0) {
  764. const tie: Tie = this.openTieDict[tieNumber];
  765. tie.AddNote(this.currentNote);
  766. if (maxTieNoteFraction.lt(Fraction.plus(this.currentStaffEntry.Timestamp, this.currentNote.Length))) {
  767. maxTieNoteFraction = Fraction.plus(this.currentStaffEntry.Timestamp, this.currentNote.Length);
  768. }
  769. }
  770. }
  771. }
  772. }
  773. /**
  774. * Find the next free int (starting from 0) to use as key in TieDict.
  775. * @returns {number}
  776. */
  777. private getNextAvailableNumberForTie(): number {
  778. const keys: string[] = Object.keys(this.openTieDict);
  779. if (keys.length === 0) {
  780. return 1;
  781. }
  782. keys.sort((a, b) => (+a - +b)); // FIXME Andrea: test
  783. for (let i: number = 0; i < keys.length; i++) {
  784. if ("" + (i + 1) !== keys[i]) {
  785. return i + 1;
  786. }
  787. }
  788. return +(keys[keys.length - 1]) + 1;
  789. }
  790. /**
  791. * Search the tieDictionary for the corresponding candidateNote to the currentNote (same FundamentalNote && Octave).
  792. * @param candidateNote
  793. * @returns {number}
  794. */
  795. private findCurrentNoteInTieDict(candidateNote: Note): number {
  796. const openTieDict: { [_: number]: Tie; } = this.openTieDict;
  797. for (const key in openTieDict) {
  798. if (openTieDict.hasOwnProperty(key)) {
  799. const tie: Tie = openTieDict[key];
  800. if (tie.Pitch.FundamentalNote === candidateNote.Pitch.FundamentalNote && tie.Pitch.Octave === candidateNote.Pitch.Octave) {
  801. return +key;
  802. }
  803. }
  804. }
  805. return -1;
  806. }
  807. /**
  808. * Calculate the normal duration of a [[Tuplet]] note.
  809. * @param xmlNode
  810. * @returns {any}
  811. */
  812. private getTupletNoteDurationFromType(xmlNode: IXmlElement): Fraction {
  813. if (xmlNode.element("type") !== undefined) {
  814. const typeNode: IXmlElement = xmlNode.element("type");
  815. if (typeNode !== undefined) {
  816. const type: string = typeNode.value;
  817. try {
  818. return this.getNoteDurationFromType(type);
  819. } catch (e) {
  820. const errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/NoteDurationError", "Invalid note duration.");
  821. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  822. throw new MusicSheetReadingException("", e);
  823. }
  824. }
  825. }
  826. return undefined;
  827. }
  828. }