VoiceGenerator.ts 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. import { LinkedVoice } from "../VoiceData/LinkedVoice";
  2. import { Voice } from "../VoiceData/Voice";
  3. import { MusicSheet } from "../MusicSheet";
  4. import { VoiceEntry, StemDirectionType } from "../VoiceData/VoiceEntry";
  5. import { Note } from "../VoiceData/Note";
  6. import { SourceMeasure } from "../VoiceData/SourceMeasure";
  7. import { SourceStaffEntry } from "../VoiceData/SourceStaffEntry";
  8. import { Beam } from "../VoiceData/Beam";
  9. import { Tie } from "../VoiceData/Tie";
  10. import { TieTypes } from "../../Common/Enums/";
  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 log from "loglevel";
  23. import { Pitch } from "../../Common/DataObjects/Pitch";
  24. import { IXmlAttribute } from "../../Common/FileIO/Xml";
  25. import { CollectionUtil } from "../../Util/CollectionUtil";
  26. import { ArticulationReader } from "./MusicSymbolModules/ArticulationReader";
  27. import { SlurReader } from "./MusicSymbolModules/SlurReader";
  28. import { Notehead } from "../VoiceData/Notehead";
  29. import { Arpeggio, ArpeggioType } from "../VoiceData/Arpeggio";
  30. import { NoteType, NoteTypeHandler } from "../VoiceData/NoteType";
  31. import { TabNote } from "../VoiceData/TabNote";
  32. import { PlacementEnum } from "../VoiceData/Expressions/AbstractExpression";
  33. import { KeyInstruction, RhythmInstruction } from "../VoiceData/Instructions";
  34. import { ReaderPluginManager } from "./ReaderPluginManager";
  35. import { Instrument } from "../Instrument";
  36. export class VoiceGenerator {
  37. constructor(pluginManager: ReaderPluginManager, staff: Staff, voiceId: number, slurReader: SlurReader, mainVoice: Voice = undefined) {
  38. this.staff = staff;
  39. this.instrument = staff.ParentInstrument;
  40. this.musicSheet = this.instrument.GetMusicSheet;
  41. this.slurReader = slurReader;
  42. this.pluginManager = pluginManager;
  43. if (mainVoice) {
  44. this.voice = new LinkedVoice(this.instrument, voiceId, mainVoice);
  45. } else {
  46. this.voice = new Voice(this.instrument, voiceId);
  47. }
  48. this.instrument.Voices.push(this.voice); // apparently necessary for cursor.next(), for "cursor with hidden instrument" test
  49. this.staff.Voices.push(this.voice);
  50. this.lyricsReader = new LyricsReader(this.musicSheet);
  51. this.articulationReader = new ArticulationReader(this.musicSheet.Rules);
  52. }
  53. public pluginManager: ReaderPluginManager; // currently only used in audio player
  54. private slurReader: SlurReader;
  55. private lyricsReader: LyricsReader;
  56. private articulationReader: ArticulationReader;
  57. private musicSheet: MusicSheet;
  58. private voice: Voice;
  59. private currentVoiceEntry: VoiceEntry;
  60. private currentNormalVoiceEntry: VoiceEntry;
  61. private currentNote: Note;
  62. private activeKey: KeyInstruction;
  63. private activeRhythm: RhythmInstruction;
  64. private currentMeasure: SourceMeasure;
  65. private currentStaffEntry: SourceStaffEntry;
  66. private staff: Staff;
  67. private instrument: Instrument;
  68. // private lastBeamTag: string = "";
  69. private openBeams: Beam[] = []; // works like a stack, with push and pop
  70. private beamNumberOffset: number = 0;
  71. private openTieDict: { [_: number]: Tie } = {};
  72. private currentOctaveShift: number = 0;
  73. private tupletDict: { [_: number]: Tuplet } = {};
  74. private openTupletNumber: number = 0;
  75. private currMeasureVoiceEntries: VoiceEntry[] = [];
  76. private graceVoiceEntriesTempList: VoiceEntry[] = [];
  77. public get GetVoice(): Voice {
  78. return this.voice;
  79. }
  80. public get OctaveShift(): number {
  81. return this.currentOctaveShift;
  82. }
  83. public set OctaveShift(value: number) {
  84. this.currentOctaveShift = value;
  85. }
  86. /**
  87. * Create new [[VoiceEntry]], add it to given [[SourceStaffEntry]] and if given so, to [[Voice]].
  88. * @param musicTimestamp
  89. * @param parentStaffEntry
  90. * @param addToVoice
  91. * @param isGrace States whether the new VoiceEntry (only) has grace notes
  92. */
  93. public createVoiceEntry(musicTimestamp: Fraction, parentStaffEntry: SourceStaffEntry, activeKey: KeyInstruction, activeRhythm: RhythmInstruction,
  94. isGrace: boolean = false, hasGraceSlash: boolean = false, graceSlur: boolean = false): void {
  95. this.activeKey = activeKey;
  96. this.activeRhythm = activeRhythm;
  97. this.currentVoiceEntry = new VoiceEntry(Fraction.createFromFraction(musicTimestamp), this.voice, parentStaffEntry, true, isGrace, hasGraceSlash, graceSlur);
  98. if (isGrace) {
  99. // if grace voice entry, add to temp list
  100. this.graceVoiceEntriesTempList.push(this.currentVoiceEntry);
  101. } else {
  102. // remember new main VE -> needed for grace voice entries
  103. this.currentNormalVoiceEntry = this.currentVoiceEntry;
  104. // add ve to list of voice entries of this measure:
  105. this.currMeasureVoiceEntries.push(this.currentNormalVoiceEntry);
  106. // add grace VE temp list to normal voice entry:
  107. if (this.graceVoiceEntriesTempList.length > 0) {
  108. this.currentVoiceEntry.GraceVoiceEntriesBefore = this.graceVoiceEntriesTempList;
  109. this.graceVoiceEntriesTempList = [];
  110. }
  111. }
  112. }
  113. public finalizeReadingMeasure(): void {
  114. // store floating grace notes, if any:
  115. if (this.graceVoiceEntriesTempList.length > 0 &&
  116. this.currentNormalVoiceEntry !== undefined) {
  117. this.currentNormalVoiceEntry.GraceVoiceEntriesAfter.concat(this.graceVoiceEntriesTempList);
  118. }
  119. this.graceVoiceEntriesTempList = [];
  120. this.pluginManager.processVoiceMeasureReadPlugins(this.currMeasureVoiceEntries, this.activeKey, this.activeRhythm);
  121. this.currMeasureVoiceEntries.length = 0;
  122. // possibly (eventuell) close an already opened beam:
  123. if (this.openBeams.length > 1) {
  124. this.handleOpenBeam();
  125. }
  126. }
  127. /**
  128. * Create [[Note]]s and handle Lyrics, Articulations, Beams, Ties, Slurs, Tuplets.
  129. * @param noteNode
  130. * @param noteDuration
  131. * @param divisions
  132. * @param restNote
  133. * @param parentStaffEntry
  134. * @param parentMeasure
  135. * @param measureStartAbsoluteTimestamp
  136. * @param maxTieNoteFraction
  137. * @param chord
  138. * @param octavePlusOne Software like Guitar Pro gives one octave too low, so we need to add one
  139. * @param printObject whether the note should be rendered (true) or invisible (false)
  140. * @returns {Note}
  141. */
  142. public read(noteNode: IXmlElement, noteDuration: Fraction, typeDuration: Fraction, noteTypeXml: NoteType, normalNotes: number, restNote: boolean,
  143. parentStaffEntry: SourceStaffEntry, parentMeasure: SourceMeasure,
  144. measureStartAbsoluteTimestamp: Fraction, maxTieNoteFraction: Fraction, chord: boolean, octavePlusOne: boolean,
  145. printObject: boolean, isCueNote: boolean, isGraceNote: boolean, stemDirectionXml: StemDirectionType, tremoloStrokes: number,
  146. stemColorXml: string, noteheadColorXml: string, vibratoStrokes: boolean): Note {
  147. this.currentStaffEntry = parentStaffEntry;
  148. this.currentMeasure = parentMeasure;
  149. //log.debug("read called:", restNote);
  150. try {
  151. this.currentNote = restNote
  152. ? this.addRestNote(noteNode.element("rest"), noteDuration, noteTypeXml, normalNotes, printObject, isCueNote, noteheadColorXml)
  153. : this.addSingleNote(noteNode, noteDuration, noteTypeXml, typeDuration, normalNotes, chord, octavePlusOne,
  154. printObject, isCueNote, isGraceNote, stemDirectionXml, tremoloStrokes, stemColorXml, noteheadColorXml, vibratoStrokes);
  155. // read lyrics
  156. const lyricElements: IXmlElement[] = noteNode.elements("lyric");
  157. if (this.lyricsReader !== undefined && lyricElements) {
  158. this.lyricsReader.addLyricEntry(lyricElements, this.currentVoiceEntry);
  159. this.voice.Parent.HasLyrics = true;
  160. }
  161. let hasTupletCommand: boolean = false;
  162. const notationNode: IXmlElement = noteNode.element("notations");
  163. if (notationNode) {
  164. // read articulations
  165. if (this.articulationReader) {
  166. this.readArticulations(notationNode, this.currentVoiceEntry, this.currentNote);
  167. }
  168. // read slurs
  169. const slurElements: IXmlElement[] = notationNode.elements("slur");
  170. if (this.slurReader !== undefined &&
  171. slurElements.length > 0 &&
  172. !this.currentNote.ParentVoiceEntry.IsGrace) {
  173. this.slurReader.addSlur(slurElements, this.currentNote);
  174. }
  175. // read Tuplets
  176. const tupletElements: IXmlElement[] = notationNode.elements("tuplet");
  177. if (tupletElements.length > 0) {
  178. this.openTupletNumber = this.addTuplet(noteNode, tupletElements);
  179. hasTupletCommand = true;
  180. }
  181. // check for Arpeggios
  182. const arpeggioNode: IXmlElement = notationNode.element("arpeggiate");
  183. if (arpeggioNode !== undefined) {
  184. let currentArpeggio: Arpeggio;
  185. if (this.currentVoiceEntry.Arpeggio) { // add note to existing Arpeggio
  186. currentArpeggio = this.currentVoiceEntry.Arpeggio;
  187. } else { // create new Arpeggio
  188. let arpeggioAlreadyExists: boolean = false;
  189. for (const voiceEntry of this.currentStaffEntry.VoiceEntries) {
  190. if (voiceEntry.Arpeggio) {
  191. arpeggioAlreadyExists = true;
  192. currentArpeggio = voiceEntry.Arpeggio;
  193. // TODO handle multiple arpeggios across multiple voices at same timestamp
  194. // this.currentVoiceEntry.Arpeggio = currentArpeggio; // register the arpeggio in the current voice entry as well?
  195. // but then we duplicate information, and may have to take care not to render it multiple times
  196. // we already have an arpeggio in another voice, at the current timestamp. add the notes there.
  197. break;
  198. }
  199. }
  200. if (!arpeggioAlreadyExists) {
  201. let arpeggioType: ArpeggioType = ArpeggioType.ARPEGGIO_DIRECTIONLESS;
  202. const directionAttr: Attr = arpeggioNode.attribute("direction");
  203. if (directionAttr) {
  204. switch (directionAttr.value) {
  205. case "up":
  206. arpeggioType = ArpeggioType.ROLL_UP;
  207. break;
  208. case "down":
  209. arpeggioType = ArpeggioType.ROLL_DOWN;
  210. break;
  211. default:
  212. arpeggioType = ArpeggioType.ARPEGGIO_DIRECTIONLESS;
  213. }
  214. }
  215. currentArpeggio = new Arpeggio(this.currentVoiceEntry, arpeggioType);
  216. this.currentVoiceEntry.Arpeggio = currentArpeggio;
  217. }
  218. }
  219. currentArpeggio.addNote(this.currentNote);
  220. }
  221. // check for Ties - must be the last check
  222. const tiedNodeList: IXmlElement[] = notationNode.elements("tied");
  223. if (tiedNodeList.length > 0) {
  224. this.addTie(tiedNodeList, measureStartAbsoluteTimestamp, maxTieNoteFraction, TieTypes.SIMPLE);
  225. }
  226. //check for slides, they are the same as Ties but with a different connection
  227. const slideNodeList: IXmlElement[] = notationNode.elements("slide");
  228. if (slideNodeList.length > 0) {
  229. this.addTie(slideNodeList, measureStartAbsoluteTimestamp, maxTieNoteFraction, TieTypes.SLIDE);
  230. }
  231. //check for guitar specific symbols:
  232. const technicalNode: IXmlElement = notationNode.element("technical");
  233. if (technicalNode) {
  234. const hammerNodeList: IXmlElement[] = technicalNode.elements("hammer-on");
  235. if (hammerNodeList.length > 0) {
  236. this.addTie(hammerNodeList, measureStartAbsoluteTimestamp, maxTieNoteFraction, TieTypes.HAMMERON);
  237. }
  238. const pulloffNodeList: IXmlElement[] = technicalNode.elements("pull-off");
  239. if (pulloffNodeList.length > 0) {
  240. this.addTie(pulloffNodeList, measureStartAbsoluteTimestamp, maxTieNoteFraction, TieTypes.PULLOFF);
  241. }
  242. }
  243. // remove open ties, if there is already a gap between the last tie note and now.
  244. const openTieDict: { [_: number]: Tie } = this.openTieDict;
  245. for (const key in openTieDict) {
  246. if (openTieDict.hasOwnProperty(key)) {
  247. const tie: Tie = openTieDict[key];
  248. if (Fraction.plus(tie.StartNote.ParentStaffEntry.Timestamp, tie.Duration).lt(this.currentStaffEntry.Timestamp)) {
  249. delete openTieDict[key];
  250. }
  251. }
  252. }
  253. }
  254. // time-modification yields tuplet in currentNote
  255. // mustn't execute method, if this is the Note where the Tuplet has been created
  256. if (noteNode.element("time-modification") !== undefined && !hasTupletCommand) {
  257. this.handleTimeModificationNode(noteNode);
  258. }
  259. } catch (err) {
  260. const errorMsg: string = ITextTranslation.translateText(
  261. "ReaderErrorMessages/NoteError", "Ignored erroneous Note."
  262. );
  263. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  264. }
  265. return this.currentNote;
  266. }
  267. /**
  268. * Create a new [[StaffEntryLink]] and sets the currenstStaffEntry accordingly.
  269. * @param index
  270. * @param currentStaff
  271. * @param currentStaffEntry
  272. * @param currentMeasure
  273. * @returns {SourceStaffEntry}
  274. */
  275. public checkForStaffEntryLink(index: number, currentStaff: Staff, currentStaffEntry: SourceStaffEntry, currentMeasure: SourceMeasure): SourceStaffEntry {
  276. const staffEntryLink: StaffEntryLink = new StaffEntryLink(this.currentVoiceEntry);
  277. staffEntryLink.LinkStaffEntries.push(currentStaffEntry);
  278. currentStaffEntry.Link = staffEntryLink;
  279. const linkMusicTimestamp: Fraction = this.currentVoiceEntry.Timestamp.clone();
  280. const verticalSourceStaffEntryContainer: VerticalSourceStaffEntryContainer = currentMeasure.getVerticalContainerByTimestamp(linkMusicTimestamp);
  281. currentStaffEntry = verticalSourceStaffEntryContainer.StaffEntries[index];
  282. if (!currentStaffEntry) {
  283. currentStaffEntry = new SourceStaffEntry(verticalSourceStaffEntryContainer, currentStaff);
  284. verticalSourceStaffEntryContainer.StaffEntries[index] = currentStaffEntry;
  285. }
  286. currentStaffEntry.VoiceEntries.push(this.currentVoiceEntry);
  287. staffEntryLink.LinkStaffEntries.push(currentStaffEntry);
  288. currentStaffEntry.Link = staffEntryLink;
  289. return currentStaffEntry;
  290. }
  291. public checkForOpenBeam(): void {
  292. if (this.openBeams.length > 0 && this.currentNote) {
  293. this.handleOpenBeam();
  294. }
  295. }
  296. public checkOpenTies(): void {
  297. const openTieDict: { [key: number]: Tie } = this.openTieDict;
  298. for (const key in openTieDict) {
  299. if (openTieDict.hasOwnProperty(key)) {
  300. const tie: Tie = openTieDict[key];
  301. if (Fraction.plus(tie.StartNote.ParentStaffEntry.Timestamp, tie.Duration)
  302. .lt(tie.StartNote.SourceMeasure.Duration)) {
  303. delete openTieDict[key];
  304. }
  305. }
  306. }
  307. }
  308. public hasVoiceEntry(): boolean {
  309. return this.currentVoiceEntry !== undefined;
  310. }
  311. private readArticulations(notationNode: IXmlElement, currentVoiceEntry: VoiceEntry, currentNote: Note): void {
  312. const articNode: IXmlElement = notationNode.element("articulations");
  313. if (articNode) {
  314. this.articulationReader.addArticulationExpression(articNode, currentVoiceEntry);
  315. }
  316. const fermaNode: IXmlElement = notationNode.element("fermata");
  317. if (fermaNode) {
  318. this.articulationReader.addFermata(fermaNode, currentVoiceEntry);
  319. }
  320. const tecNode: IXmlElement = notationNode.element("technical");
  321. if (tecNode) {
  322. this.articulationReader.addTechnicalArticulations(tecNode, currentVoiceEntry, currentNote);
  323. }
  324. const ornaNode: IXmlElement = notationNode.element("ornaments");
  325. if (ornaNode) {
  326. this.articulationReader.addOrnament(ornaNode, currentVoiceEntry);
  327. // const tremoloNode: IXmlElement = ornaNode.element("tremolo");
  328. // tremolo should be and is added per note, not per VoiceEntry. see addSingleNote()
  329. }
  330. }
  331. /**
  332. * Create a new [[Note]] and adds it to the currentVoiceEntry
  333. * @param node
  334. * @param noteDuration
  335. * @param divisions
  336. * @param chord
  337. * @param octavePlusOne Software like Guitar Pro gives one octave too low, so we need to add one
  338. * @returns {Note}
  339. */
  340. private addSingleNote(node: IXmlElement, noteDuration: Fraction, noteTypeXml: NoteType, typeDuration: Fraction,
  341. normalNotes: number, chord: boolean, octavePlusOne: boolean,
  342. printObject: boolean, isCueNote: boolean, isGraceNote: boolean, stemDirectionXml: StemDirectionType, tremoloStrokes: number,
  343. stemColorXml: string, noteheadColorXml: string, vibratoStrokes: boolean): Note {
  344. //log.debug("addSingleNote called");
  345. let noteAlter: number = 0;
  346. let noteAccidental: AccidentalEnum = AccidentalEnum.NONE;
  347. let noteStep: NoteEnum = NoteEnum.C;
  348. let displayStepUnpitched: NoteEnum = NoteEnum.C;
  349. let noteOctave: number = 0;
  350. let displayOctaveUnpitched: number = 0;
  351. let playbackInstrumentId: string = undefined;
  352. let noteheadShapeXml: string = undefined;
  353. let noteheadFilledXml: boolean = undefined; // if undefined, the final filled parameter will be calculated from duration
  354. const xmlnodeElementsArr: IXmlElement[] = node.elements();
  355. for (let idx: number = 0, len: number = xmlnodeElementsArr.length; idx < len; ++idx) {
  356. const noteElement: IXmlElement = xmlnodeElementsArr[idx];
  357. try {
  358. if (noteElement.name === "pitch") {
  359. const noteElementsArr: IXmlElement[] = noteElement.elements();
  360. for (let idx2: number = 0, len2: number = noteElementsArr.length; idx2 < len2; ++idx2) {
  361. const pitchElement: IXmlElement = noteElementsArr[idx2];
  362. noteheadShapeXml = undefined; // reinitialize for each pitch
  363. noteheadFilledXml = undefined;
  364. try {
  365. if (pitchElement.name === "step") {
  366. noteStep = NoteEnum[pitchElement.value];
  367. if (noteStep === undefined) { // don't replace undefined check
  368. const errorMsg: string = ITextTranslation.translateText(
  369. "ReaderErrorMessages/NotePitchError",
  370. "Invalid pitch while reading note."
  371. );
  372. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  373. throw new MusicSheetReadingException(errorMsg, undefined);
  374. }
  375. } else if (pitchElement.name === "alter") {
  376. noteAlter = parseFloat(pitchElement.value);
  377. if (isNaN(noteAlter)) {
  378. const errorMsg: string = ITextTranslation.translateText(
  379. "ReaderErrorMessages/NoteAlterationError", "Invalid alteration while reading note."
  380. );
  381. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  382. throw new MusicSheetReadingException(errorMsg, undefined);
  383. }
  384. noteAccidental = Pitch.AccidentalFromHalfTones(noteAlter); // potentially overwritten by "accidental" noteElement
  385. } else if (pitchElement.name === "octave") {
  386. noteOctave = parseInt(pitchElement.value, 10);
  387. if (isNaN(noteOctave)) {
  388. const errorMsg: string = ITextTranslation.translateText(
  389. "ReaderErrorMessages/NoteOctaveError", "Invalid octave value while reading note."
  390. );
  391. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  392. throw new MusicSheetReadingException(errorMsg, undefined);
  393. }
  394. }
  395. } catch (ex) {
  396. log.info("VoiceGenerator.addSingleNote read Step: ", ex.message);
  397. }
  398. }
  399. } else if (noteElement.name === "accidental") {
  400. const accidentalValue: string = noteElement.value;
  401. if (accidentalValue === "natural") {
  402. noteAccidental = AccidentalEnum.NATURAL;
  403. }
  404. } else if (noteElement.name === "unpitched") {
  405. const displayStepElement: IXmlElement = noteElement.element("display-step");
  406. const octave: IXmlElement = noteElement.element("display-octave");
  407. if (octave) {
  408. noteOctave = parseInt(octave.value, 10);
  409. displayOctaveUnpitched = noteOctave - 3;
  410. if (octavePlusOne) {
  411. noteOctave += 1;
  412. }
  413. if (this.instrument.Staves[0].StafflineCount === 1) {
  414. displayOctaveUnpitched += 1;
  415. }
  416. }
  417. if (displayStepElement) {
  418. noteStep = NoteEnum[displayStepElement.value.toUpperCase()];
  419. let octaveShift: number = 0;
  420. let noteValueShift: number = this.musicSheet.Rules.PercussionXMLDisplayStepNoteValueShift;
  421. if (this.instrument.Staves[0].StafflineCount === 1) {
  422. noteValueShift -= 3; // for percussion one line scores, we need to set the notes 3 lines lower
  423. }
  424. [displayStepUnpitched, octaveShift] = Pitch.lineShiftFromNoteEnum(noteStep, noteValueShift);
  425. displayOctaveUnpitched += octaveShift;
  426. }
  427. } else if (noteElement.name === "instrument") {
  428. if (noteElement.firstAttribute) {
  429. playbackInstrumentId = noteElement.firstAttribute.value;
  430. }
  431. } else if (noteElement.name === "notehead") {
  432. noteheadShapeXml = noteElement.value;
  433. if (noteElement.attribute("filled")) {
  434. noteheadFilledXml = noteElement.attribute("filled").value === "yes";
  435. }
  436. }
  437. } catch (ex) {
  438. log.info("VoiceGenerator.addSingleNote: ", ex);
  439. }
  440. }
  441. noteOctave -= Pitch.OctaveXmlDifference;
  442. const pitch: Pitch = new Pitch(noteStep, noteOctave, noteAccidental);
  443. const noteLength: Fraction = Fraction.createFromFraction(noteDuration);
  444. let note: Note = undefined;
  445. let stringNumber: number = -1;
  446. let fretNumber: number = -1;
  447. const bends: {bendalter: number, direction: string}[] = [];
  448. // check for guitar tabs:
  449. const notationNode: IXmlElement = node.element("notations");
  450. if (notationNode) {
  451. const technicalNode: IXmlElement = notationNode.element("technical");
  452. if (technicalNode) {
  453. const stringNode: IXmlElement = technicalNode.element("string");
  454. if (stringNode) {
  455. stringNumber = parseInt(stringNode.value, 10);
  456. }
  457. const fretNode: IXmlElement = technicalNode.element("fret");
  458. if (fretNode) {
  459. fretNumber = parseInt(fretNode.value, 10);
  460. }
  461. const bendElementsArr: IXmlElement[] = technicalNode.elements("bend");
  462. bendElementsArr.forEach(function (bend: IXmlElement): void {
  463. const bendalterNote: IXmlElement = bend.element("bend-alter");
  464. const releaseNode: IXmlElement = bend.element("release");
  465. if (releaseNode !== undefined) {
  466. bends.push({bendalter: parseInt (bendalterNote.value, 10), direction: "down"});
  467. } else {
  468. bends.push({bendalter: parseInt (bendalterNote.value, 10), direction: "up"});
  469. }
  470. });
  471. }
  472. }
  473. if (stringNumber < 0 || fretNumber < 0) {
  474. // create normal Note
  475. note = new Note(this.currentVoiceEntry, this.currentStaffEntry, noteLength, pitch, this.currentMeasure);
  476. } else {
  477. // create TabNote
  478. note = new TabNote(this.currentVoiceEntry, this.currentStaffEntry, noteLength, pitch, this.currentMeasure,
  479. stringNumber, fretNumber, bends, vibratoStrokes);
  480. }
  481. this.addNoteInfo(note, noteTypeXml, printObject, isCueNote, normalNotes,
  482. displayStepUnpitched, displayOctaveUnpitched,
  483. noteheadColorXml, noteheadColorXml);
  484. note.TypeLength = typeDuration;
  485. note.IsGraceNote = isGraceNote;
  486. note.StemDirectionXml = stemDirectionXml; // maybe unnecessary, also in VoiceEntry
  487. note.TremoloStrokes = tremoloStrokes; // could be a Tremolo object in future if we have more data to manage like two-note tremolo
  488. note.PlaybackInstrumentId = playbackInstrumentId;
  489. if ((noteheadShapeXml !== undefined && noteheadShapeXml !== "normal") || noteheadFilledXml !== undefined) {
  490. note.Notehead = new Notehead(note, noteheadShapeXml, noteheadFilledXml);
  491. } // if normal, leave note head undefined to save processing/runtime
  492. note.NoteheadColorXml = noteheadColorXml; // color set in Xml, shouldn't be changed.
  493. note.NoteheadColor = noteheadColorXml; // color currently used
  494. note.PlaybackInstrumentId = playbackInstrumentId;
  495. this.currentVoiceEntry.addNote(note);
  496. if (stemDirectionXml === StemDirectionType.None) {
  497. stemColorXml = "#00000000"; // just setting this to transparent for now
  498. }
  499. this.currentVoiceEntry.StemDirectionXml = stemDirectionXml;
  500. if (stemColorXml) {
  501. this.currentVoiceEntry.StemColorXml = stemColorXml;
  502. this.currentVoiceEntry.StemColor = stemColorXml;
  503. note.StemColorXml = stemColorXml;
  504. }
  505. if (node.elements("beam") && !chord) {
  506. this.createBeam(node, note);
  507. }
  508. return note;
  509. }
  510. /**
  511. * Create a new rest note and add it to the currentVoiceEntry.
  512. * @param noteDuration
  513. * @param divisions
  514. * @returns {Note}
  515. */
  516. private addRestNote(node: IXmlElement, noteDuration: Fraction, noteTypeXml: NoteType,
  517. normalNotes: number, printObject: boolean, isCueNote: boolean, noteheadColorXml: string): Note {
  518. const restFraction: Fraction = Fraction.createFromFraction(noteDuration);
  519. const displayStepElement: IXmlElement = node.element("display-step");
  520. const octaveElement: IXmlElement = node.element("display-octave");
  521. let displayStep: NoteEnum;
  522. let displayOctave: number;
  523. let pitch: Pitch = undefined;
  524. if (displayStepElement && octaveElement) {
  525. displayStep = NoteEnum[displayStepElement.value.toUpperCase()];
  526. displayOctave = parseInt(octaveElement.value, 10);
  527. pitch = new Pitch(displayStep, displayOctave, AccidentalEnum.NONE);
  528. }
  529. const restNote: Note = new Note(this.currentVoiceEntry, this.currentStaffEntry, restFraction, pitch, this.currentMeasure, true);
  530. this.addNoteInfo(restNote, noteTypeXml, printObject, isCueNote, normalNotes, displayStep, displayOctave, noteheadColorXml, noteheadColorXml);
  531. this.currentVoiceEntry.Notes.push(restNote);
  532. if (this.openBeams.length > 0) {
  533. this.openBeams.last().ExtendedNoteList.push(restNote);
  534. }
  535. return restNote;
  536. }
  537. // common for "normal" notes and rest notes
  538. private addNoteInfo(note: Note, noteTypeXml: NoteType, printObject: boolean, isCueNote: boolean, normalNotes: number,
  539. displayStep: NoteEnum, displayOctave: number,
  540. noteheadColorXml: string, noteheadColor: string): void {
  541. // common for normal notes and rest note
  542. note.NoteTypeXml = noteTypeXml;
  543. note.PrintObject = printObject;
  544. note.IsCueNote = isCueNote;
  545. note.NormalNotes = normalNotes; // how many rhythmical notes the notes replace (e.g. for tuplets), see xml "actual-notes" and "normal-notes"
  546. note.displayStepUnpitched = displayStep;
  547. note.displayOctaveUnpitched = displayOctave;
  548. note.NoteheadColorXml = noteheadColorXml; // color set in Xml, shouldn't be changed.
  549. note.NoteheadColor = noteheadColorXml; // color currently used
  550. // add TypeLength for rest notes like with Note?
  551. // add IsGraceNote for rest notes like with Notes?
  552. // add PlaybackInstrumentId for rest notes?
  553. }
  554. /**
  555. * Handle the currentVoiceBeam.
  556. * @param node
  557. * @param note
  558. */
  559. private createBeam(node: IXmlElement, note: Note): void {
  560. try {
  561. const beamNode: IXmlElement = node.element("beam");
  562. let beamAttr: IXmlAttribute = undefined;
  563. if (beamNode !== undefined && beamNode.hasAttributes) {
  564. beamAttr = beamNode.attribute("number");
  565. }
  566. if (beamAttr) {
  567. let beamNumber: number = parseInt(beamAttr.value, 10);
  568. const mainBeamNode: IXmlElement[] = node.elements("beam");
  569. const currentBeamTag: string = mainBeamNode[0].value;
  570. if (mainBeamNode) {
  571. if (currentBeamTag === "begin") {
  572. if (beamNumber === this.openBeams.last()?.BeamNumber) {
  573. // beam with same number already existed (error in XML), bump beam number
  574. this.beamNumberOffset++;
  575. beamNumber += this.beamNumberOffset;
  576. } else if (this.openBeams.last()) {
  577. this.handleOpenBeam();
  578. }
  579. this.openBeams.push(new Beam(beamNumber, this.beamNumberOffset));
  580. } else {
  581. beamNumber += this.beamNumberOffset;
  582. }
  583. }
  584. let sameVoiceEntry: boolean = false;
  585. if (!(beamNumber > 0 && beamNumber <= this.openBeams.length) || !this.openBeams[beamNumber - 1]) {
  586. log.debug("[OSMD] invalid beamnumber"); // this shouldn't happen, probably error in this method
  587. return;
  588. }
  589. for (let idx: number = 0, len: number = this.openBeams[beamNumber - 1].Notes.length; idx < len; ++idx) {
  590. const beamNote: Note = this.openBeams[beamNumber - 1].Notes[idx];
  591. if (this.currentVoiceEntry === beamNote.ParentVoiceEntry) {
  592. sameVoiceEntry = true;
  593. }
  594. }
  595. if (!sameVoiceEntry) {
  596. const openBeam: Beam = this.openBeams[beamNumber - 1];
  597. openBeam.addNoteToBeam(note);
  598. // const lastBeamNote: Note = openBeam.Notes.last();
  599. // const graceStatusChanged: boolean = (lastBeamNote?.IsCueNote || lastBeamNote?.IsGraceNote) !== (note.IsCueNote) || (note.IsGraceNote);
  600. if (currentBeamTag === "end") {
  601. this.endBeam();
  602. }
  603. }
  604. }
  605. } catch (e) {
  606. const errorMsg: string = ITextTranslation.translateText(
  607. "ReaderErrorMessages/BeamError", "Error while reading beam."
  608. );
  609. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  610. throw new MusicSheetReadingException("", e);
  611. }
  612. }
  613. private endBeam(): void {
  614. this.openBeams.pop(); // pop the last open beam from the stack. the latest openBeam will be the one before that now
  615. this.beamNumberOffset = Math.max(0, this.beamNumberOffset - 1);
  616. }
  617. /**
  618. * Check for open [[Beam]]s at end of [[SourceMeasure]] and closes them explicity.
  619. */
  620. private handleOpenBeam(): void {
  621. const openBeam: Beam = this.openBeams.last();
  622. if (openBeam.Notes.length === 1) {
  623. const beamNote: Note = openBeam.Notes[0];
  624. beamNote.NoteBeam = undefined;
  625. this.endBeam();
  626. return;
  627. }
  628. if (this.currentNote === CollectionUtil.last(openBeam.Notes)) {
  629. this.endBeam();
  630. } else {
  631. const beamLastNote: Note = CollectionUtil.last(openBeam.Notes);
  632. const beamLastNoteStaffEntry: SourceStaffEntry = beamLastNote.ParentStaffEntry;
  633. const horizontalIndex: number = this.currentMeasure.getVerticalContainerIndexByTimestamp(beamLastNoteStaffEntry.Timestamp);
  634. const verticalIndex: number = beamLastNoteStaffEntry.VerticalContainerParent.StaffEntries.indexOf(beamLastNoteStaffEntry);
  635. if (horizontalIndex < this.currentMeasure.VerticalSourceStaffEntryContainers.length - 1) {
  636. const nextStaffEntry: SourceStaffEntry = this.currentMeasure
  637. .VerticalSourceStaffEntryContainers[horizontalIndex + 1]
  638. .StaffEntries[verticalIndex];
  639. if (nextStaffEntry) {
  640. for (let idx: number = 0, len: number = nextStaffEntry.VoiceEntries.length; idx < len; ++idx) {
  641. const voiceEntry: VoiceEntry = nextStaffEntry.VoiceEntries[idx];
  642. if (voiceEntry.ParentVoice === this.voice) {
  643. const candidateNote: Note = voiceEntry.Notes[0];
  644. if (candidateNote.Length.lte(new Fraction(1, 8))) {
  645. this.openBeams.last().addNoteToBeam(candidateNote);
  646. this.endBeam();
  647. } else {
  648. this.endBeam();
  649. }
  650. }
  651. }
  652. }
  653. } else {
  654. this.endBeam();
  655. }
  656. }
  657. }
  658. /**
  659. * Create a [[Tuplet]].
  660. * @param node
  661. * @param tupletNodeList
  662. * @returns {number}
  663. */
  664. private addTuplet(node: IXmlElement, tupletNodeList: IXmlElement[]): number {
  665. let bracketed: boolean = false; // xml bracket attribute value
  666. // TODO refactor this to not duplicate lots of code for the cases tupletNodeList.length == 1 and > 1
  667. if (tupletNodeList !== undefined && tupletNodeList.length > 1) {
  668. let timeModNode: IXmlElement = node.element("time-modification");
  669. if (timeModNode) {
  670. timeModNode = timeModNode.element("actual-notes");
  671. }
  672. const tupletNodeListArr: IXmlElement[] = tupletNodeList;
  673. for (let idx: number = 0, len: number = tupletNodeListArr.length; idx < len; ++idx) {
  674. const tupletNode: IXmlElement = tupletNodeListArr[idx];
  675. if (tupletNode !== undefined && tupletNode.attributes()) {
  676. const bracketAttr: Attr = tupletNode.attribute("bracket");
  677. if (bracketAttr && bracketAttr.value === "yes") {
  678. bracketed = true;
  679. }
  680. const placementAttr: Attr = tupletNode.attribute("placement");
  681. const placementBelow: boolean = placementAttr && placementAttr.value === "below";
  682. const type: Attr = tupletNode.attribute("type");
  683. if (type && type.value === "start") {
  684. let tupletNumber: number = 1;
  685. if (tupletNode.attribute("number")) {
  686. tupletNumber = parseInt(tupletNode.attribute("number").value, 10);
  687. }
  688. let tupletLabelNumber: number = 0;
  689. if (timeModNode) {
  690. tupletLabelNumber = parseInt(timeModNode.value, 10);
  691. if (isNaN(tupletLabelNumber)) {
  692. const errorMsg: string = ITextTranslation.translateText(
  693. "ReaderErrorMessages/TupletNoteDurationError", "Invalid tuplet note duration."
  694. );
  695. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  696. throw new MusicSheetReadingException(errorMsg, undefined);
  697. }
  698. }
  699. const tuplet: Tuplet = new Tuplet(tupletLabelNumber, bracketed);
  700. tuplet.tupletLabelNumberPlacement = placementBelow ? PlacementEnum.Below : PlacementEnum.Above;
  701. if (this.tupletDict[tupletNumber]) {
  702. delete this.tupletDict[tupletNumber];
  703. if (Object.keys(this.tupletDict).length === 0) {
  704. this.openTupletNumber = 0;
  705. } else if (Object.keys(this.tupletDict).length > 1) {
  706. this.openTupletNumber--;
  707. }
  708. }
  709. this.tupletDict[tupletNumber] = tuplet;
  710. const subnotelist: Note[] = [];
  711. subnotelist.push(this.currentNote);
  712. tuplet.Notes.push(subnotelist);
  713. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  714. this.currentNote.NoteTuplet = tuplet;
  715. this.openTupletNumber = tupletNumber;
  716. } else if (type.value === "stop") {
  717. let tupletNumber: number = 1;
  718. if (tupletNode.attribute("number")) {
  719. tupletNumber = parseInt(tupletNode.attribute("number").value, 10);
  720. }
  721. const tuplet: Tuplet = this.tupletDict[tupletNumber];
  722. if (tuplet) {
  723. const subnotelist: Note[] = [];
  724. subnotelist.push(this.currentNote);
  725. tuplet.Notes.push(subnotelist);
  726. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  727. this.currentNote.NoteTuplet = tuplet;
  728. delete this.tupletDict[tupletNumber];
  729. if (Object.keys(this.tupletDict).length === 0) {
  730. this.openTupletNumber = 0;
  731. } else if (Object.keys(this.tupletDict).length > 1) {
  732. this.openTupletNumber--;
  733. }
  734. }
  735. }
  736. }
  737. }
  738. } else if (tupletNodeList[0]) {
  739. const n: IXmlElement = tupletNodeList[0];
  740. if (n.hasAttributes) {
  741. const type: string = n.attribute("type").value;
  742. let tupletnumber: number = 1;
  743. if (n.attribute("number")) {
  744. tupletnumber = parseInt(n.attribute("number").value, 10);
  745. }
  746. const noTupletNumbering: boolean = isNaN(tupletnumber);
  747. const bracketAttr: Attr = n.attribute("bracket");
  748. if (bracketAttr && bracketAttr.value === "yes") {
  749. bracketed = true;
  750. }
  751. const placementAttr: Attr = n.attribute("placement");
  752. const placementBelow: boolean = placementAttr && placementAttr.value === "below";
  753. if (type === "start") {
  754. let tupletLabelNumber: number = 0;
  755. let timeModNode: IXmlElement = node.element("time-modification");
  756. if (timeModNode) {
  757. timeModNode = timeModNode.element("actual-notes");
  758. }
  759. if (timeModNode) {
  760. tupletLabelNumber = parseInt(timeModNode.value, 10);
  761. if (isNaN(tupletLabelNumber)) {
  762. const errorMsg: string = ITextTranslation.translateText(
  763. "ReaderErrorMessages/TupletNoteDurationError", "Invalid tuplet note duration."
  764. );
  765. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  766. throw new MusicSheetReadingException(errorMsg);
  767. }
  768. }
  769. if (noTupletNumbering) {
  770. this.openTupletNumber++;
  771. tupletnumber = this.openTupletNumber;
  772. }
  773. let tuplet: Tuplet = this.tupletDict[tupletnumber];
  774. if (!tuplet) {
  775. tuplet = this.tupletDict[tupletnumber] = new Tuplet(tupletLabelNumber, bracketed);
  776. tuplet.tupletLabelNumberPlacement = placementBelow ? PlacementEnum.Below : PlacementEnum.Above;
  777. }
  778. const subnotelist: Note[] = [];
  779. subnotelist.push(this.currentNote);
  780. tuplet.Notes.push(subnotelist);
  781. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  782. this.currentNote.NoteTuplet = tuplet;
  783. this.openTupletNumber = tupletnumber;
  784. } else if (type === "stop") {
  785. if (noTupletNumbering) {
  786. tupletnumber = this.openTupletNumber;
  787. }
  788. const tuplet: Tuplet = this.tupletDict[this.openTupletNumber];
  789. if (tuplet) {
  790. const subnotelist: Note[] = [];
  791. subnotelist.push(this.currentNote);
  792. tuplet.Notes.push(subnotelist);
  793. tuplet.Fractions.push(this.getTupletNoteDurationFromType(node));
  794. this.currentNote.NoteTuplet = tuplet;
  795. if (Object.keys(this.tupletDict).length === 0) {
  796. this.openTupletNumber = 0;
  797. } else if (Object.keys(this.tupletDict).length > 1) {
  798. this.openTupletNumber--;
  799. }
  800. delete this.tupletDict[tupletnumber];
  801. }
  802. }
  803. }
  804. }
  805. return this.openTupletNumber;
  806. }
  807. /**
  808. * This method handles the time-modification IXmlElement for the Tuplet case (tupletNotes not at begin/end of Tuplet).
  809. * @param noteNode
  810. */
  811. private handleTimeModificationNode(noteNode: IXmlElement): void {
  812. if (this.tupletDict[this.openTupletNumber]) {
  813. try {
  814. // Tuplet should already be created
  815. const tuplet: Tuplet = this.tupletDict[this.openTupletNumber];
  816. const notes: Note[] = CollectionUtil.last(tuplet.Notes);
  817. const lastTupletVoiceEntry: VoiceEntry = notes[0].ParentVoiceEntry;
  818. let noteList: Note[];
  819. if (lastTupletVoiceEntry.Timestamp.Equals(this.currentVoiceEntry.Timestamp)) {
  820. noteList = notes;
  821. } else {
  822. noteList = [];
  823. tuplet.Notes.push(noteList);
  824. tuplet.Fractions.push(this.getTupletNoteDurationFromType(noteNode));
  825. }
  826. noteList.push(this.currentNote);
  827. this.currentNote.NoteTuplet = tuplet;
  828. } catch (ex) {
  829. const errorMsg: string = ITextTranslation.translateText(
  830. "ReaderErrorMessages/TupletNumberError", "Invalid tuplet number."
  831. );
  832. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  833. throw ex;
  834. }
  835. } else if (this.currentVoiceEntry.Notes.length > 0) {
  836. const firstNote: Note = this.currentVoiceEntry.Notes[0];
  837. if (firstNote.NoteTuplet) {
  838. const tuplet: Tuplet = firstNote.NoteTuplet;
  839. const notes: Note[] = CollectionUtil.last(tuplet.Notes);
  840. notes.push(this.currentNote);
  841. this.currentNote.NoteTuplet = tuplet;
  842. }
  843. }
  844. }
  845. private addTie(tieNodeList: IXmlElement[], measureStartAbsoluteTimestamp: Fraction, maxTieNoteFraction: Fraction, tieType: TieTypes): void {
  846. if (tieNodeList) {
  847. if (tieNodeList.length === 1) {
  848. const tieNode: IXmlElement = tieNodeList[0];
  849. if (tieNode !== undefined && tieNode.attributes()) {
  850. const type: string = tieNode.attribute("type").value;
  851. try {
  852. if (type === "start") {
  853. const num: number = this.findCurrentNoteInTieDict(this.currentNote);
  854. if (num < 0) {
  855. delete this.openTieDict[num];
  856. }
  857. const newTieNumber: number = this.getNextAvailableNumberForTie();
  858. const tie: Tie = new Tie(this.currentNote, tieType);
  859. this.openTieDict[newTieNumber] = tie;
  860. tie.TieNumber = newTieNumber;
  861. this.setTieDirections();
  862. } else if (type === "stop") {
  863. const tieNumber: number = this.findCurrentNoteInTieDict(this.currentNote);
  864. const tie: Tie = this.openTieDict[tieNumber];
  865. if (tie) {
  866. tie.AddNote(this.currentNote);
  867. delete this.openTieDict[tieNumber];
  868. }
  869. }
  870. } catch (err) {
  871. const errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/TieError", "Error while reading tie.");
  872. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  873. }
  874. }
  875. } else if (tieNodeList.length === 2) {
  876. const tieNumber: number = this.findCurrentNoteInTieDict(this.currentNote);
  877. if (tieNumber >= 0) {
  878. const tie: Tie = this.openTieDict[tieNumber];
  879. tie.AddNote(this.currentNote);
  880. }
  881. }
  882. }
  883. }
  884. // TODO do same for slurs, optimize.
  885. /** Sets the directions of open ties: up for the top one, down for the others. */
  886. private setTieDirections(): void {
  887. const tieKeys: string[] = Object.keys(this.openTieDict);
  888. let highestNote: Note = undefined;
  889. for (const tieKey of tieKeys) {
  890. const tie: Tie = this.openTieDict[tieKey];
  891. const tieNote: Note = tie.Notes[0];
  892. if (!highestNote || tieNote.Pitch.OperatorFundamentalGreaterThan(highestNote.Pitch)) {
  893. highestNote = tieNote;
  894. }
  895. }
  896. for (const tieKey of tieKeys) {
  897. const tie: Tie = this.openTieDict[tieKey];
  898. if (tie.Notes[0] === highestNote) {
  899. tie.TieDirection = PlacementEnum.Above;
  900. } else {
  901. tie.TieDirection = PlacementEnum.Below;
  902. }
  903. }
  904. }
  905. /**
  906. * Find the next free int (starting from 0) to use as key in TieDict.
  907. * @returns {number}
  908. */
  909. private getNextAvailableNumberForTie(): number {
  910. const keys: string[] = Object.keys(this.openTieDict);
  911. if (keys.length === 0) {
  912. return 1;
  913. }
  914. keys.sort((a, b) => (+a - +b)); // FIXME Andrea: test
  915. for (let i: number = 0; i < keys.length; i++) {
  916. if ("" + (i + 1) !== keys[i]) {
  917. return i + 1;
  918. }
  919. }
  920. return +(keys[keys.length - 1]) + 1;
  921. }
  922. /**
  923. * Search the tieDictionary for the corresponding candidateNote to the currentNote (same FundamentalNote && Octave).
  924. * @param candidateNote
  925. * @returns {number}
  926. */
  927. private findCurrentNoteInTieDict(candidateNote: Note): number {
  928. const openTieDict: { [_: number]: Tie } = this.openTieDict;
  929. for (const key in openTieDict) {
  930. if (openTieDict.hasOwnProperty(key)) {
  931. const tie: Tie = openTieDict[key];
  932. const tieTabNote: TabNote = tie.Notes[0] as TabNote;
  933. const tieCandidateNote: TabNote = candidateNote as TabNote;
  934. if (tie.Pitch.FundamentalNote === candidateNote.Pitch.FundamentalNote && tie.Pitch.Octave === candidateNote.Pitch.Octave) {
  935. return parseInt(key, 10);
  936. } else if (tieTabNote.StringNumberTab !== undefined) {
  937. if (tieTabNote.StringNumberTab === tieCandidateNote.StringNumberTab) {
  938. return parseInt(key, 10);
  939. }
  940. }
  941. }
  942. }
  943. return -1;
  944. }
  945. /**
  946. * Calculate the normal duration of a [[Tuplet]] note.
  947. * @param xmlNode
  948. * @returns {any}
  949. */
  950. private getTupletNoteDurationFromType(xmlNode: IXmlElement): Fraction {
  951. if (xmlNode.element("type")) {
  952. const typeNode: IXmlElement = xmlNode.element("type");
  953. if (typeNode) {
  954. const type: string = typeNode.value;
  955. try {
  956. return NoteTypeHandler.getNoteDurationFromType(type);
  957. } catch (e) {
  958. const errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/NoteDurationError", "Invalid note duration.");
  959. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  960. throw new MusicSheetReadingException("", e);
  961. }
  962. }
  963. }
  964. return undefined;
  965. }
  966. }