VoiceGenerator.ts 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  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 notationNode: IXmlElement = noteNode.element("notations");
  120. if (notationNode !== undefined) {
  121. // let articNode: IXmlElement = undefined;
  122. // (*)
  123. //if (this.articulationReader !== undefined) {
  124. // this.readArticulations(notationNode, this.currentVoiceEntry);
  125. //}
  126. //let slurNodes: IXmlElement[] = undefined;
  127. // (*)
  128. //if (this.slurReader !== undefined && (slurNodes = notationNode.elements("slur")))
  129. // this.slurReader.addSlur(slurNodes, this.currentNote);
  130. let tupletNodeList: IXmlElement[] = notationNode.elements("tuplet");
  131. if (tupletNodeList) {
  132. this.openTupletNumber = this.addTuplet(noteNode, tupletNodeList);
  133. }
  134. if (notationNode.element("arpeggiate") !== undefined && !graceNote) {
  135. this.currentVoiceEntry.ArpeggiosNotesIndices.push(this.currentVoiceEntry.Notes.indexOf(this.currentNote));
  136. }
  137. let tiedNodeList: IXmlElement[] = notationNode.elements("tied");
  138. if (tiedNodeList) {
  139. this.addTie(tiedNodeList, measureStartAbsoluteTimestamp, maxTieNoteFraction);
  140. }
  141. let openTieDict: { [_: number]: Tie; } = this.openTieDict;
  142. for (let key in openTieDict) {
  143. if (openTieDict.hasOwnProperty(key)) {
  144. let tie: Tie = openTieDict[key];
  145. if (Fraction.plus(tie.Start.ParentStaffEntry.Timestamp, tie.Start.Length).lt(this.currentStaffEntry.Timestamp)) {
  146. delete openTieDict[key];
  147. }
  148. }
  149. }
  150. }
  151. if (noteNode.element("time-modification") !== undefined && notationNode === undefined) {
  152. this.handleTimeModificationNode(noteNode);
  153. }
  154. } catch (err) {
  155. let errorMsg: string = ITextTranslation.translateText(
  156. "ReaderErrorMessages/NoteError", "Ignored erroneous Note."
  157. );
  158. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  159. }
  160. return this.currentNote;
  161. }
  162. /**
  163. * Handle the GraceNotes that appear before the Measure's End
  164. * and aren't assigned to any normal (with [[VoiceEntries]]) [[SourceStaffEntry]]s yet.
  165. */
  166. public checkForOpenGraceNotes(): void {
  167. if (
  168. this.currentStaffEntry !== undefined
  169. && this.currentStaffEntry.VoiceEntries.length === 0
  170. && this.currentVoiceEntry.graceVoiceEntriesBefore !== undefined
  171. && this.currentVoiceEntry.graceVoiceEntriesBefore.length > 0
  172. ) {
  173. let voice: Voice = this.currentVoiceEntry.ParentVoice;
  174. let horizontalIndex: number = this.currentMeasure.VerticalSourceStaffEntryContainers.indexOf(this.currentStaffEntry.VerticalContainerParent);
  175. let verticalIndex: number = this.currentStaffEntry.VerticalContainerParent.StaffEntries.indexOf(this.currentStaffEntry);
  176. let previousStaffEntry: SourceStaffEntry = this.currentMeasure.getPreviousSourceStaffEntryFromIndex(verticalIndex, horizontalIndex);
  177. if (previousStaffEntry !== undefined) {
  178. let previousVoiceEntry: VoiceEntry = undefined;
  179. for (let idx: number = 0, len: number = previousStaffEntry.VoiceEntries.length; idx < len; ++idx) {
  180. let voiceEntry: VoiceEntry = previousStaffEntry.VoiceEntries[idx];
  181. if (voiceEntry.ParentVoice === voice) {
  182. previousVoiceEntry = voiceEntry;
  183. previousVoiceEntry.graceVoiceEntriesAfter = [];
  184. for (let idx2: number = 0, len2: number = this.currentVoiceEntry.graceVoiceEntriesBefore.length; idx2 < len2; ++idx2) {
  185. let graceVoiceEntry: VoiceEntry = this.currentVoiceEntry.graceVoiceEntriesBefore[idx2];
  186. previousVoiceEntry.graceVoiceEntriesAfter.push(graceVoiceEntry);
  187. }
  188. this.currentVoiceEntry.graceVoiceEntriesBefore = [];
  189. this.currentStaffEntry = undefined;
  190. break;
  191. }
  192. }
  193. }
  194. }
  195. }
  196. /**
  197. * Create a new [[StaffEntryLink]] and sets the currenstStaffEntry accordingly.
  198. * @param index
  199. * @param currentStaff
  200. * @param currentStaffEntry
  201. * @param currentMeasure
  202. * @returns {SourceStaffEntry}
  203. */
  204. public checkForStaffEntryLink(
  205. index: number, currentStaff: Staff, currentStaffEntry: SourceStaffEntry, currentMeasure: SourceMeasure
  206. ): SourceStaffEntry {
  207. let staffEntryLink: StaffEntryLink = new StaffEntryLink(this.currentVoiceEntry);
  208. staffEntryLink.LinkStaffEntries.push(currentStaffEntry);
  209. currentStaffEntry.Link = staffEntryLink;
  210. let linkMusicTimestamp: Fraction = this.currentVoiceEntry.Timestamp.clone();
  211. let 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. let openTieDict: {[key: number]: Tie} = this.openTieDict;
  229. for (let key in openTieDict) {
  230. if (openTieDict.hasOwnProperty(key)) {
  231. let tie: Tie = openTieDict[key];
  232. if (Fraction.plus(tie.Start.ParentStaffEntry.Timestamp, tie.Start.Length)
  233. .lt(tie.Start.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. let errorMsg: string = ITextTranslation.translateText(
  280. "ReaderErrorMessages/NoteDurationError", "Invalid note duration."
  281. );
  282. throw new MusicSheetReadingException(errorMsg);
  283. }
  284. }
  285. }
  286. // (*)
  287. //private readArticulations(notationNode: IXmlElement, currentVoiceEntry: VoiceEntry): void {
  288. // let articNode: IXmlElement;
  289. // if ((articNode = notationNode.element("articulations")) !== undefined)
  290. // this.articulationReader.addArticulationExpression(articNode, currentVoiceEntry);
  291. // let fermaNode: IXmlElement = undefined;
  292. // if ((fermaNode = notationNode.element("fermata")) !== undefined)
  293. // this.articulationReader.addFermata(fermaNode, currentVoiceEntry);
  294. // let tecNode: IXmlElement = undefined;
  295. // if ((tecNode = notationNode.element("technical")) !== undefined)
  296. // this.articulationReader.addTechnicalArticulations(tecNode, currentVoiceEntry);
  297. // let ornaNode: IXmlElement = undefined;
  298. // if ((ornaNode = notationNode.element("ornaments")) !== undefined)
  299. // this.articulationReader.addOrnament(ornaNode, currentVoiceEntry);
  300. //}
  301. /**
  302. * Create a new [[Note]] and adds it to the currentVoiceEntry
  303. * @param node
  304. * @param noteDuration
  305. * @param divisions
  306. * @param graceNote
  307. * @param chord
  308. * @param guitarPro
  309. * @returns {Note}
  310. */
  311. private addSingleNote(
  312. node: IXmlElement, noteDuration: Fraction, graceNote: boolean, chord: boolean, guitarPro: boolean
  313. ): Note {
  314. //Logging.debug("addSingleNote called");
  315. let noteAlter: AccidentalEnum = AccidentalEnum.NONE;
  316. let noteStep: NoteEnum = NoteEnum.C;
  317. let noteOctave: number = 0;
  318. let playbackInstrumentId: string = undefined;
  319. let xmlnodeElementsArr: IXmlElement[] = node.elements();
  320. for (let idx: number = 0, len: number = xmlnodeElementsArr.length; idx < len; ++idx) {
  321. let noteElement: IXmlElement = xmlnodeElementsArr[idx];
  322. try {
  323. if (noteElement.name === "pitch") {
  324. let noteElementsArr: IXmlElement[] = noteElement.elements();
  325. for (let idx2: number = 0, len2: number = noteElementsArr.length; idx2 < len2; ++idx2) {
  326. let pitchElement: IXmlElement = noteElementsArr[idx2];
  327. try {
  328. if (pitchElement.name === "step") {
  329. noteStep = NoteEnum[pitchElement.value];
  330. if (noteStep === undefined) {
  331. let errorMsg: string = ITextTranslation.translateText(
  332. "ReaderErrorMessages/NotePitchError",
  333. "Invalid pitch while reading note."
  334. );
  335. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  336. throw new MusicSheetReadingException(errorMsg, undefined);
  337. }
  338. } else if (pitchElement.name === "alter") {
  339. noteAlter = parseInt(pitchElement.value, 10);
  340. if (isNaN(noteAlter)) {
  341. let errorMsg: string = ITextTranslation.translateText(
  342. "ReaderErrorMessages/NoteAlterationError", "Invalid alteration while reading note."
  343. );
  344. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  345. throw new MusicSheetReadingException(errorMsg, undefined);
  346. }
  347. } else if (pitchElement.name === "octave") {
  348. noteOctave = parseInt(pitchElement.value, 10);
  349. if (isNaN(noteOctave)) {
  350. let errorMsg: string = ITextTranslation.translateText(
  351. "ReaderErrorMessages/NoteOctaveError", "Invalid octave value while reading note."
  352. );
  353. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  354. throw new MusicSheetReadingException(errorMsg, undefined);
  355. }
  356. }
  357. } catch (ex) {
  358. Logging.log("VoiceGenerator.addSingleNote read Step: ", ex.message);
  359. }
  360. }
  361. } else if (noteElement.name === "unpitched") {
  362. let displayStep: IXmlElement = noteElement.element("display-step");
  363. if (displayStep !== undefined) {
  364. noteStep = NoteEnum[displayStep.value.toUpperCase()];
  365. }
  366. let octave: IXmlElement = noteElement.element("display-octave");
  367. if (octave !== undefined) {
  368. noteOctave = parseInt(octave.value, 10);
  369. if (guitarPro) {
  370. noteOctave += 1;
  371. }
  372. }
  373. } else if (noteElement.name === "instrument") {
  374. if (noteElement.firstAttribute !== undefined) {
  375. playbackInstrumentId = noteElement.firstAttribute.value;
  376. }
  377. }
  378. } catch (ex) {
  379. Logging.log("VoiceGenerator.addSingleNote: ", ex);
  380. }
  381. }
  382. noteOctave -= Pitch.OctaveXmlDifference;
  383. let pitch: Pitch = new Pitch(noteStep, noteOctave, noteAlter);
  384. let noteLength: Fraction = Fraction.createFromFraction(noteDuration);
  385. let note: Note = new Note(this.currentVoiceEntry, this.currentStaffEntry, noteLength, pitch);
  386. note.PlaybackInstrumentId = playbackInstrumentId;
  387. if (!graceNote) {
  388. this.currentVoiceEntry.Notes.push(note);
  389. } else {
  390. this.handleGraceNote(node, note);
  391. }
  392. if (node.elements("beam") && !chord) {
  393. this.createBeam(node, note, graceNote);
  394. }
  395. return note;
  396. }
  397. /**
  398. * Create a new rest note and add it to the currentVoiceEntry.
  399. * @param noteDuration
  400. * @param divisions
  401. * @returns {Note}
  402. */
  403. private addRestNote(noteDuration: Fraction): Note {
  404. let restFraction: Fraction = Fraction.createFromFraction(noteDuration);
  405. let restNote: Note = new Note(this.currentVoiceEntry, this.currentStaffEntry, restFraction, undefined);
  406. this.currentVoiceEntry.Notes.push(restNote);
  407. if (this.openBeam !== undefined) {
  408. this.openBeam.ExtendedNoteList.push(restNote);
  409. }
  410. return restNote;
  411. }
  412. /**
  413. * Handle the currentVoiceBeam.
  414. * @param node
  415. * @param note
  416. * @param grace
  417. */
  418. private createBeam(node: IXmlElement, note: Note, grace: boolean): void {
  419. try {
  420. let beamNode: IXmlElement = node.element("beam");
  421. let beamAttr: IXmlAttribute = undefined;
  422. if (beamNode !== undefined && beamNode.hasAttributes) {
  423. beamAttr = beamNode.attribute("number");
  424. }
  425. if (beamAttr !== undefined) {
  426. let beamNumber: number = parseInt(beamAttr.value, 10);
  427. let mainBeamNode: IXmlElement[] = node.elements("beam");
  428. let currentBeamTag: string = mainBeamNode[0].value;
  429. if (beamNumber === 1 && mainBeamNode !== undefined) {
  430. if (currentBeamTag === "begin" && this.lastBeamTag !== currentBeamTag) {
  431. if (grace) {
  432. if (this.openGraceBeam !== undefined) {
  433. this.handleOpenBeam();
  434. }
  435. this.openGraceBeam = new Beam();
  436. } else {
  437. if (this.openBeam !== undefined) {
  438. this.handleOpenBeam();
  439. }
  440. this.openBeam = new Beam();
  441. }
  442. }
  443. this.lastBeamTag = currentBeamTag;
  444. }
  445. let sameVoiceEntry: boolean = false;
  446. if (grace) {
  447. if (this.openGraceBeam === undefined) { return; }
  448. for (let idx: number = 0, len: number = this.openGraceBeam.Notes.length; idx < len; ++idx) {
  449. let beamNote: Note = this.openGraceBeam.Notes[idx];
  450. if (this.currentVoiceEntry === beamNote.ParentVoiceEntry) {
  451. sameVoiceEntry = true;
  452. }
  453. }
  454. if (!sameVoiceEntry) {
  455. this.openGraceBeam.addNoteToBeam(note);
  456. if (currentBeamTag === "end" && beamNumber === 1) {
  457. this.openGraceBeam = undefined;
  458. }
  459. }
  460. } else {
  461. if (this.openBeam === undefined) { return; }
  462. for (let idx: number = 0, len: number = this.openBeam.Notes.length; idx < len; ++idx) {
  463. let beamNote: Note = this.openBeam.Notes[idx];
  464. if (this.currentVoiceEntry === beamNote.ParentVoiceEntry) {
  465. sameVoiceEntry = true;
  466. }
  467. }
  468. if (!sameVoiceEntry) {
  469. this.openBeam.addNoteToBeam(note);
  470. if (currentBeamTag === "end" && beamNumber === 1) {
  471. this.openBeam = undefined;
  472. }
  473. }
  474. }
  475. }
  476. } catch (e) {
  477. let errorMsg: string = ITextTranslation.translateText(
  478. "ReaderErrorMessages/BeamError", "Error while reading beam."
  479. );
  480. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  481. throw new MusicSheetReadingException("", e);
  482. }
  483. }
  484. /**
  485. * Check for open [[Beam]]s at end of [[SourceMeasure]] and closes them explicity.
  486. */
  487. private handleOpenBeam(): void {
  488. if (this.openBeam.Notes.length === 1) {
  489. let beamNote: Note = this.openBeam.Notes[0];
  490. beamNote.NoteBeam = undefined;
  491. this.openBeam = undefined;
  492. return;
  493. }
  494. if (this.currentNote === CollectionUtil.last(this.openBeam.Notes)) {
  495. this.openBeam = undefined;
  496. } else {
  497. let beamLastNote: Note = CollectionUtil.last(this.openBeam.Notes);
  498. let beamLastNoteStaffEntry: SourceStaffEntry = beamLastNote.ParentStaffEntry;
  499. let horizontalIndex: number = this.currentMeasure.getVerticalContainerIndexByTimestamp(beamLastNoteStaffEntry.Timestamp);
  500. let verticalIndex: number = beamLastNoteStaffEntry.VerticalContainerParent.StaffEntries.indexOf(beamLastNoteStaffEntry);
  501. if (horizontalIndex < this.currentMeasure.VerticalSourceStaffEntryContainers.length - 1) {
  502. let nextStaffEntry: SourceStaffEntry = this.currentMeasure.VerticalSourceStaffEntryContainers[horizontalIndex + 1].StaffEntries[verticalIndex];
  503. if (nextStaffEntry !== undefined) {
  504. for (let idx: number = 0, len: number = nextStaffEntry.VoiceEntries.length; idx < len; ++idx) {
  505. let voiceEntry: VoiceEntry = nextStaffEntry.VoiceEntries[idx];
  506. if (voiceEntry.ParentVoice === this.voice) {
  507. let candidateNote: Note = voiceEntry.Notes[0];
  508. if (candidateNote.Length.lte(new Fraction(1, 8))) {
  509. this.openBeam.addNoteToBeam(candidateNote);
  510. this.openBeam = undefined;
  511. } else {
  512. this.openBeam = undefined;
  513. }
  514. }
  515. }
  516. }
  517. } else {
  518. this.openBeam = undefined;
  519. }
  520. }
  521. }
  522. private handleGraceNote(node: IXmlElement, note: Note): void {
  523. let graceChord: boolean = false;
  524. let type: string = "";
  525. if (node.elements("type")) {
  526. let typeNode: IXmlElement[] = node.elements("type");
  527. if (typeNode) {
  528. type = typeNode[0].value;
  529. try {
  530. note.Length = this.getNoteDurationFromType(type);
  531. note.Length.Numerator = 1;
  532. } catch (e) {
  533. let errorMsg: string = ITextTranslation.translateText(
  534. "ReaderErrorMessages/NoteDurationError", "Invalid note duration."
  535. );
  536. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  537. throw new MusicSheetReadingException(errorMsg, e);
  538. }
  539. }
  540. }
  541. let graceNode: IXmlElement = node.element("grace");
  542. if (graceNode !== undefined && graceNode.attributes()) {
  543. if (graceNode.attribute("slash")) {
  544. let slash: string = graceNode.attribute("slash").value;
  545. if (slash === "yes") {
  546. note.GraceNoteSlash = true;
  547. }
  548. }
  549. }
  550. if (node.element("chord") !== undefined) {
  551. graceChord = true;
  552. }
  553. let graceVoiceEntry: VoiceEntry = undefined;
  554. if (!graceChord) {
  555. graceVoiceEntry = new VoiceEntry(
  556. new Fraction(0, 1), this.currentVoiceEntry.ParentVoice, this.currentStaffEntry
  557. );
  558. if (this.currentVoiceEntry.graceVoiceEntriesBefore === undefined) {
  559. this.currentVoiceEntry.graceVoiceEntriesBefore = [];
  560. }
  561. this.currentVoiceEntry.graceVoiceEntriesBefore.push(graceVoiceEntry);
  562. } else {
  563. if (
  564. this.currentVoiceEntry.graceVoiceEntriesBefore !== undefined
  565. && this.currentVoiceEntry.graceVoiceEntriesBefore.length > 0
  566. ) {
  567. graceVoiceEntry = CollectionUtil.last(this.currentVoiceEntry.graceVoiceEntriesBefore);
  568. }
  569. }
  570. if (graceVoiceEntry !== undefined) {
  571. graceVoiceEntry.Notes.push(note);
  572. note.ParentVoiceEntry = graceVoiceEntry;
  573. }
  574. }
  575. /**
  576. * Create a [[Tuplet]].
  577. * @param node
  578. * @param tupletNodeList
  579. * @returns {number}
  580. */
  581. private addTuplet(node: IXmlElement, tupletNodeList: IXmlElement[]): number {
  582. if (tupletNodeList !== undefined && tupletNodeList.length > 1) {
  583. let timeModNode: IXmlElement = node.element("time-modification");
  584. if (timeModNode !== undefined) {
  585. timeModNode = timeModNode.element("actual-notes");
  586. }
  587. let tupletNodeListArr: IXmlElement[] = tupletNodeList;
  588. for (let idx: number = 0, len: number = tupletNodeListArr.length; idx < len; ++idx) {
  589. let tupletNode: IXmlElement = tupletNodeListArr[idx];
  590. if (tupletNode !== undefined && tupletNode.attributes()) {
  591. let type: string = tupletNode.attribute("type").value;
  592. if (type === "start") {
  593. let tupletNumber: number = 1;
  594. if (tupletNode.attribute("number")) {
  595. tupletNumber = parseInt(tupletNode.attribute("number").value, 10);
  596. }
  597. let tupletLabelNumber: number = 0;
  598. if (timeModNode !== undefined) {
  599. tupletLabelNumber = parseInt(timeModNode.value, 10);
  600. if (isNaN(tupletLabelNumber)) {
  601. let errorMsg: string = ITextTranslation.translateText(
  602. "ReaderErrorMessages/TupletNoteDurationError", "Invalid tuplet note duration."
  603. );
  604. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  605. throw new MusicSheetReadingException(errorMsg, undefined);
  606. }
  607. }
  608. let tuplet: Tuplet = new Tuplet(tupletLabelNumber);
  609. if (this.tupletDict[tupletNumber] !== undefined) {
  610. delete this.tupletDict[tupletNumber];
  611. if (Object.keys(this.tupletDict).length === 0) {
  612. this.openTupletNumber = 0;
  613. } else if (Object.keys(this.tupletDict).length > 1) {
  614. this.openTupletNumber--;
  615. }
  616. }
  617. this.tupletDict[tupletNumber] = tuplet;
  618. let subnotelist: Note[] = [];
  619. subnotelist.push(this.currentNote);
  620. tuplet.Notes.push(subnotelist);
  621. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  622. this.currentNote.NoteTuplet = tuplet;
  623. this.openTupletNumber = tupletNumber;
  624. } else if (type === "stop") {
  625. let tupletNumber: number = 1;
  626. if (tupletNode.attribute("number")) {
  627. tupletNumber = parseInt(tupletNode.attribute("number").value, 10);
  628. }
  629. let tuplet: Tuplet = this.tupletDict[tupletNumber];
  630. if (tuplet !== undefined) {
  631. let subnotelist: Note[] = [];
  632. subnotelist.push(this.currentNote);
  633. tuplet.Notes.push(subnotelist);
  634. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  635. this.currentNote.NoteTuplet = tuplet;
  636. delete this.tupletDict[tupletNumber];
  637. if (Object.keys(this.tupletDict).length === 0) {
  638. this.openTupletNumber = 0;
  639. } else if (Object.keys(this.tupletDict).length > 1) {
  640. this.openTupletNumber--;
  641. }
  642. }
  643. }
  644. }
  645. }
  646. } else if (tupletNodeList[0] !== undefined) {
  647. let n: IXmlElement = tupletNodeList[0];
  648. if (n.hasAttributes) {
  649. let type: string = n.attribute("type").value;
  650. let tupletnumber: number = 1;
  651. if (n.attribute("number")) {
  652. tupletnumber = parseInt(n.attribute("number").value, 10);
  653. }
  654. let noTupletNumbering: boolean = isNaN(tupletnumber);
  655. if (type === "start") {
  656. let tupletLabelNumber: number = 0;
  657. let timeModNode: IXmlElement = node.element("time-modification");
  658. if (timeModNode !== undefined) {
  659. timeModNode = timeModNode.element("actual-notes");
  660. }
  661. if (timeModNode !== undefined) {
  662. tupletLabelNumber = parseInt(timeModNode.value, 10);
  663. if (isNaN(tupletLabelNumber)) {
  664. let errorMsg: string = ITextTranslation.translateText(
  665. "ReaderErrorMessages/TupletNoteDurationError", "Invalid tuplet note duration."
  666. );
  667. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  668. throw new MusicSheetReadingException(errorMsg);
  669. }
  670. }
  671. if (noTupletNumbering) {
  672. this.openTupletNumber++;
  673. tupletnumber = this.openTupletNumber;
  674. }
  675. let tuplet: Tuplet = this.tupletDict[tupletnumber];
  676. if (tuplet === undefined) {
  677. tuplet = this.tupletDict[tupletnumber] = new Tuplet(tupletLabelNumber);
  678. }
  679. let subnotelist: Note[] = [];
  680. subnotelist.push(this.currentNote);
  681. tuplet.Notes.push(subnotelist);
  682. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  683. this.currentNote.NoteTuplet = tuplet;
  684. this.openTupletNumber = tupletnumber;
  685. } else if (type === "stop") {
  686. if (noTupletNumbering) {
  687. tupletnumber = this.openTupletNumber;
  688. }
  689. let tuplet: Tuplet = this.tupletDict[this.openTupletNumber];
  690. if (tuplet !== undefined) {
  691. let subnotelist: Note[] = [];
  692. subnotelist.push(this.currentNote);
  693. tuplet.Notes.push(subnotelist);
  694. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  695. this.currentNote.NoteTuplet = tuplet;
  696. if (Object.keys(this.tupletDict).length === 0) {
  697. this.openTupletNumber = 0;
  698. } else if (Object.keys(this.tupletDict).length > 1) {
  699. this.openTupletNumber--;
  700. }
  701. delete this.tupletDict[tupletnumber];
  702. }
  703. }
  704. }
  705. }
  706. return this.openTupletNumber;
  707. }
  708. /**
  709. * Handle the time-modification [[IXmlElement]] for the [[Tuplet]] case (tupletNotes not at begin/end of [[Tuplet]]).
  710. * @param noteNode
  711. */
  712. private handleTimeModificationNode(noteNode: IXmlElement): void {
  713. if (this.openTupletNumber in this.tupletDict) {
  714. try {
  715. let tuplet: Tuplet = this.tupletDict[this.openTupletNumber];
  716. let notes: Note[] = CollectionUtil.last(tuplet.Notes);
  717. let lastTupletVoiceEntry: VoiceEntry = notes[0].ParentVoiceEntry;
  718. let noteList: Note[];
  719. if (lastTupletVoiceEntry.Timestamp.Equals(this.currentVoiceEntry.Timestamp)) {
  720. noteList = notes;
  721. } else {
  722. noteList = [];
  723. tuplet.Notes.push(noteList);
  724. tuplet.Fractions.push(this.getTupletNoteDurationFromType(noteNode));
  725. }
  726. noteList.push(this.currentNote);
  727. this.currentNote.NoteTuplet = tuplet;
  728. } catch (ex) {
  729. let errorMsg: string = ITextTranslation.translateText(
  730. "ReaderErrorMessages/TupletNumberError", "Invalid tuplet number."
  731. );
  732. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  733. throw ex;
  734. }
  735. } else if (this.currentVoiceEntry.Notes.length > 0) {
  736. let firstNote: Note = this.currentVoiceEntry.Notes[0];
  737. if (firstNote.NoteTuplet !== undefined) {
  738. let tuplet: Tuplet = firstNote.NoteTuplet;
  739. let notes: Note[] = CollectionUtil.last(tuplet.Notes);
  740. notes.push(this.currentNote);
  741. this.currentNote.NoteTuplet = tuplet;
  742. }
  743. }
  744. }
  745. private addTie(tieNodeList: IXmlElement[], measureStartAbsoluteTimestamp: Fraction, maxTieNoteFraction: Fraction): void {
  746. if (tieNodeList !== undefined) {
  747. if (tieNodeList.length === 1) {
  748. let tieNode: IXmlElement = tieNodeList[0];
  749. if (tieNode !== undefined && tieNode.attributes()) {
  750. let type: string = tieNode.attribute("type").value;
  751. try {
  752. if (type === "start") {
  753. let num: number = this.findCurrentNoteInTieDict(this.currentNote);
  754. if (num < 0) {
  755. delete this.openTieDict[num];
  756. }
  757. let newTieNumber: number = this.getNextAvailableNumberForTie();
  758. let tie: Tie = new Tie(this.currentNote);
  759. this.openTieDict[newTieNumber] = tie;
  760. if (this.currentNote.NoteBeam !== undefined) {
  761. if (this.currentNote.NoteBeam.Notes[0] === this.currentNote) {
  762. tie.BeamStartTimestamp = Fraction.plus(measureStartAbsoluteTimestamp, this.currentVoiceEntry.Timestamp);
  763. } else {
  764. for (let idx: number = 0, len: number = this.currentNote.NoteBeam.Notes.length; idx < len; ++idx) {
  765. let note: Note = this.currentNote.NoteBeam.Notes[idx];
  766. if (note.NoteTie !== undefined && note.NoteTie !== tie && note.NoteTie.BeamStartTimestamp !== undefined) {
  767. tie.BeamStartTimestamp = note.NoteTie.BeamStartTimestamp;
  768. break;
  769. }
  770. }
  771. if (this.currentNote === CollectionUtil.last(this.currentNote.NoteBeam.Notes)) {
  772. tie.BeamStartTimestamp = Fraction.plus(measureStartAbsoluteTimestamp, this.currentVoiceEntry.Timestamp);
  773. }
  774. }
  775. }
  776. } else if (type === "stop") {
  777. let tieNumber: number = this.findCurrentNoteInTieDict(this.currentNote);
  778. let tie: Tie = this.openTieDict[tieNumber];
  779. if (tie !== undefined) {
  780. let tieStartNote: Note = tie.Start;
  781. tieStartNote.NoteTie = tie;
  782. tieStartNote.Length.Add(this.currentNote.Length);
  783. tie.Fractions.push(this.currentNote.Length);
  784. if (maxTieNoteFraction.lt(Fraction.plus(this.currentStaffEntry.Timestamp, this.currentNote.Length))) {
  785. maxTieNoteFraction = Fraction.plus(this.currentStaffEntry.Timestamp, this.currentNote.Length);
  786. }
  787. let i: number = this.currentVoiceEntry.Notes.indexOf(this.currentNote);
  788. if (i !== -1) { this.currentVoiceEntry.Notes.splice(i, 1); }
  789. if (
  790. this.currentVoiceEntry.Articulations.length === 1
  791. && this.currentVoiceEntry.Articulations[0] === ArticulationEnum.fermata
  792. && tieStartNote.ParentVoiceEntry.Articulations[ArticulationEnum.fermata] === undefined
  793. ) {
  794. tieStartNote.ParentVoiceEntry.Articulations.push(ArticulationEnum.fermata);
  795. }
  796. if (this.currentNote.NoteBeam !== undefined) {
  797. let noteBeamIndex: number = this.currentNote.NoteBeam.Notes.indexOf(this.currentNote);
  798. if (noteBeamIndex === 0 && tie.BeamStartTimestamp === undefined) {
  799. tie.BeamStartTimestamp = Fraction.plus(measureStartAbsoluteTimestamp, this.currentVoiceEntry.Timestamp);
  800. }
  801. let noteBeam: Beam = this.currentNote.NoteBeam;
  802. noteBeam.Notes[noteBeamIndex] = tieStartNote;
  803. tie.TieBeam = noteBeam;
  804. }
  805. if (this.currentNote.NoteTuplet !== undefined) {
  806. let noteTupletIndex: number = this.currentNote.NoteTuplet.getNoteIndex(this.currentNote);
  807. let index: number = this.currentNote.NoteTuplet.Notes[noteTupletIndex].indexOf(this.currentNote);
  808. let noteTuplet: Tuplet = this.currentNote.NoteTuplet;
  809. noteTuplet.Notes[noteTupletIndex][index] = tieStartNote;
  810. tie.TieTuplet = noteTuplet;
  811. }
  812. for (let idx: number = 0, len: number = this.currentNote.NoteSlurs.length; idx < len; ++idx) {
  813. let slur: Slur = this.currentNote.NoteSlurs[idx];
  814. if (slur.StartNote === this.currentNote) {
  815. slur.StartNote = tie.Start;
  816. slur.StartNote.NoteSlurs.push(slur);
  817. }
  818. if (slur.EndNote === this.currentNote) {
  819. slur.EndNote = tie.Start;
  820. slur.EndNote.NoteSlurs.push(slur);
  821. }
  822. }
  823. let lyricsEntries: Dictionary<number, LyricsEntry> = this.currentVoiceEntry.LyricsEntries;
  824. for (let lyricsEntry in lyricsEntries) {
  825. if (lyricsEntries.hasOwnProperty(lyricsEntry)) {
  826. let val: LyricsEntry = this.currentVoiceEntry.LyricsEntries[lyricsEntry];
  827. if (!tieStartNote.ParentVoiceEntry.LyricsEntries.hasOwnProperty(lyricsEntry)) {
  828. tieStartNote.ParentVoiceEntry.LyricsEntries[lyricsEntry] = val;
  829. val.Parent = tieStartNote.ParentVoiceEntry;
  830. }
  831. }
  832. }
  833. delete this.openTieDict[tieNumber];
  834. }
  835. }
  836. } catch (err) {
  837. let errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/TieError", "Error while reading tie.");
  838. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  839. }
  840. }
  841. } else if (tieNodeList.length === 2) {
  842. let tieNumber: number = this.findCurrentNoteInTieDict(this.currentNote);
  843. if (tieNumber >= 0) {
  844. let tie: Tie = this.openTieDict[tieNumber];
  845. let tieStartNote: Note = tie.Start;
  846. tieStartNote.Length.Add(this.currentNote.Length);
  847. tie.Fractions.push(this.currentNote.Length);
  848. if (this.currentNote.NoteBeam !== undefined) {
  849. let noteBeamIndex: number = this.currentNote.NoteBeam.Notes.indexOf(this.currentNote);
  850. if (noteBeamIndex === 0 && tie.BeamStartTimestamp === undefined) {
  851. tie.BeamStartTimestamp = Fraction.plus(measureStartAbsoluteTimestamp, this.currentVoiceEntry.Timestamp);
  852. }
  853. let noteBeam: Beam = this.currentNote.NoteBeam;
  854. noteBeam.Notes[noteBeamIndex] = tieStartNote;
  855. tie.TieBeam = noteBeam;
  856. }
  857. for (let idx: number = 0, len: number = this.currentNote.NoteSlurs.length; idx < len; ++idx) {
  858. let slur: Slur = this.currentNote.NoteSlurs[idx];
  859. if (slur.StartNote === this.currentNote) {
  860. slur.StartNote = tie.Start;
  861. slur.StartNote.NoteSlurs.push(slur);
  862. }
  863. if (slur.EndNote === this.currentNote) {
  864. slur.EndNote = tie.Start;
  865. slur.EndNote.NoteSlurs.push(slur);
  866. }
  867. }
  868. this.currentVoiceEntry.LyricsEntries.forEach((key: number, value: LyricsEntry): void => {
  869. if (!tieStartNote.ParentVoiceEntry.LyricsEntries.containsKey(key)) {
  870. tieStartNote.ParentVoiceEntry.LyricsEntries.setValue(key, value);
  871. value.Parent = tieStartNote.ParentVoiceEntry;
  872. }
  873. });
  874. if (maxTieNoteFraction.lt(Fraction.plus(this.currentStaffEntry.Timestamp, this.currentNote.Length))) {
  875. maxTieNoteFraction = Fraction.plus(this.currentStaffEntry.Timestamp, this.currentNote.Length);
  876. }
  877. // delete currentNote from Notes:
  878. let i: number = this.currentVoiceEntry.Notes.indexOf(this.currentNote);
  879. if (i !== -1) { this.currentVoiceEntry.Notes.splice(i, 1); }
  880. }
  881. }
  882. }
  883. }
  884. /**
  885. * Find the next free int (starting from 0) to use as key in TieDict.
  886. * @returns {number}
  887. */
  888. private getNextAvailableNumberForTie(): number {
  889. let keys: string[] = Object.keys(this.openTieDict);
  890. if (keys.length === 0) { return 1; }
  891. keys.sort((a, b) => (+a - +b)); // FIXME Andrea: test
  892. for (let i: number = 0; i < keys.length; i++) {
  893. if ("" + (i + 1) !== keys[i]) {
  894. return i + 1;
  895. }
  896. }
  897. return +(keys[keys.length - 1]) + 1;
  898. }
  899. /**
  900. * Search the tieDictionary for the corresponding candidateNote to the currentNote (same FundamentalNote && Octave).
  901. * @param candidateNote
  902. * @returns {number}
  903. */
  904. private findCurrentNoteInTieDict(candidateNote: Note): number {
  905. let openTieDict: { [_: number]: Tie; } = this.openTieDict;
  906. for (let key in openTieDict) {
  907. if (openTieDict.hasOwnProperty(key)) {
  908. let tie: Tie = openTieDict[key];
  909. if (tie.Start.Pitch.FundamentalNote === candidateNote.Pitch.FundamentalNote && tie.Start.Pitch.Octave === candidateNote.Pitch.Octave) {
  910. return +key;
  911. }
  912. }
  913. }
  914. return -1;
  915. }
  916. /**
  917. * Calculate the normal duration of a [[Tuplet]] note.
  918. * @param xmlNode
  919. * @returns {any}
  920. */
  921. private getTupletNoteDurationFromType(xmlNode: IXmlElement): Fraction {
  922. if (xmlNode.element("type") !== undefined) {
  923. let typeNode: IXmlElement = xmlNode.element("type");
  924. if (typeNode !== undefined) {
  925. let type: string = typeNode.value;
  926. try {
  927. return this.getNoteDurationFromType(type);
  928. } catch (e) {
  929. let errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/NoteDurationError", "Invalid note duration.");
  930. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  931. throw new MusicSheetReadingException("", e);
  932. }
  933. }
  934. }
  935. return undefined;
  936. }
  937. }