VexFlowMusicSheetCalculator.ts 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815
  1. import { MusicSheetCalculator } from "../MusicSheetCalculator";
  2. import { VexFlowGraphicalSymbolFactory } from "./VexFlowGraphicalSymbolFactory";
  3. import { GraphicalMeasure } from "../GraphicalMeasure";
  4. import { StaffLine } from "../StaffLine";
  5. import { VoiceEntry } from "../../VoiceData/VoiceEntry";
  6. import { GraphicalNote } from "../GraphicalNote";
  7. import { GraphicalStaffEntry } from "../GraphicalStaffEntry";
  8. import { GraphicalTie } from "../GraphicalTie";
  9. import { Tie } from "../../VoiceData/Tie";
  10. import { SourceMeasure } from "../../VoiceData/SourceMeasure";
  11. import { MultiExpression } from "../../VoiceData/Expressions/MultiExpression";
  12. import { RepetitionInstruction } from "../../VoiceData/Instructions/RepetitionInstruction";
  13. import { Beam } from "../../VoiceData/Beam";
  14. import { ClefInstruction } from "../../VoiceData/Instructions/ClefInstruction";
  15. import { OctaveEnum, OctaveShift } from "../../VoiceData/Expressions/ContinuousExpressions/OctaveShift";
  16. import { Fraction } from "../../../Common/DataObjects/Fraction";
  17. import { LyricWord } from "../../VoiceData/Lyrics/LyricsWord";
  18. import { OrnamentContainer, OrnamentEnum } from "../../VoiceData/OrnamentContainer";
  19. import { Articulation } from "../../VoiceData/Articulation";
  20. import { Tuplet } from "../../VoiceData/Tuplet";
  21. import { VexFlowMeasure } from "./VexFlowMeasure";
  22. import { VexFlowTextMeasurer } from "./VexFlowTextMeasurer";
  23. import Vex from "vexflow";
  24. import log from "loglevel";
  25. import { unitInPixels } from "./VexFlowMusicSheetDrawer";
  26. import { VexFlowGraphicalNote } from "./VexFlowGraphicalNote";
  27. import { TechnicalInstruction } from "../../VoiceData/Instructions/TechnicalInstruction";
  28. import { GraphicalLyricEntry } from "../GraphicalLyricEntry";
  29. import { GraphicalLabel } from "../GraphicalLabel";
  30. import { LyricsEntry } from "../../VoiceData/Lyrics/LyricsEntry";
  31. import { GraphicalLyricWord } from "../GraphicalLyricWord";
  32. import { VexFlowStaffEntry } from "./VexFlowStaffEntry";
  33. import { VexFlowOctaveShift } from "./VexFlowOctaveShift";
  34. import { VexFlowInstantaneousDynamicExpression } from "./VexFlowInstantaneousDynamicExpression";
  35. import { Slur } from "../../VoiceData/Expressions/ContinuousExpressions/Slur";
  36. /* VexFlow Version - for later use
  37. // import { VexFlowSlur } from "./VexFlowSlur";
  38. // import { VexFlowStaffLine } from "./VexFlowStaffLine";
  39. // import { VexFlowVoiceEntry } from "./VexFlowVoiceEntry";
  40. */
  41. import { PointF2D } from "../../../Common/DataObjects/PointF2D";
  42. import { TextAlignmentEnum, TextAlignment } from "../../../Common/Enums/TextAlignment";
  43. import { GraphicalSlur } from "../GraphicalSlur";
  44. import { BoundingBox } from "../BoundingBox";
  45. import { ContinuousDynamicExpression } from "../../VoiceData/Expressions/ContinuousExpressions/ContinuousDynamicExpression";
  46. import { VexFlowContinuousDynamicExpression } from "./VexFlowContinuousDynamicExpression";
  47. import { InstantaneousTempoExpression, TempoEnum } from "../../VoiceData/Expressions/InstantaneousTempoExpression";
  48. import { AlignRestOption } from "../../../OpenSheetMusicDisplay/OSMDOptions";
  49. import { VexFlowStaffLine } from "./VexFlowStaffLine";
  50. import { EngravingRules } from "../EngravingRules";
  51. import { VexflowStafflineNoteCalculator } from "./VexflowStafflineNoteCalculator";
  52. import { MusicSystem } from "../MusicSystem";
  53. import { NoteTypeHandler } from "../../VoiceData/NoteType";
  54. import { VexFlowConverter } from "./VexFlowConverter";
  55. import { TabNote } from "../../VoiceData/TabNote";
  56. import { PlacementEnum } from "../../VoiceData/Expressions";
  57. import { GraphicalChordSymbolContainer } from "../GraphicalChordSymbolContainer";
  58. import { RehearsalExpression } from "../../VoiceData/Expressions/RehearsalExpression";
  59. import { Pedal } from "../../VoiceData/Expressions/ContinuousExpressions/Pedal";
  60. import { VexFlowPedal } from "./VexFlowPedal";
  61. import { MusicSymbol } from "../MusicSymbol";
  62. import { VexFlowVoiceEntry } from "./VexFlowVoiceEntry";
  63. import { WavyLine } from "../../VoiceData/Expressions/ContinuousExpressions/WavyLine";
  64. import { VexflowVibratoBracket } from "./VexflowVibratoBracket";
  65. export class VexFlowMusicSheetCalculator extends MusicSheetCalculator {
  66. /** space needed for a dash for lyrics spacing, calculated once */
  67. private dashSpace: number;
  68. public beamsNeedUpdate: boolean = false;
  69. constructor(rules: EngravingRules) {
  70. super();
  71. this.rules = rules;
  72. MusicSheetCalculator.symbolFactory = new VexFlowGraphicalSymbolFactory();
  73. MusicSheetCalculator.TextMeasurer = new VexFlowTextMeasurer(this.rules);
  74. MusicSheetCalculator.stafflineNoteCalculator = new VexflowStafflineNoteCalculator(this.rules);
  75. // prepare Vexflow font (doesn't affect Vexflow 1.x). It seems like this has to be done here for now, otherwise it's too slow for the generateImages script.
  76. // (first image will have the non-updated font, in this case the Vexflow default Bravura, while we want Gonville here)
  77. if (this.rules.DefaultVexFlowNoteFont?.toLowerCase() === "gonville") {
  78. (Vex.Flow as any).DEFAULT_FONT_STACK = [(Vex.Flow as any).Fonts?.Gonville, (Vex.Flow as any).Fonts?.Bravura, (Vex.Flow as any).Fonts?.Custom];
  79. } else if (this.rules.DefaultVexFlowNoteFont?.toLowerCase() === "petaluma") {
  80. (Vex.Flow as any).DEFAULT_FONT_STACK = [(Vex.Flow as any).Fonts?.Petaluma, (Vex.Flow as any).Fonts?.Gonville, (Vex.Flow as any).Fonts?.Bravura];
  81. }
  82. // else keep new vexflow default Bravura (more cursive, bold)
  83. }
  84. protected clearRecreatedObjects(): void {
  85. super.clearRecreatedObjects();
  86. MusicSheetCalculator.stafflineNoteCalculator = new VexflowStafflineNoteCalculator(this.rules);
  87. for (const graphicalMeasures of this.graphicalMusicSheet.MeasureList) {
  88. for (const graphicalMeasure of graphicalMeasures) {
  89. (<VexFlowMeasure>graphicalMeasure)?.clean();
  90. }
  91. }
  92. }
  93. protected formatMeasures(): void {
  94. // let totalFinalizeBeamsTime: number = 0;
  95. for (const verticalMeasureList of this.graphicalMusicSheet.MeasureList) {
  96. if (!verticalMeasureList || !verticalMeasureList[0]) {
  97. continue;
  98. }
  99. const firstMeasure: VexFlowMeasure = verticalMeasureList[0] as VexFlowMeasure;
  100. // first measure has formatting method as lambda function object, but formats all measures. TODO this could be refactored
  101. firstMeasure.format();
  102. for (const measure of verticalMeasureList) {
  103. for (const staffEntry of measure.staffEntries) {
  104. (<VexFlowStaffEntry>staffEntry).calculateXPosition();
  105. }
  106. // const t0: number = performance.now();
  107. if (true || this.beamsNeedUpdate) {
  108. // finalizeBeams takes a few milliseconds, so we can save some performance here sometimes,
  109. // but we'd have to check for every setting change that would affect beam rendering. See #843
  110. (measure as VexFlowMeasure).finalizeBeams(); // without this, when zooming a lot (e.g. 250%), beams keep their old, now wrong slope.
  111. // totalFinalizeBeamsTime += performance.now() - t0;
  112. // console.log("Total calls to finalizeBeams in VexFlowMusicSheetCalculator took " + totalFinalizeBeamsTime + " milliseconds.");
  113. }
  114. }
  115. }
  116. this.beamsNeedUpdate = false;
  117. }
  118. //protected clearSystemsAndMeasures(): void {
  119. // for (let measure of measures) {
  120. //
  121. // }
  122. //}
  123. /**
  124. * Calculates the x layout of the staff entries within the staff measures belonging to one source measure.
  125. * All staff entries are x-aligned throughout all vertically aligned staff measures.
  126. * This method is called within calculateXLayout.
  127. * The staff entries are aligned with minimum needed x distances.
  128. * The MinimumStaffEntriesWidth of every measure will be set - needed for system building.
  129. * Prepares the VexFlow formatter for later formatting
  130. * Does not calculate measure width from lyrics (which is called from MusicSheetCalculator)
  131. * @param measures
  132. * @returns the minimum required x width of the source measure (=list of staff measures)
  133. */
  134. protected calculateMeasureXLayout(measures: GraphicalMeasure[]): number {
  135. const visibleMeasures: GraphicalMeasure[] = [];
  136. for (const measure of measures) {
  137. if (measure) {
  138. visibleMeasures.push(measure);
  139. }
  140. }
  141. if (visibleMeasures.length === 0) { // e.g. after Multiple Rest measures (VexflowMultiRestMeasure)
  142. return 0;
  143. }
  144. measures = visibleMeasures;
  145. // Format the voices
  146. const allVoices: Vex.Flow.Voice[] = [];
  147. const formatter: Vex.Flow.Formatter = new Vex.Flow.Formatter({
  148. // maxIterations: 2,
  149. softmaxFactor: this.rules.SoftmaxFactorVexFlow // this setting is only applied in Vexflow 3.x. also this needs @types/vexflow ^3.0.0
  150. });
  151. let maxStaffEntries: number = measures[0].staffEntries.length;
  152. let maxStaffEntriesPlusAccidentals: number = 1;
  153. for (const measure of measures) {
  154. if (!measure) {
  155. continue;
  156. }
  157. let measureAccidentals: number = 0;
  158. for (const staffEntry of measure.staffEntries) {
  159. measureAccidentals += (staffEntry as VexFlowStaffEntry).setMaxAccidentals(); // staffEntryAccidentals
  160. }
  161. // TODO the if is a TEMP change to show pure diff for pickup measures, should be done for all measures, but increases spacing
  162. if (measure.parentSourceMeasure.ImplicitMeasure) {
  163. maxStaffEntries = Math.max(measure.staffEntries.length, maxStaffEntries);
  164. maxStaffEntriesPlusAccidentals = Math.max(measure.staffEntries.length + measureAccidentals, maxStaffEntriesPlusAccidentals);
  165. }
  166. const mvoices: { [voiceID: number]: Vex.Flow.Voice } = (measure as VexFlowMeasure).vfVoices;
  167. const voices: Vex.Flow.Voice[] = [];
  168. for (const voiceID in mvoices) {
  169. if (mvoices.hasOwnProperty(voiceID)) {
  170. voices.push(mvoices[voiceID]);
  171. allVoices.push(mvoices[voiceID]);
  172. }
  173. }
  174. if (voices.length === 0) {
  175. log.debug("Found a measure with no voices. Continuing anyway.", mvoices);
  176. // no need to log this, measures with no voices/notes are fine. see OSMDOptions.fillEmptyMeasuresWithWholeRest
  177. continue;
  178. }
  179. // all voices that belong to one stave are collectively added to create a common context in VexFlow.
  180. formatter.joinVoices(voices);
  181. }
  182. let minStaffEntriesWidth: number = 12; // a typical measure has roughly a length of 3*StaffHeight (3*4 = 12)
  183. const parentSourceMeasure: SourceMeasure = measures[0].parentSourceMeasure;
  184. // the voicing space bonus addition makes the voicing more relaxed. With a bonus of 0 the notes are basically completely squeezed together.
  185. const staffEntryFactor: number = 0.3;
  186. if (allVoices.length > 0) {
  187. minStaffEntriesWidth = formatter.preCalculateMinTotalWidth(allVoices) / unitInPixels
  188. * this.rules.VoiceSpacingMultiplierVexflow
  189. + this.rules.VoiceSpacingAddendVexflow
  190. + maxStaffEntries * staffEntryFactor; // TODO use maxStaffEntriesPlusAccidentals here as well, adjust spacing
  191. if (parentSourceMeasure?.ImplicitMeasure) {
  192. // shrink width in the ratio that the pickup measure is shorter compared to a full measure('s time signature):
  193. minStaffEntriesWidth = parentSourceMeasure.Duration.RealValue / parentSourceMeasure.ActiveTimeSignature.RealValue * minStaffEntriesWidth;
  194. // e.g. a 1/4 pickup measure in a 3/4 time signature should be 1/4 / 3/4 = 1/3 as long (a third)
  195. // it seems like this should be respected by staffEntries.length and preCaculateMinTotalWidth, but apparently not,
  196. // without this the pickup measures were always too long.
  197. // add more than the original staffEntries scaling again: (removing it above makes it too short)
  198. if (maxStaffEntries > 1) { // not necessary for only 1 StaffEntry
  199. minStaffEntriesWidth += maxStaffEntriesPlusAccidentals * staffEntryFactor * 1.5; // don't scale this for implicit measures
  200. // in fact overscale it, this needs a lot of space the more staffEntries (and modifiers like accidentals) there are
  201. }
  202. minStaffEntriesWidth *= this.rules.PickupMeasureWidthMultiplier;
  203. }
  204. // TODO this could use some fine-tuning. currently using *1.5 + 1 by default, results in decent spacing.
  205. // firstMeasure.formatVoices = (w: number) => {
  206. // formatter.format(allVoices, w);
  207. // };
  208. MusicSheetCalculator.setMeasuresMinStaffEntriesWidth(measures, minStaffEntriesWidth);
  209. const formatVoicesDefault: (w: number, p: VexFlowMeasure) => void = (w, p) => {
  210. formatter.formatToStave(allVoices, p.getVFStave());
  211. };
  212. const formatVoicesAlignRests: (w: number, p: VexFlowMeasure) => void = (w, p) => {
  213. formatter.formatToStave(allVoices, p.getVFStave(), {
  214. align_rests: true,
  215. context: undefined
  216. });
  217. };
  218. for (const measure of measures) {
  219. // determine whether to align rests
  220. if (this.rules.AlignRests === AlignRestOption.Never) {
  221. (measure as VexFlowMeasure).formatVoices = formatVoicesDefault;
  222. } else if (this.rules.AlignRests === AlignRestOption.Always) {
  223. (measure as VexFlowMeasure).formatVoices = formatVoicesAlignRests;
  224. } else if (this.rules.AlignRests === AlignRestOption.Auto) {
  225. let alignRests: boolean = false;
  226. for (const staffEntry of measure.staffEntries) {
  227. let collidableVoiceEntries: number = 0;
  228. let numberOfRests: number = 0;
  229. for (const voiceEntry of staffEntry.graphicalVoiceEntries) {
  230. if (!voiceEntry.parentVoiceEntry.IsGrace) {
  231. if (voiceEntry && voiceEntry.notes && voiceEntry.notes[0] && voiceEntry.notes[0].sourceNote) {// TODO null chaining, TS 3.7
  232. if (voiceEntry.notes[0].sourceNote.PrintObject) { // only respect collision when not invisible
  233. collidableVoiceEntries++;
  234. }
  235. }
  236. }
  237. if (voiceEntry && voiceEntry.notes && voiceEntry.notes[0] && voiceEntry.notes[0].sourceNote) {// TODO null chaining, TS 3.7
  238. if (voiceEntry.notes[0].sourceNote.isRest() && voiceEntry.notes[0].sourceNote.PrintObject) {
  239. numberOfRests++; // only align rests if there is actually a rest (which could collide)
  240. }
  241. }
  242. if (collidableVoiceEntries > 1 && numberOfRests >= 1) {
  243. // TODO could add further checks like if any of the already checked voice entries actually collide
  244. alignRests = true;
  245. break;
  246. }
  247. }
  248. if (alignRests) {
  249. break;
  250. }
  251. }
  252. // set measure's format function
  253. if (alignRests) {
  254. (measure as VexFlowMeasure).formatVoices = formatVoicesAlignRests;
  255. } else {
  256. (measure as VexFlowMeasure).formatVoices = formatVoicesDefault;
  257. }
  258. }
  259. // format first measure with minimum width
  260. if (measure === measures[0]) {
  261. const vexflowMeasure: VexFlowMeasure = (measure as VexFlowMeasure);
  262. // prepare format function for voices, will be called later for formatting measure again
  263. //vexflowMeasure.formatVoices = formatVoicesDefault;
  264. // format now for minimum width, calculateMeasureWidthFromLyrics later
  265. vexflowMeasure.formatVoices(minStaffEntriesWidth * unitInPixels, vexflowMeasure);
  266. } else {
  267. //(measure as VexFlowMeasure).formatVoices = undefined;
  268. // TODO why was the formatVoices function disabled for other measures? would now disable the new align rests option.
  269. }
  270. }
  271. }
  272. for (const graphicalMeasure of measures) {
  273. if (!graphicalMeasure) {
  274. continue;
  275. }
  276. for (const staffEntry of graphicalMeasure.staffEntries) {
  277. // here the measure modifiers are not yet set, therefore the begin instruction width will be empty
  278. (<VexFlowStaffEntry>staffEntry).calculateXPosition();
  279. }
  280. }
  281. //Can't quite figure out why, but this is the calculation that needs redone to have consistent rendering.
  282. //The first render of a sheet vs. subsequent renders are calculated differently by vexflow without this re-joining of the voices
  283. for (const measure of measures) {
  284. if (!measure) {
  285. continue;
  286. }
  287. const mvoices: { [voiceID: number]: Vex.Flow.Voice } = (measure as VexFlowMeasure).vfVoices;
  288. const voices: Vex.Flow.Voice[] = [];
  289. for (const voiceID in mvoices) {
  290. if (mvoices.hasOwnProperty(voiceID)) {
  291. voices.push(mvoices[voiceID]);
  292. }
  293. }
  294. if (voices.length === 0) {
  295. log.debug("Found a measure with no voices. Continuing anyway.", mvoices);
  296. // no need to log this, measures with no voices/notes are fine. see OSMDOptions.fillEmptyMeasuresWithWholeRest
  297. continue;
  298. }
  299. // all voices that belong to one stave are collectively added to create a common context in VexFlow.
  300. formatter.joinVoices(voices);
  301. }
  302. // calculateMeasureWidthFromLyrics() will be called from MusicSheetCalculator after this
  303. return minStaffEntriesWidth;
  304. }
  305. private calculateElongationFactor(containers: (GraphicalLyricEntry|GraphicalChordSymbolContainer)[], staffEntry: GraphicalStaffEntry, lastEntryDict: any,
  306. oldMinimumStaffEntriesWidth: number, elongationFactorForMeasureWidth: number,
  307. measureNumber: number, oldMinSpacing: number, nextMeasureOverlap: number): number {
  308. let newElongationFactorForMeasureWidth: number = elongationFactorForMeasureWidth;
  309. let currentContainerIndex: number = 0;
  310. for (const container of containers) {
  311. const alignment: TextAlignmentEnum = container.GraphicalLabel.Label.textAlignment;
  312. let minSpacing: number = oldMinSpacing;
  313. let overlapAllowedIntoNextMeasure: number = nextMeasureOverlap;
  314. if (container instanceof GraphicalLyricEntry && container.ParentLyricWord) {
  315. // spacing for multi-syllable words
  316. if (container.LyricsEntry.SyllableIndex > 0) { // syllables after first
  317. // give a little more spacing for dash between syllables
  318. minSpacing = this.rules.BetweenSyllableMinimumDistance;
  319. if (TextAlignment.IsCenterAligned(alignment)) {
  320. minSpacing += 1.0; // TODO check for previous lyric alignment too. though center is not standard
  321. // without this, there's not enough space for dashes between long syllables on eigth notes
  322. }
  323. }
  324. const syllables: LyricsEntry[] = container.ParentLyricWord.GetLyricWord.Syllables;
  325. if (syllables.length > 1) {
  326. if (container.LyricsEntry.SyllableIndex < syllables.length - 1) {
  327. // if a middle syllable of a word, give less measure overlap into next measure, to give room for dash
  328. if (this.dashSpace === undefined) { // don't replace undefined check
  329. this.dashSpace = 1.5;
  330. // better method, doesn't work:
  331. // this.dashLength = new GraphicalLabel(new Label("-"), this.rules.LyricsHeight, TextAlignmentEnum.CenterBottom)
  332. // .PositionAndShape.Size.width; // always returns 0
  333. }
  334. overlapAllowedIntoNextMeasure -= this.dashSpace;
  335. }
  336. }
  337. }
  338. const bBox: BoundingBox = container instanceof GraphicalLyricEntry ? container.GraphicalLabel.PositionAndShape : container.PositionAndShape;
  339. const labelWidth: number = bBox.Size.width;
  340. const staffEntryXPosition: number = (staffEntry as VexFlowStaffEntry).PositionAndShape.RelativePosition.x;
  341. const xPosition: number = staffEntryXPosition + bBox.BorderMarginLeft;
  342. if (lastEntryDict[currentContainerIndex] !== undefined) {
  343. if (lastEntryDict[currentContainerIndex].extend) {
  344. // TODO handle extend of last entry (extend is stored in lyrics entry of preceding syllable)
  345. // only necessary for center alignment
  346. }
  347. }
  348. let spacingNeededToLastContainer: number;
  349. let currentSpacingToLastContainer: number; // undefined for first container in measure
  350. if (lastEntryDict[currentContainerIndex]) {
  351. currentSpacingToLastContainer = xPosition - lastEntryDict[currentContainerIndex].xPosition;
  352. }
  353. let currentSpacingToMeasureEnd: number;
  354. let spacingNeededToMeasureEnd: number;
  355. const maxXInMeasure: number = oldMinimumStaffEntriesWidth * elongationFactorForMeasureWidth;
  356. if (TextAlignment.IsCenterAligned(alignment)) {
  357. overlapAllowedIntoNextMeasure /= 4; // reserve space for overlap from next measure. its first note can't be spaced.
  358. currentSpacingToMeasureEnd = maxXInMeasure - xPosition;
  359. spacingNeededToMeasureEnd = (labelWidth / 2) - overlapAllowedIntoNextMeasure;
  360. // spacing to last lyric only done if not first lyric in measure:
  361. if (lastEntryDict[currentContainerIndex]) {
  362. spacingNeededToLastContainer =
  363. lastEntryDict[currentContainerIndex].labelWidth / 2 + labelWidth / 2 + minSpacing;
  364. }
  365. } else if (TextAlignment.IsLeft(alignment)) {
  366. currentSpacingToMeasureEnd = maxXInMeasure - xPosition;
  367. spacingNeededToMeasureEnd = labelWidth - overlapAllowedIntoNextMeasure;
  368. if (lastEntryDict[currentContainerIndex]) {
  369. spacingNeededToLastContainer = lastEntryDict[currentContainerIndex].labelWidth + minSpacing;
  370. }
  371. }
  372. // get factor of how much we need to stretch the measure to space the current lyric
  373. let elongationFactorForMeasureWidthForCurrentContainer: number = 1;
  374. const elongationFactorNeededForMeasureEnd: number =
  375. spacingNeededToMeasureEnd / currentSpacingToMeasureEnd;
  376. let elongationFactorNeededForLastContainer: number = 1;
  377. if (container instanceof GraphicalLyricEntry && container.LyricsEntry) {
  378. if (lastEntryDict[currentContainerIndex]) { // if previous lyric needs more spacing than measure end, take that spacing
  379. const lastNoteDuration: Fraction = lastEntryDict[currentContainerIndex].sourceNoteDuration;
  380. elongationFactorNeededForLastContainer = spacingNeededToLastContainer / currentSpacingToLastContainer;
  381. if ((lastNoteDuration.Denominator) > 4) {
  382. elongationFactorNeededForLastContainer *= 1.1; // from 1.2 upwards, this unnecessarily bloats shorter measures
  383. // spacing in Vexflow depends on note duration, our minSpacing is calibrated for quarter notes
  384. // if we double the measure length, the distance between eigth notes only gets half of the added length
  385. // compared to a quarter note.
  386. }
  387. }
  388. } else if (lastEntryDict[currentContainerIndex]) {
  389. elongationFactorNeededForLastContainer =
  390. spacingNeededToLastContainer / currentSpacingToLastContainer;
  391. }
  392. elongationFactorForMeasureWidthForCurrentContainer = Math.max(
  393. elongationFactorNeededForMeasureEnd,
  394. elongationFactorNeededForLastContainer
  395. );
  396. newElongationFactorForMeasureWidth = Math.max(
  397. newElongationFactorForMeasureWidth,
  398. elongationFactorForMeasureWidthForCurrentContainer
  399. );
  400. let overlap: number = Math.max((spacingNeededToLastContainer - currentSpacingToLastContainer) || 0, 0);
  401. if (lastEntryDict[currentContainerIndex]) {
  402. overlap += lastEntryDict[currentContainerIndex].cumulativeOverlap;
  403. }
  404. // set up information about this lyric entry of verse j for next lyric entry of verse j
  405. lastEntryDict[currentContainerIndex] = {
  406. cumulativeOverlap: overlap,
  407. extend: container instanceof GraphicalLyricEntry ? container.LyricsEntry.extend : false,
  408. labelWidth: labelWidth,
  409. measureNumber: measureNumber,
  410. sourceNoteDuration: container instanceof GraphicalLyricEntry ? (container.LyricsEntry && container.LyricsEntry.Parent.Notes[0].Length) : false,
  411. text: container instanceof GraphicalLyricEntry ? container.LyricsEntry.Text : container.GraphicalLabel.Label.text,
  412. xPosition: xPosition,
  413. };
  414. currentContainerIndex++;
  415. }
  416. return newElongationFactorForMeasureWidth;
  417. }
  418. public calculateElongationFactorFromStaffEntries(staffEntries: GraphicalStaffEntry[], oldMinimumStaffEntriesWidth: number,
  419. elongationFactorForMeasureWidth: number, measureNumber: number): number {
  420. interface EntryInfo {
  421. cumulativeOverlap: number;
  422. extend: boolean;
  423. labelWidth: number;
  424. xPosition: number;
  425. sourceNoteDuration: Fraction;
  426. text: string;
  427. measureNumber: number;
  428. }
  429. // holds lyrics entries for verses i
  430. interface EntryDict {
  431. [i: number]: EntryInfo;
  432. }
  433. let newElongationFactorForMeasureWidth: number = elongationFactorForMeasureWidth;
  434. const lastLyricEntryDict: EntryDict = {}; // holds info about last lyric entries for all verses j???
  435. const lastChordEntryDict: EntryDict = {}; // holds info about last chord entries for all verses j???
  436. // for all staffEntries i, each containing the lyric entry for all verses at that timestamp in the measure
  437. for (const staffEntry of staffEntries) {
  438. if (staffEntry.LyricsEntries.length > 0) {
  439. newElongationFactorForMeasureWidth =
  440. this.calculateElongationFactor(
  441. staffEntry.LyricsEntries,
  442. staffEntry,
  443. lastLyricEntryDict,
  444. oldMinimumStaffEntriesWidth,
  445. newElongationFactorForMeasureWidth,
  446. measureNumber,
  447. this.rules.HorizontalBetweenLyricsDistance,
  448. this.rules.LyricOverlapAllowedIntoNextMeasure,
  449. );
  450. }
  451. if (staffEntry.graphicalChordContainers.length > 0) {
  452. newElongationFactorForMeasureWidth =
  453. this.calculateElongationFactor(
  454. staffEntry.graphicalChordContainers,
  455. staffEntry,
  456. lastChordEntryDict,
  457. oldMinimumStaffEntriesWidth,
  458. newElongationFactorForMeasureWidth,
  459. measureNumber,
  460. this.rules.ChordSymbolXSpacing,
  461. this.rules.ChordOverlapAllowedIntoNextMeasure,
  462. );
  463. }
  464. }
  465. return newElongationFactorForMeasureWidth;
  466. }
  467. public calculateMeasureWidthFromStaffEntries(measuresVertical: GraphicalMeasure[], oldMinimumStaffEntriesWidth: number): number {
  468. let elongationFactorForMeasureWidth: number = 1;
  469. for (const measure of measuresVertical) {
  470. if (!measure || measure.staffEntries.length === 0) {
  471. continue;
  472. }
  473. elongationFactorForMeasureWidth =
  474. this.calculateElongationFactorFromStaffEntries(
  475. measure.staffEntries,
  476. oldMinimumStaffEntriesWidth,
  477. elongationFactorForMeasureWidth,
  478. measure.MeasureNumber,
  479. );
  480. }
  481. elongationFactorForMeasureWidth = Math.min(elongationFactorForMeasureWidth, this.rules.MaximumLyricsElongationFactor);
  482. // TODO check when this is > 2.0. there seems to be an error here where this is unnecessarily > 2 in Beethoven Geliebte.
  483. const newMinimumStaffEntriesWidth: number = oldMinimumStaffEntriesWidth * elongationFactorForMeasureWidth;
  484. return newMinimumStaffEntriesWidth;
  485. }
  486. protected createGraphicalTie(tie: Tie, startGse: GraphicalStaffEntry, endGse: GraphicalStaffEntry,
  487. startNote: GraphicalNote, endNote: GraphicalNote): GraphicalTie {
  488. return new GraphicalTie(tie, startNote, endNote);
  489. }
  490. protected updateStaffLineBorders(staffLine: StaffLine): void {
  491. staffLine.SkyBottomLineCalculator.updateStaffLineBorders();
  492. }
  493. protected graphicalMeasureCreatedCalculations(measure: GraphicalMeasure): void {
  494. (measure as VexFlowMeasure).rules = this.rules;
  495. (measure as VexFlowMeasure).graphicalMeasureCreatedCalculations();
  496. }
  497. /**
  498. * Can be used to calculate articulations, stem directions, helper(ledger) lines, and overlapping note x-displacement.
  499. * Is Excecuted per voice entry of a staff entry.
  500. * After that layoutStaffEntry is called.
  501. * @param voiceEntry
  502. * @param graphicalNotes
  503. * @param graphicalStaffEntry
  504. * @param hasPitchedNote
  505. */
  506. protected layoutVoiceEntry(voiceEntry: VoiceEntry, graphicalNotes: GraphicalNote[], graphicalStaffEntry: GraphicalStaffEntry,
  507. hasPitchedNote: boolean): void {
  508. for (let i: number = 0; i < graphicalNotes.length; i++) {
  509. graphicalNotes[i] = MusicSheetCalculator.stafflineNoteCalculator.positionNote(graphicalNotes[i]);
  510. }
  511. }
  512. /**
  513. * Do all layout calculations that have to be done per staff entry, like dots, ornaments, arpeggios....
  514. * This method is called after the voice entries are handled by layoutVoiceEntry().
  515. * @param graphicalStaffEntry
  516. */
  517. protected layoutStaffEntry(graphicalStaffEntry: GraphicalStaffEntry): void {
  518. (graphicalStaffEntry.parentMeasure as VexFlowMeasure).layoutStaffEntry(graphicalStaffEntry);
  519. }
  520. /**
  521. * Is called at the begin of the method for creating the vertically aligned staff measures belonging to one source measure.
  522. */
  523. protected initGraphicalMeasuresCreation(): void {
  524. return;
  525. }
  526. /**
  527. * add here all given articulations to the VexFlowGraphicalStaffEntry and prepare them for rendering.
  528. * @param articulations
  529. * @param voiceEntry
  530. * @param graphicalStaffEntry
  531. */
  532. protected layoutArticulationMarks(articulations: Articulation[], voiceEntry: VoiceEntry, graphicalStaffEntry: GraphicalStaffEntry): void {
  533. // uncomment this when implementing:
  534. // let vfse: VexFlowStaffEntry = (graphicalStaffEntry as VexFlowStaffEntry);
  535. return;
  536. }
  537. /**
  538. * Calculate the shape (Bezier curve) for this tie.
  539. * @param tie
  540. * @param tieIsAtSystemBreak
  541. * @param isTab Whether this tie is for a tab note (guitar tabulature)
  542. */
  543. protected layoutGraphicalTie(tie: GraphicalTie, tieIsAtSystemBreak: boolean, isTab: boolean): void {
  544. const startNote: VexFlowGraphicalNote = (tie.StartNote as VexFlowGraphicalNote);
  545. const endNote: VexFlowGraphicalNote = (tie.EndNote as VexFlowGraphicalNote);
  546. let vfStartNote: Vex.Flow.StemmableNote = undefined;
  547. let startNoteIndexInTie: number = 0;
  548. if (startNote && startNote.vfnote && startNote.vfnote.length >= 2) {
  549. vfStartNote = startNote.vfnote[0];
  550. startNoteIndexInTie = startNote.vfnote[1];
  551. }
  552. let vfEndNote: Vex.Flow.StemmableNote = undefined;
  553. let endNoteIndexInTie: number = 0;
  554. if (endNote && endNote.vfnote && endNote.vfnote.length >= 2) {
  555. vfEndNote = endNote.vfnote[0];
  556. endNoteIndexInTie = endNote.vfnote[1];
  557. }
  558. if (tieIsAtSystemBreak) {
  559. // split tie into two ties:
  560. if (vfStartNote) { // first_note or last_note must be not null in Vexflow
  561. const vfTie1: Vex.Flow.StaveTie = new Vex.Flow.StaveTie({
  562. first_indices: [startNoteIndexInTie],
  563. first_note: vfStartNote
  564. });
  565. const measure1: VexFlowMeasure = (startNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure);
  566. measure1.vfTies.push(vfTie1);
  567. }
  568. if (vfEndNote) {
  569. const vfTie2: Vex.Flow.StaveTie = new Vex.Flow.StaveTie({
  570. last_indices: [endNoteIndexInTie],
  571. last_note: vfEndNote
  572. });
  573. const measure2: VexFlowMeasure = (endNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure);
  574. measure2.vfTies.push(vfTie2);
  575. }
  576. } else {
  577. // normal case
  578. if (vfStartNote || vfEndNote) { // one of these must be not null in Vexflow
  579. let vfTie: any;
  580. if (isTab) {
  581. if (tie.Tie.Type === "S") {
  582. //calculate direction
  583. const startTieNote: TabNote = <TabNote> tie.StartNote.sourceNote;
  584. const endTieNote: TabNote = <TabNote> tie.EndNote.sourceNote;
  585. let slideDirection: number = 1;
  586. if (startTieNote.FretNumber > endTieNote.FretNumber) {
  587. slideDirection = -1;
  588. }
  589. vfTie = new Vex.Flow.TabSlide(
  590. {
  591. first_indices: [startNoteIndexInTie],
  592. first_note: vfStartNote,
  593. last_indices: [endNoteIndexInTie],
  594. last_note: vfEndNote,
  595. },
  596. slideDirection
  597. );
  598. } else {
  599. vfTie = new Vex.Flow.TabTie(
  600. {
  601. first_indices: [startNoteIndexInTie],
  602. first_note: vfStartNote,
  603. last_indices: [endNoteIndexInTie],
  604. last_note: vfEndNote,
  605. },
  606. tie.Tie.Type
  607. );
  608. }
  609. } else { // not Tab (guitar), normal StaveTie
  610. vfTie = new Vex.Flow.StaveTie({
  611. first_indices: [startNoteIndexInTie],
  612. first_note: vfStartNote,
  613. last_indices: [endNoteIndexInTie],
  614. last_note: vfEndNote
  615. });
  616. if (tie.Tie.TieDirection === PlacementEnum.Below) {
  617. vfTie.setDirection(1); // + is down in vexflow
  618. } else if (tie.Tie.TieDirection === PlacementEnum.Above) {
  619. vfTie.setDirection(-1);
  620. }
  621. }
  622. const measure: VexFlowMeasure = (endNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure);
  623. measure.vfTies.push(vfTie);
  624. }
  625. }
  626. }
  627. protected calculateDynamicExpressionsForMultiExpression(multiExpression: MultiExpression, measureIndex: number, staffIndex: number): void {
  628. if (measureIndex < this.rules.MinMeasureToDrawIndex || measureIndex > this.rules.MaxMeasureToDrawIndex) {
  629. return;
  630. // we do already use the min/max in MusicSheetCalculator.calculateDynamicsExpressions,
  631. // but this may be necessary for StaffLinkedExpressions, not tested.
  632. }
  633. // calculate absolute Timestamp
  634. const absoluteTimestamp: Fraction = multiExpression.AbsoluteTimestamp;
  635. const measures: GraphicalMeasure[] = this.graphicalMusicSheet.MeasureList[measureIndex];
  636. const staffLine: StaffLine = measures[staffIndex].ParentStaffLine;
  637. const startMeasure: GraphicalMeasure = measures[staffIndex];
  638. if (!staffLine) {
  639. return;
  640. }
  641. const startPosInStaffline: PointF2D = this.getRelativePositionInStaffLineFromTimestamp(
  642. absoluteTimestamp,
  643. staffIndex,
  644. staffLine,
  645. staffLine?.isPartOfMultiStaffInstrument());
  646. const dynamicStartPosition: PointF2D = startPosInStaffline;
  647. if (startPosInStaffline.x <= 0) {
  648. dynamicStartPosition.x = startMeasure.beginInstructionsWidth + this.rules.RhythmRightMargin;
  649. }
  650. if (multiExpression.InstantaneousDynamic) {
  651. const graphicalInstantaneousDynamic: VexFlowInstantaneousDynamicExpression = new VexFlowInstantaneousDynamicExpression(
  652. multiExpression.InstantaneousDynamic,
  653. staffLine,
  654. startMeasure);
  655. this.calculateGraphicalInstantaneousDynamicExpression(graphicalInstantaneousDynamic, dynamicStartPosition, absoluteTimestamp);
  656. this.dynamicExpressionMap.set(absoluteTimestamp.RealValue, graphicalInstantaneousDynamic.PositionAndShape);
  657. }
  658. if (multiExpression.StartingContinuousDynamic) {
  659. const continuousDynamic: ContinuousDynamicExpression = multiExpression.StartingContinuousDynamic;
  660. const graphicalContinuousDynamic: VexFlowContinuousDynamicExpression = new VexFlowContinuousDynamicExpression(
  661. multiExpression.StartingContinuousDynamic,
  662. staffLine,
  663. startMeasure.parentSourceMeasure);
  664. graphicalContinuousDynamic.StartMeasure = startMeasure;
  665. if (!graphicalContinuousDynamic.IsVerbal && continuousDynamic.EndMultiExpression) {
  666. try {
  667. this.calculateGraphicalContinuousDynamic(graphicalContinuousDynamic, dynamicStartPosition);
  668. graphicalContinuousDynamic.updateSkyBottomLine();
  669. } catch (e) {
  670. // TODO this sometimes fails when the measure range to draw doesn't include all the dynamic's measures, method needs to be adjusted
  671. // see calculateGraphicalContinuousDynamic(), also in MusicSheetCalculator.
  672. }
  673. } else if (graphicalContinuousDynamic.IsVerbal) {
  674. this.calculateGraphicalVerbalContinuousDynamic(graphicalContinuousDynamic, dynamicStartPosition);
  675. } else {
  676. log.warn("This continuous dynamic is not covered");
  677. }
  678. }
  679. }
  680. protected createMetronomeMark(metronomeExpression: InstantaneousTempoExpression): void {
  681. // note: sometimes MeasureNumber is 0 here, e.g. in Christbaum, maybe because of pickup measure (auftakt)
  682. const measureNumber: number = Math.max(metronomeExpression.ParentMultiTempoExpression.SourceMeasureParent.MeasureNumber - 1, 0);
  683. const staffNumber: number = Math.max(metronomeExpression.StaffNumber - 1, 0);
  684. const firstMetronomeMark: boolean = measureNumber === 0 && staffNumber === 0;
  685. const vfStave: Vex.Flow.Stave = (this.graphicalMusicSheet.MeasureList[measureNumber][staffNumber] as VexFlowMeasure).getVFStave();
  686. //vfStave.addModifier(new Vex.Flow.StaveTempo( // needs Vexflow PR
  687. let vexflowDuration: string = "q";
  688. if (metronomeExpression.beatUnit) {
  689. const duration: Fraction = NoteTypeHandler.getNoteDurationFromType(metronomeExpression.beatUnit);
  690. vexflowDuration = VexFlowConverter.durations(duration, false)[0];
  691. }
  692. let yShift: number = this.rules.MetronomeMarkYShift;
  693. let hasExpressionsAboveStaffline: boolean = false;
  694. for (const expression of metronomeExpression.parentMeasure.TempoExpressions) {
  695. const isMetronomeExpression: boolean = expression.InstantaneousTempo?.Enum === TempoEnum.metronomeMark;
  696. if (expression.getPlacementOfFirstEntry() === PlacementEnum.Above &&
  697. !isMetronomeExpression) {
  698. hasExpressionsAboveStaffline = true;
  699. break;
  700. }
  701. }
  702. if (hasExpressionsAboveStaffline) {
  703. yShift -= 1.4;
  704. // TODO improve this with proper skyline / collision detection. unfortunately we don't have a skyline here yet.
  705. // let maxSkylineBeginning: number = 0;
  706. // for (let i = 0; i < skyline.length / 1; i++) { // search in first 3rd, disregard end of measure
  707. // maxSkylineBeginning = Math.max(skyline[i], maxSkylineBeginning);
  708. // }
  709. // console.log('max skyline: ' + maxSkylineBeginning);
  710. }
  711. const skyline: number[] = this.graphicalMusicSheet.MeasureList[0][0].ParentStaffLine.SkyLine;
  712. vfStave.setTempo(
  713. {
  714. bpm: metronomeExpression.TempoInBpm,
  715. dots: metronomeExpression.dotted,
  716. duration: vexflowDuration
  717. },
  718. yShift * unitInPixels);
  719. // -50, -30), 0); //needs Vexflow PR
  720. //.setShiftX(-50);
  721. const xShift: number = firstMetronomeMark ? this.rules.MetronomeMarkXShift * unitInPixels : 0;
  722. (<any>vfStave.getModifiers()[vfStave.getModifiers().length - 1]).setShiftX(
  723. xShift
  724. );
  725. // TODO calculate bounding box of metronome mark instead of hacking skyline to fix lyricist collision
  726. skyline[0] = Math.min(skyline[0], -4.5 + yShift);
  727. // somehow this is called repeatedly in Clementi, so skyline[0] = Math.min instead of -=
  728. }
  729. protected calculateRehearsalMark(measure: SourceMeasure): void {
  730. const rehearsalExpression: RehearsalExpression = measure.rehearsalExpression;
  731. if (!rehearsalExpression) {
  732. return;
  733. }
  734. const firstMeasureNumber: number = this.graphicalMusicSheet.MeasureList[0][0].MeasureNumber; // 0 for pickup, 1 otherwise
  735. const measureNumber: number = Math.max(measure.MeasureNumber - firstMeasureNumber, 0);
  736. const staffNumber: number = 0;
  737. const vfStave: Vex.Flow.Stave = (this.graphicalMusicSheet.MeasureList[measureNumber][staffNumber] as VexFlowMeasure).getVFStave();
  738. const yOffset: number = -this.rules.RehearsalMarkYOffsetDefault - this.rules.RehearsalMarkYOffset;
  739. let xOffset: number = this.rules.RehearsalMarkXOffsetDefault + this.rules.RehearsalMarkXOffset;
  740. if (measure.IsSystemStartMeasure) {
  741. xOffset += this.rules.RehearsalMarkXOffsetSystemStartMeasure;
  742. }
  743. // const section: Vex.Flow.StaveSection = new Vex.Flow.StaveSection(rehearsalExpression.label, vfStave.getX(), yOffset);
  744. // (vfStave as any).modifiers.push(section);
  745. const fontSize: number = this.rules.RehearsalMarkFontSize;
  746. (vfStave as any).setSection(rehearsalExpression.label, yOffset, xOffset, fontSize); // fontSize is an extra argument from VexFlowPatch
  747. }
  748. /**
  749. * Calculate a single OctaveShift for a [[MultiExpression]].
  750. * @param sourceMeasure
  751. * @param multiExpression
  752. * @param measureIndex
  753. * @param staffIndex
  754. */
  755. protected calculateSingleOctaveShift(sourceMeasure: SourceMeasure, multiExpression: MultiExpression, measureIndex: number, staffIndex: number): void {
  756. // calculate absolute Timestamp and startStaffLine (and EndStaffLine if needed)
  757. const octaveShift: OctaveShift = multiExpression.OctaveShiftStart;
  758. const startTimeStamp: Fraction = octaveShift.ParentStartMultiExpression.Timestamp;
  759. const endTimeStamp: Fraction = octaveShift.ParentEndMultiExpression?.Timestamp;
  760. const minMeasureToDrawIndex: number = this.rules.MinMeasureToDrawIndex;
  761. const maxMeasureToDrawIndex: number = this.rules.MaxMeasureToDrawIndex;
  762. let startStaffLine: StaffLine = this.graphicalMusicSheet.MeasureList[measureIndex][staffIndex].ParentStaffLine;
  763. if (!startStaffLine) { // fix for rendering range set. all of these can probably be done cleaner.
  764. startStaffLine = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex].ParentStaffLine;
  765. }
  766. let endMeasure: GraphicalMeasure = undefined;
  767. if (octaveShift.ParentEndMultiExpression) {
  768. endMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(octaveShift.ParentEndMultiExpression.SourceMeasureParent,
  769. staffIndex);
  770. } else {
  771. endMeasure = this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(staffIndex, true); // get last rendered measure
  772. }
  773. if (endMeasure.MeasureNumber > maxMeasureToDrawIndex + 1) { // octaveshift ends in measure not rendered
  774. endMeasure = this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(staffIndex, true);
  775. }
  776. let startMeasure: GraphicalMeasure = undefined;
  777. if (octaveShift.ParentEndMultiExpression) {
  778. startMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(octaveShift.ParentStartMultiExpression.SourceMeasureParent,
  779. staffIndex);
  780. } else {
  781. startMeasure = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex]; // first rendered measure
  782. }
  783. if (startMeasure.MeasureNumber < minMeasureToDrawIndex + 1) { // octaveshift starts before range of measures selected to render
  784. startMeasure = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex]; // first rendered measure
  785. }
  786. if (startMeasure.parentSourceMeasure.measureListIndex < minMeasureToDrawIndex ||
  787. startMeasure.parentSourceMeasure.measureListIndex > maxMeasureToDrawIndex ||
  788. endMeasure.parentSourceMeasure.measureListIndex < minMeasureToDrawIndex ||
  789. endMeasure.parentSourceMeasure.measureListIndex > maxMeasureToDrawIndex) {
  790. // completely out of drawing range, don't draw anything
  791. return;
  792. }
  793. let endStaffLine: StaffLine = endMeasure.ParentStaffLine;
  794. if (!endStaffLine) {
  795. endStaffLine = startStaffLine;
  796. }
  797. if (endMeasure && startStaffLine && endStaffLine) {
  798. // calculate GraphicalOctaveShift and RelativePositions
  799. const graphicalOctaveShift: VexFlowOctaveShift = new VexFlowOctaveShift(octaveShift, startStaffLine.PositionAndShape);
  800. if (!graphicalOctaveShift.startNote) { // fix for rendering range set
  801. let startGse: GraphicalStaffEntry;
  802. for (const gse of startMeasure.staffEntries) {
  803. if (gse) {
  804. startGse = gse;
  805. break;
  806. } // sometimes the first graphical staff entry is undefined, not sure why.
  807. }
  808. if (!startGse) {
  809. return; // couldn't find a start staffentry, don't draw the octave shift
  810. }
  811. graphicalOctaveShift.setStartNote(startGse);
  812. if (!graphicalOctaveShift.startNote) {
  813. return; // couldn't find a start note, don't draw the octave shift
  814. }
  815. }
  816. if (!graphicalOctaveShift.endNote) { // fix for rendering range set
  817. let endGse: GraphicalStaffEntry;
  818. for (let i: number = endMeasure.staffEntries.length - 1; i >= 0; i++) {
  819. // search backwards from end of measure
  820. if (endMeasure.staffEntries[i]) {
  821. endGse = endMeasure.staffEntries[i];
  822. break;
  823. }
  824. }
  825. graphicalOctaveShift.setEndNote(endGse);
  826. if (!graphicalOctaveShift.endNote) {
  827. return;
  828. }
  829. }
  830. // calculate RelativePosition and Dashes
  831. let startStaffEntry: GraphicalStaffEntry = startMeasure.findGraphicalStaffEntryFromTimestamp(startTimeStamp);
  832. if (!startStaffEntry) { // fix for rendering range set
  833. startStaffEntry = startMeasure.staffEntries[0];
  834. }
  835. let endStaffEntry: GraphicalStaffEntry = endMeasure.findGraphicalStaffEntryFromTimestamp(endTimeStamp);
  836. if (!endStaffEntry) { // fix for rendering range set
  837. endStaffEntry = endMeasure.staffEntries[endMeasure.staffEntries.length - 1];
  838. }
  839. graphicalOctaveShift.setStartNote(startStaffEntry);
  840. if (endStaffLine !== startStaffLine) {
  841. graphicalOctaveShift.endsOnDifferentStaffLine = true;
  842. let lastMeasureOfFirstShift: GraphicalMeasure = startStaffLine.Measures[startStaffLine.Measures.length - 1];
  843. if (lastMeasureOfFirstShift === undefined) { // TODO handle this case correctly (when drawUpToMeasureNumber etc set)
  844. lastMeasureOfFirstShift = endMeasure;
  845. }
  846. const lastNoteOfFirstShift: GraphicalStaffEntry = lastMeasureOfFirstShift.staffEntries[lastMeasureOfFirstShift.staffEntries.length - 1];
  847. graphicalOctaveShift.setEndNote(lastNoteOfFirstShift);
  848. const systemsInBetweenCount: number = endStaffLine.ParentMusicSystem.Id - startStaffLine.ParentMusicSystem.Id;
  849. if (systemsInBetweenCount > 0) {
  850. //Loop through the stafflines in between to the end
  851. for (let i: number = startStaffLine.ParentMusicSystem.Id; i < endStaffLine.ParentMusicSystem.Id; i++) {
  852. const idx: number = i + 1;
  853. const nextShiftMusicSystem: MusicSystem = this.musicSystems[idx];
  854. const nextShiftStaffline: StaffLine = nextShiftMusicSystem.StaffLines[staffIndex];
  855. const nextShiftFirstMeasure: GraphicalMeasure = nextShiftStaffline.Measures[0];
  856. // Shift starts on the first measure
  857. const nextOctaveShift: VexFlowOctaveShift = new VexFlowOctaveShift(octaveShift, nextShiftFirstMeasure.PositionAndShape);
  858. if (i < systemsInBetweenCount) {
  859. nextOctaveShift.endsOnDifferentStaffLine = true;
  860. }
  861. let nextShiftLastMeasure: GraphicalMeasure = nextShiftStaffline.Measures[nextShiftStaffline.Measures.length - 1];
  862. const firstNote: GraphicalStaffEntry = nextShiftFirstMeasure.staffEntries[0];
  863. let lastNote: GraphicalStaffEntry = nextShiftLastMeasure.staffEntries[nextShiftLastMeasure.staffEntries.length - 1];
  864. //If the end measure's staffline is the ending staffline, this endMeasure is the end of the shift
  865. if (endMeasure.ParentStaffLine === nextShiftStaffline) {
  866. nextShiftLastMeasure = endMeasure;
  867. lastNote = endStaffEntry;
  868. }
  869. nextOctaveShift.setStartNote(firstNote);
  870. nextOctaveShift.setEndNote(lastNote);
  871. nextShiftStaffline.OctaveShifts.push(nextOctaveShift);
  872. this.calculateOctaveShiftSkyBottomLine(firstNote, lastNote, nextOctaveShift, nextShiftStaffline);
  873. }
  874. }
  875. this.calculateOctaveShiftSkyBottomLine(startStaffEntry, lastNoteOfFirstShift, graphicalOctaveShift, startStaffLine);
  876. } else {
  877. graphicalOctaveShift.setEndNote(endStaffEntry);
  878. this.calculateOctaveShiftSkyBottomLine(startStaffEntry, endStaffEntry, graphicalOctaveShift, startStaffLine);
  879. }
  880. startStaffLine.OctaveShifts.push(graphicalOctaveShift);
  881. } else {
  882. log.warn("End measure or staffLines for octave shift are undefined! This should not happen!");
  883. }
  884. }
  885. protected calculateSinglePedal(sourceMeasure: SourceMeasure, multiExpression: MultiExpression, measureIndex: number, staffIndex: number): void {
  886. // calculate absolute Timestamp and startStaffLine (and EndStaffLine if needed)
  887. const pedal: Pedal = multiExpression.PedalStart;
  888. const startTimeStamp: Fraction = pedal.ParentStartMultiExpression.Timestamp;
  889. const endTimeStamp: Fraction = pedal.ParentEndMultiExpression?.Timestamp;
  890. const minMeasureToDrawIndex: number = this.rules.MinMeasureToDrawIndex;
  891. const maxMeasureToDrawIndex: number = this.rules.MaxMeasureToDrawIndex;
  892. let startStaffLine: StaffLine = this.graphicalMusicSheet.MeasureList[measureIndex][staffIndex].ParentStaffLine;
  893. if (!startStaffLine) { // fix for rendering range set. all of these can probably be done cleaner.
  894. startStaffLine = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex].ParentStaffLine;
  895. }
  896. let endMeasure: GraphicalMeasure = undefined;
  897. if (pedal.ParentEndMultiExpression) {
  898. endMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(pedal.ParentEndMultiExpression.SourceMeasureParent,
  899. staffIndex);
  900. } else {
  901. endMeasure = this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(staffIndex, true); // get last rendered measure
  902. }
  903. if (endMeasure.MeasureNumber > maxMeasureToDrawIndex + 1) { // ends in measure not rendered
  904. endMeasure = this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(staffIndex, true);
  905. }
  906. let startMeasure: GraphicalMeasure = undefined;
  907. if (pedal.ParentEndMultiExpression) {
  908. startMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(pedal.ParentStartMultiExpression.SourceMeasureParent,
  909. staffIndex);
  910. } else {
  911. startMeasure = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex]; // first rendered measure
  912. }
  913. if (startMeasure.MeasureNumber < minMeasureToDrawIndex + 1) { // starts before range of measures selected to render
  914. startMeasure = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex]; // first rendered measure
  915. }
  916. if (startMeasure.parentSourceMeasure.measureListIndex < minMeasureToDrawIndex ||
  917. startMeasure.parentSourceMeasure.measureListIndex > maxMeasureToDrawIndex ||
  918. endMeasure.parentSourceMeasure.measureListIndex < minMeasureToDrawIndex ||
  919. endMeasure.parentSourceMeasure.measureListIndex > maxMeasureToDrawIndex) {
  920. // completely out of drawing range, don't draw anything
  921. return;
  922. }
  923. let endStaffLine: StaffLine = endMeasure.ParentStaffLine;
  924. if (!endStaffLine) {
  925. endStaffLine = startStaffLine;
  926. }
  927. if (endMeasure && startStaffLine && endStaffLine) {
  928. let openEnd: boolean = false;
  929. if (startStaffLine !== endStaffLine) {
  930. openEnd = true;
  931. }
  932. // calculate GraphicalPedal and RelativePositions
  933. const graphicalPedal: VexFlowPedal = new VexFlowPedal(pedal, startStaffLine.PositionAndShape, false, openEnd);
  934. // calculate RelativePosition
  935. let startStaffEntry: GraphicalStaffEntry = startMeasure.findGraphicalStaffEntryFromTimestamp(startTimeStamp);
  936. if (!startStaffEntry) { // fix for rendering range set
  937. startStaffEntry = startMeasure.staffEntries[0];
  938. }
  939. let endStaffEntry: GraphicalStaffEntry = endMeasure.findGraphicalStaffEntryFromTimestamp(endTimeStamp);
  940. if (!endStaffEntry) { // fix for rendering range set
  941. endStaffEntry = endMeasure.staffEntries[endMeasure.staffEntries.length - 1];
  942. // TODO can be undefined if no notes in end measure
  943. }
  944. if(!graphicalPedal.setStartNote(startStaffEntry)){
  945. return;
  946. }
  947. if (endStaffLine !== startStaffLine) {
  948. if(graphicalPedal.pedalSymbol === MusicSymbol.PEDAL_SYMBOL){
  949. graphicalPedal.setEndNote(endStaffEntry);
  950. graphicalPedal.setEndMeasure(endMeasure);
  951. graphicalPedal.ReleaseText = " ";
  952. graphicalPedal.CalculateBoundingBox();
  953. this.calculatePedalSkyBottomLine(graphicalPedal.startVfVoiceEntry, graphicalPedal.endVfVoiceEntry, graphicalPedal, startStaffLine);
  954. const nextPedalFirstMeasure: GraphicalMeasure = endStaffLine.Measures[0];
  955. // pedal starts on the first measure
  956. const nextPedal: VexFlowPedal = new VexFlowPedal(pedal, nextPedalFirstMeasure.PositionAndShape);
  957. const firstNote: GraphicalStaffEntry = nextPedalFirstMeasure.staffEntries[0];
  958. if(!nextPedal.setStartNote(firstNote)){
  959. return;
  960. }
  961. nextPedal.setEndNote(endStaffEntry);
  962. graphicalPedal.setEndMeasure(endMeasure);
  963. endStaffLine.Pedals.push(nextPedal);
  964. nextPedal.CalculateBoundingBox();
  965. nextPedal.DepressText = " ";
  966. this.calculatePedalSkyBottomLine(nextPedal.startVfVoiceEntry, nextPedal.endVfVoiceEntry, nextPedal, endStaffLine);
  967. } else {
  968. let lastMeasureOfFirstShift: GraphicalMeasure = startStaffLine.Measures[startStaffLine.Measures.length - 1];
  969. if (lastMeasureOfFirstShift === undefined) { // TODO handle this case correctly (when drawUpToMeasureNumber etc set)
  970. lastMeasureOfFirstShift = endMeasure;
  971. }
  972. const lastNoteOfFirstShift: GraphicalStaffEntry = lastMeasureOfFirstShift.staffEntries[lastMeasureOfFirstShift.staffEntries.length - 1];
  973. graphicalPedal.setEndNote(lastNoteOfFirstShift);
  974. graphicalPedal.setEndMeasure(endMeasure);
  975. graphicalPedal.ChangeEnd = false;
  976. const systemsInBetweenCount: number = endStaffLine.ParentMusicSystem.Id - startStaffLine.ParentMusicSystem.Id;
  977. if (systemsInBetweenCount > 0) {
  978. //Loop through the stafflines in between to the end
  979. let currentCount: number = 1;
  980. for (let i: number = startStaffLine.ParentMusicSystem.Id; i < endStaffLine.ParentMusicSystem.Id; i++) {
  981. const nextPedalMusicSystem: MusicSystem = this.musicSystems[i + 1];
  982. const nextPedalStaffline: StaffLine = nextPedalMusicSystem.StaffLines[staffIndex];
  983. const nextPedalFirstMeasure: GraphicalMeasure = nextPedalStaffline.Measures[0];
  984. let nextOpenEnd: boolean = false;
  985. let nextChangeEndFromParent: boolean = false;
  986. if (currentCount < systemsInBetweenCount) {
  987. nextOpenEnd = true;
  988. } else {
  989. nextChangeEndFromParent = true;
  990. }
  991. currentCount++;
  992. // pedal starts on the first measure
  993. const nextPedal: VexFlowPedal = new VexFlowPedal(pedal, nextPedalFirstMeasure.PositionAndShape, true, nextOpenEnd);
  994. nextPedal.ChangeBegin = false;
  995. if(nextChangeEndFromParent){
  996. nextPedal.ChangeEnd = pedal.ChangeEnd;
  997. } else {
  998. nextPedal.ChangeEnd = false;
  999. }
  1000. let nextPedalLastMeasure: GraphicalMeasure = nextPedalStaffline.Measures[nextPedalStaffline.Measures.length - 1];
  1001. const firstNote: GraphicalStaffEntry = nextPedalFirstMeasure.staffEntries[0];
  1002. let lastNote: GraphicalStaffEntry = nextPedalLastMeasure.staffEntries[nextPedalLastMeasure.staffEntries.length - 1];
  1003. //If the end measure's staffline is the ending staffline, this endMeasure is the end of the pedal
  1004. if (endMeasure.ParentStaffLine === nextPedalStaffline) {
  1005. nextPedalLastMeasure = endMeasure;
  1006. lastNote = endStaffEntry;
  1007. }
  1008. if(!nextPedal.setStartNote(firstNote)){
  1009. break;
  1010. }
  1011. nextPedal.setEndNote(lastNote);
  1012. graphicalPedal.setEndMeasure(endMeasure);
  1013. nextPedalStaffline.Pedals.push(nextPedal);
  1014. nextPedal.CalculateBoundingBox();
  1015. this.calculatePedalSkyBottomLine(nextPedal.startVfVoiceEntry, nextPedal.endVfVoiceEntry, nextPedal, nextPedalStaffline);
  1016. }
  1017. }
  1018. graphicalPedal.CalculateBoundingBox();
  1019. this.calculatePedalSkyBottomLine(graphicalPedal.startVfVoiceEntry, graphicalPedal.endVfVoiceEntry, graphicalPedal, startStaffLine);
  1020. }
  1021. } else {
  1022. graphicalPedal.setEndNote(endStaffEntry);
  1023. graphicalPedal.setEndMeasure(endMeasure);
  1024. graphicalPedal.CalculateBoundingBox();
  1025. this.calculatePedalSkyBottomLine(graphicalPedal.startVfVoiceEntry, graphicalPedal.endVfVoiceEntry, graphicalPedal, startStaffLine);
  1026. }
  1027. startStaffLine.Pedals.push(graphicalPedal);
  1028. } else {
  1029. log.warn("End measure or staffLines for pedal are undefined! This should not happen!");
  1030. }
  1031. }
  1032. protected calculateSingleWavyLine(sourceMeasure: SourceMeasure, multiExpression: MultiExpression, measureIndex: number, staffIndex: number): void {
  1033. // calculate absolute Timestamp and startStaffLine (and EndStaffLine if needed)
  1034. const wavyLine: WavyLine = multiExpression.WavyLineStart;
  1035. const startTimeStamp: Fraction = wavyLine.ParentStartMultiExpression.Timestamp;
  1036. const endTimeStamp: Fraction = wavyLine.ParentEndMultiExpression?.Timestamp;
  1037. const minMeasureToDrawIndex: number = this.rules.MinMeasureToDrawIndex;
  1038. const maxMeasureToDrawIndex: number = this.rules.MaxMeasureToDrawIndex;
  1039. let startStaffLine: StaffLine = this.graphicalMusicSheet.MeasureList[measureIndex][staffIndex].ParentStaffLine;
  1040. if (!startStaffLine) { // fix for rendering range set. all of these can probably be done cleaner.
  1041. startStaffLine = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex].ParentStaffLine;
  1042. }
  1043. let endMeasure: GraphicalMeasure = undefined;
  1044. if (wavyLine.ParentEndMultiExpression) {
  1045. endMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(wavyLine.ParentEndMultiExpression.SourceMeasureParent,
  1046. staffIndex);
  1047. } else {
  1048. endMeasure = this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(staffIndex, true); // get last rendered measure
  1049. }
  1050. if (endMeasure.MeasureNumber > maxMeasureToDrawIndex + 1) { // ends in measure not rendered
  1051. endMeasure = this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(staffIndex, true);
  1052. }
  1053. let startMeasure: GraphicalMeasure = undefined;
  1054. if (wavyLine.ParentEndMultiExpression) {
  1055. startMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(wavyLine.ParentStartMultiExpression.SourceMeasureParent,
  1056. staffIndex);
  1057. } else {
  1058. startMeasure = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex]; // first rendered measure
  1059. }
  1060. if (startMeasure.MeasureNumber < minMeasureToDrawIndex + 1) { // starts before range of measures selected to render
  1061. startMeasure = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex]; // first rendered measure
  1062. }
  1063. if (startMeasure.parentSourceMeasure.measureListIndex < minMeasureToDrawIndex ||
  1064. startMeasure.parentSourceMeasure.measureListIndex > maxMeasureToDrawIndex ||
  1065. endMeasure.parentSourceMeasure.measureListIndex < minMeasureToDrawIndex ||
  1066. endMeasure.parentSourceMeasure.measureListIndex > maxMeasureToDrawIndex) {
  1067. // completely out of drawing range, don't draw anything
  1068. return;
  1069. }
  1070. let endStaffLine: StaffLine = endMeasure.ParentStaffLine;
  1071. if (!endStaffLine) {
  1072. endStaffLine = startStaffLine;
  1073. }
  1074. if (endMeasure && startStaffLine && endStaffLine) {
  1075. const graphicalWavyLine: VexflowVibratoBracket = new VexflowVibratoBracket(wavyLine, startStaffLine.PositionAndShape, startMeasure.ParentStaff.isTab);
  1076. // calculate RelativePosition
  1077. let startStaffEntry: GraphicalStaffEntry = startMeasure.findGraphicalStaffEntryFromTimestamp(startTimeStamp);
  1078. if (!startStaffEntry) { // fix for rendering range set
  1079. startStaffEntry = startMeasure.staffEntries[0];
  1080. }
  1081. let endStaffEntry: GraphicalStaffEntry = endMeasure.findGraphicalStaffEntryFromTimestamp(endTimeStamp);
  1082. if (!endStaffEntry) { // fix for rendering range set
  1083. endStaffEntry = endMeasure.staffEntries[endMeasure.staffEntries.length - 1];
  1084. }
  1085. graphicalWavyLine.setStartNote(startStaffEntry);
  1086. if (endStaffLine !== startStaffLine) {
  1087. let lastMeasureOfFirstShift: GraphicalMeasure = startStaffLine.Measures[startStaffLine.Measures.length - 1];
  1088. if (lastMeasureOfFirstShift === undefined) { // TODO handle this case correctly (when drawUpToMeasureNumber etc set)
  1089. lastMeasureOfFirstShift = endMeasure;
  1090. }
  1091. const lastNoteOfFirstShift: GraphicalStaffEntry = lastMeasureOfFirstShift.staffEntries[lastMeasureOfFirstShift.staffEntries.length - 1];
  1092. graphicalWavyLine.setEndNote(lastNoteOfFirstShift);
  1093. const systemsInBetweenCount: number = endStaffLine.ParentMusicSystem.Id - startStaffLine.ParentMusicSystem.Id;
  1094. if (systemsInBetweenCount > 0) {
  1095. for (let i: number = startStaffLine.ParentMusicSystem.Id; i < endStaffLine.ParentMusicSystem.Id; i++) {
  1096. const nextWavyLineMusicSystem: MusicSystem = this.musicSystems[i + 1];
  1097. const nextWavyLineStaffline: StaffLine = nextWavyLineMusicSystem.StaffLines[staffIndex];
  1098. const nextWavyLineFirstMeasure: GraphicalMeasure = nextWavyLineStaffline.Measures[0];
  1099. // vibrato starts on the first measure
  1100. const nextWavyLine: VexflowVibratoBracket = new VexflowVibratoBracket(wavyLine, nextWavyLineFirstMeasure.PositionAndShape,
  1101. nextWavyLineStaffline.ParentStaff.isTab);
  1102. let nextWavyLineLastMeasure: GraphicalMeasure = nextWavyLineStaffline.Measures[nextWavyLineStaffline.Measures.length - 1];
  1103. const firstNote: GraphicalStaffEntry = nextWavyLineFirstMeasure.staffEntries[0];
  1104. let lastNote: GraphicalStaffEntry = nextWavyLineLastMeasure.staffEntries[nextWavyLineLastMeasure.staffEntries.length - 1];
  1105. //If the end measure's is the ending staffline, this endMeasure is the end of the wavy line
  1106. if (endMeasure.ParentStaffLine === nextWavyLineStaffline) {
  1107. nextWavyLineLastMeasure = endMeasure;
  1108. lastNote = endStaffEntry;
  1109. }
  1110. nextWavyLine.setStartNote(firstNote);
  1111. nextWavyLine.setEndNote(lastNote);
  1112. nextWavyLineStaffline.WavyLines.push(nextWavyLine);
  1113. nextWavyLine.CalculateBoundingBox();
  1114. this.calculateWavyLineSkyBottomLine(nextWavyLine.startVfVoiceEntry, nextWavyLine.endVfVoiceEntry, nextWavyLine, nextWavyLineStaffline);
  1115. }
  1116. }
  1117. graphicalWavyLine.CalculateBoundingBox();
  1118. this.calculateWavyLineSkyBottomLine(graphicalWavyLine.startVfVoiceEntry, graphicalWavyLine.endVfVoiceEntry, graphicalWavyLine, startStaffLine);
  1119. } else {
  1120. graphicalWavyLine.setEndNote(endStaffEntry);
  1121. graphicalWavyLine.CalculateBoundingBox();
  1122. this.calculateWavyLineSkyBottomLine(graphicalWavyLine.startVfVoiceEntry, graphicalWavyLine.endVfVoiceEntry, graphicalWavyLine, startStaffLine);
  1123. }
  1124. startStaffLine.WavyLines.push(graphicalWavyLine);
  1125. } else {
  1126. log.warn("End measure or staffLines for wavy line are undefined! This should not happen!");
  1127. }
  1128. }
  1129. private calculateWavyLineSkyBottomLine(startVfVoiceEntry: VexFlowVoiceEntry, endVfVoiceEntry: VexFlowVoiceEntry,
  1130. vfVibratoBracket: VexflowVibratoBracket, parentStaffline: StaffLine): void {
  1131. const startStave: Vex.Flow.Stave = vfVibratoBracket.startNote.getStave();
  1132. const endStave: Vex.Flow.Stave = vfVibratoBracket.endNote.getStave();
  1133. //In VF Line positions, need to negate for our units
  1134. const highestVFTopTextPosition: number = Math.max(
  1135. startStave.options.top_text_position,
  1136. endStave.options.top_text_position
  1137. );
  1138. //Whichever is higher, set the other to match
  1139. startStave.options.top_text_position = highestVFTopTextPosition;
  1140. endStave.options.top_text_position = highestVFTopTextPosition;
  1141. let headroom: number = -highestVFTopTextPosition;
  1142. let trillStartX: number = 0;
  1143. let trillEndX: number = 0;
  1144. let trillSkyline: number = Infinity;
  1145. let trillWavyLineBottom: number = Infinity;
  1146. const TRILL_HEIGHT: number = 1.85;
  1147. let startX: number = startVfVoiceEntry.PositionAndShape.AbsolutePosition.x + startVfVoiceEntry.PositionAndShape.BorderLeft;
  1148. if (startVfVoiceEntry.parentVoiceEntry?.OrnamentContainer?.GetOrnament === OrnamentEnum.Trill) {
  1149. trillStartX = startX;
  1150. //Width of trill mark
  1151. startX += 2;
  1152. trillEndX = startX;
  1153. //Since the trill mark is not managed or calculated by our bounding boxes, we have to get the location this way
  1154. //Also at this point the skyline has already been updated with the trill mark. So we can't determine if it should go lower
  1155. //Need to trust Vexflow later on, unless the wavy line must be rendered higher
  1156. trillSkyline = parentStaffline.SkyBottomLineCalculator.getSkyLineMinInRange(trillStartX, trillEndX);
  1157. //height of the trill mark
  1158. trillWavyLineBottom = trillSkyline + TRILL_HEIGHT;
  1159. }
  1160. let stopX: number = undefined;
  1161. //If the end of the line is the last note in the measure, go all the way to the end of the stave
  1162. if(vfVibratoBracket.ToEndOfStopStave) {
  1163. //vexflow backs off by 1 unit (10 pixels) from stave edge
  1164. stopX = endVfVoiceEntry.parentStaffEntry.parentMeasure.PositionAndShape.AbsolutePosition.x +
  1165. endVfVoiceEntry.parentStaffEntry.parentMeasure.PositionAndShape.BorderRight - 1;
  1166. } else {
  1167. stopX = endVfVoiceEntry.PositionAndShape.AbsolutePosition.x + endVfVoiceEntry.PositionAndShape.BorderRight;
  1168. //Take into account in-staff clefs associated with the staff entry (they modify the bounding box position)
  1169. const vfClefBefore: Vex.Flow.ClefNote = (endVfVoiceEntry.parentStaffEntry as VexFlowStaffEntry).vfClefBefore;
  1170. if (vfClefBefore) {
  1171. const clefWidth: number = vfClefBefore.getWidth() / 10;
  1172. stopX += clefWidth;
  1173. }
  1174. }
  1175. headroom = parentStaffline.SkyBottomLineCalculator.getSkyLineMinInRange(startX, stopX);
  1176. if (headroom === Infinity) { // will cause Vexflow error
  1177. return;
  1178. }
  1179. //If somewhere in our wavy line path we have to render higher than where the trill mark is set...
  1180. if (headroom < trillSkyline) {
  1181. startStave.options.top_text_position = -headroom;
  1182. endStave.options.top_text_position = -headroom;
  1183. //A decent enough approximation. Better than recalculating via Canvas or SVG sampling
  1184. parentStaffline.SkyBottomLineCalculator.updateSkyLineInRange(trillStartX, trillEndX, headroom - TRILL_HEIGHT);
  1185. } else { //Else just render where Vexflow has set the trill mark
  1186. vfVibratoBracket.line = -trillWavyLineBottom;
  1187. headroom = trillWavyLineBottom;
  1188. }
  1189. //Update skyline to include height of the wavy line
  1190. headroom -= vfVibratoBracket.PositionAndShape.Size.height;
  1191. parentStaffline.SkyBottomLineCalculator.updateSkyLineInRange(startX, stopX, headroom);
  1192. }
  1193. private calculatePedalSkyBottomLine(startVfVoiceEntry: VexFlowVoiceEntry, endVfVoiceEntry: VexFlowVoiceEntry,
  1194. vfPedal: VexFlowPedal, parentStaffline: StaffLine): void {
  1195. let endBbox: BoundingBox = endVfVoiceEntry?.PositionAndShape;
  1196. if (!endBbox) {
  1197. endBbox = vfPedal.endMeasure.PositionAndShape;
  1198. }
  1199. //Just for shorthand. Easier readability below
  1200. const PEDAL_STYLES_ENUM: any = Vex.Flow.PedalMarking.Styles;
  1201. const pedalMarking: any = vfPedal.getPedalMarking();
  1202. //VF adds 3 lines to whatever the pedal line is set to.
  1203. //VF also measures from the bottom line, whereas our bottom line is from the top staff line
  1204. const yLineForPedalMarking: number = (pedalMarking.line + 3 + (parentStaffline.StaffLines.length - 1));
  1205. //VF Uses a margin offset for rendering. Take this into account
  1206. const pedalMarkingMarginXOffset: number = pedalMarking.render_options.text_margin_right / 10;
  1207. //TODO: Most of this should be in the bounding box calculation
  1208. let startX: number = startVfVoiceEntry.PositionAndShape.AbsolutePosition.x - pedalMarkingMarginXOffset;
  1209. if (pedalMarking.style === PEDAL_STYLES_ENUM.MIXED ||
  1210. pedalMarking.style === PEDAL_STYLES_ENUM.MIXED_OPEN_END ||
  1211. pedalMarking.style === PEDAL_STYLES_ENUM.TEXT) {
  1212. //Accomodate the Ped. sign
  1213. startX -= 1;
  1214. }
  1215. let stopX: number = undefined;
  1216. let footroom: number = (parentStaffline.StaffLines.length - 1);
  1217. //Find the highest foot room in our staffline
  1218. for (const otherPedal of parentStaffline.Pedals) {
  1219. const vfOtherPedal: VexFlowPedal = otherPedal as VexFlowPedal;
  1220. const otherPedalMarking: any = vfOtherPedal.getPedalMarking();
  1221. const yLineForOtherPedalMarking: number = (otherPedalMarking.line + 3 + (parentStaffline.StaffLines.length - 1));
  1222. footroom = Math.max(yLineForOtherPedalMarking, footroom);
  1223. }
  1224. //We have the two seperate symbols, with two bounding boxes
  1225. if (vfPedal.EndSymbolPositionAndShape) {
  1226. const symbolHalfHeight: number = pedalMarking.render_options.glyph_point_size / 20;
  1227. //Width of the Ped. symbol
  1228. stopX = startX + 3.4;
  1229. const startX2: number = endBbox.AbsolutePosition.x - pedalMarkingMarginXOffset;
  1230. //Width of * symbol
  1231. const stopX2: number = startX2 + 1.5;
  1232. footroom = Math.max(parentStaffline.SkyBottomLineCalculator.getBottomLineMaxInRange(startX, stopX), footroom);
  1233. footroom = Math.max(yLineForPedalMarking + symbolHalfHeight * 2, footroom);
  1234. const footroom2: number = parentStaffline.SkyBottomLineCalculator.getBottomLineMaxInRange(startX2, stopX2);
  1235. //If Depress text is set, means we are not rendering the begin label (we are just rendering the end one)
  1236. if (!vfPedal.DepressText) {
  1237. footroom = Math.max(footroom, footroom2);
  1238. }
  1239. vfPedal.setLine(footroom - 3 - (parentStaffline.StaffLines.length - 1));
  1240. parentStaffline.SkyBottomLineCalculator.updateBottomLineInRange(startX, stopX, footroom + symbolHalfHeight);
  1241. parentStaffline.SkyBottomLineCalculator.updateBottomLineInRange(startX2, stopX2, footroom + symbolHalfHeight);
  1242. } else {
  1243. const bracketHeight: number = pedalMarking.render_options.bracket_height / 10;
  1244. if(pedalMarking.EndsStave){
  1245. if(endVfVoiceEntry){
  1246. stopX = endVfVoiceEntry.parentStaffEntry.parentMeasure.PositionAndShape.AbsolutePosition.x +
  1247. endVfVoiceEntry.parentStaffEntry.parentMeasure.PositionAndShape.Size.width - pedalMarkingMarginXOffset;
  1248. } else {
  1249. stopX = endBbox.AbsolutePosition.x + endBbox.Size.width;
  1250. }
  1251. } else {
  1252. switch (pedalMarking.style) {
  1253. case PEDAL_STYLES_ENUM.BRACKET_OPEN_END:
  1254. case PEDAL_STYLES_ENUM.BRACKET_OPEN_BOTH:
  1255. case PEDAL_STYLES_ENUM.MIXED_OPEN_END:
  1256. stopX = endBbox.AbsolutePosition.x + endBbox.BorderRight - pedalMarkingMarginXOffset;
  1257. break;
  1258. default:
  1259. stopX = endBbox.AbsolutePosition.x + endBbox.BorderLeft - pedalMarkingMarginXOffset;
  1260. break;
  1261. }
  1262. }
  1263. //Take into account in-staff clefs associated with the staff entry (they modify the bounding box position)
  1264. const vfClefBefore: Vex.Flow.ClefNote = (endVfVoiceEntry?.parentStaffEntry as VexFlowStaffEntry)?.vfClefBefore;
  1265. if (vfClefBefore) {
  1266. const clefWidth: number = vfClefBefore.getWidth() / 10;
  1267. stopX += clefWidth;
  1268. }
  1269. footroom = Math.max(parentStaffline.SkyBottomLineCalculator.getBottomLineMaxInRange(startX, stopX), footroom);
  1270. if (footroom === Infinity) { // will cause Vexflow error
  1271. return;
  1272. }
  1273. //Whatever is currently lower - the set render height of the begin vf stave, the set render height of the end vf stave,
  1274. //or the bottom line. Use that as the render height of both staves
  1275. footroom = Math.max(footroom, yLineForPedalMarking + bracketHeight);
  1276. vfPedal.setLine(footroom - 3 - (parentStaffline.StaffLines.length - 1));
  1277. if (startX > stopX) { // TODO hotfix for skybottomlinecalculator after pedal no endNote fix
  1278. const newStart: number = stopX;
  1279. stopX = startX;
  1280. startX = newStart;
  1281. }
  1282. parentStaffline.SkyBottomLineCalculator.updateBottomLineInRange(startX, stopX, footroom + bracketHeight);
  1283. }
  1284. //If our current pedal is below the other pedals in this staffline, set them all to this height
  1285. for (const otherPedal of parentStaffline.Pedals) {
  1286. const vfOtherPedal: VexFlowPedal = otherPedal as VexFlowPedal;
  1287. const otherPedalMarking: any = vfOtherPedal.getPedalMarking();
  1288. const yLineForOtherPedalMarking: number = (otherPedalMarking.line + 3 + (parentStaffline.StaffLines.length - 1));
  1289. //Only do these changes if current footroom is higher
  1290. if(footroom > yLineForOtherPedalMarking) {
  1291. const otherPedalMarkingMarginXOffset: number = otherPedalMarking.render_options.text_margin_right / 10;
  1292. const otherPedalStartX: number = vfOtherPedal.startVfVoiceEntry.PositionAndShape.AbsolutePosition.x - otherPedalMarkingMarginXOffset;
  1293. let otherPedalStopX: number = undefined;
  1294. vfOtherPedal.setLine(footroom - 3 - (parentStaffline.StaffLines.length - 1));
  1295. let otherPedalEndBBox: BoundingBox = vfOtherPedal.endVfVoiceEntry?.PositionAndShape;
  1296. if (!otherPedalEndBBox) {
  1297. otherPedalEndBBox = vfOtherPedal.endMeasure.PositionAndShape;
  1298. }
  1299. if (vfOtherPedal.EndSymbolPositionAndShape) {
  1300. const otherSymbolHalfHeight: number = pedalMarking.render_options.glyph_point_size / 20;
  1301. //Width of the Ped. symbol
  1302. otherPedalStopX = otherPedalStartX + 3.4;
  1303. const otherPedalStartX2: number = otherPedalEndBBox.AbsolutePosition.x - otherPedalMarkingMarginXOffset;
  1304. //Width of * symbol
  1305. const otherPedalStopX2: number = otherPedalStartX2 + 1.5;
  1306. parentStaffline.SkyBottomLineCalculator.updateBottomLineInRange(otherPedalStartX, otherPedalStopX, footroom + otherSymbolHalfHeight);
  1307. parentStaffline.SkyBottomLineCalculator.updateBottomLineInRange(otherPedalStartX2, otherPedalStopX2, footroom + otherSymbolHalfHeight);
  1308. } else {
  1309. const otherPedalBracketHeight: number = otherPedalMarking.render_options.bracket_height / 10;
  1310. if(otherPedalMarking.EndsStave){
  1311. otherPedalStopX = otherPedalEndBBox.AbsolutePosition.x + otherPedalEndBBox.Size.width - otherPedalMarkingMarginXOffset;
  1312. } else {
  1313. switch (pedalMarking.style) {
  1314. case PEDAL_STYLES_ENUM.BRACKET_OPEN_END:
  1315. case PEDAL_STYLES_ENUM.BRACKET_OPEN_BOTH:
  1316. case PEDAL_STYLES_ENUM.MIXED_OPEN_END:
  1317. otherPedalStopX = otherPedalEndBBox.AbsolutePosition.x + otherPedalEndBBox.BorderRight - otherPedalMarkingMarginXOffset;
  1318. break;
  1319. default:
  1320. otherPedalStopX = otherPedalEndBBox.AbsolutePosition.x + otherPedalEndBBox.BorderLeft - otherPedalMarkingMarginXOffset;
  1321. break;
  1322. }
  1323. }
  1324. //Take into account in-staff clefs associated with the staff entry (they modify the bounding box position)
  1325. const vfOtherClefBefore: Vex.Flow.ClefNote = (vfOtherPedal.endVfVoiceEntry?.parentStaffEntry as VexFlowStaffEntry)?.vfClefBefore;
  1326. if (vfOtherClefBefore) {
  1327. const otherClefWidth: number = vfOtherClefBefore.getWidth() / 10;
  1328. otherPedalStopX += otherClefWidth;
  1329. }
  1330. parentStaffline.SkyBottomLineCalculator.updateBottomLineInRange(otherPedalStartX, otherPedalStopX, footroom + otherPedalBracketHeight);
  1331. }
  1332. }
  1333. }
  1334. }
  1335. private calculateOctaveShiftSkyBottomLine(startStaffEntry: GraphicalStaffEntry, endStaffEntry: GraphicalStaffEntry,
  1336. vfOctaveShift: VexFlowOctaveShift, parentStaffline: StaffLine): void {
  1337. let startXOffset: number = startStaffEntry.PositionAndShape.Size.width;
  1338. let endXOffset: number = endStaffEntry.PositionAndShape.Size.width;
  1339. //Vexflow renders differently with rests
  1340. if (startStaffEntry.hasOnlyRests()) {
  1341. startXOffset = -startXOffset;
  1342. } else {
  1343. startXOffset /= 2;
  1344. }
  1345. if (!endStaffEntry.hasOnlyRests()) {
  1346. endXOffset /= 2;
  1347. } else {
  1348. endXOffset *= 2;
  1349. }
  1350. if (startStaffEntry === endStaffEntry) {
  1351. endXOffset *= 2;
  1352. }
  1353. const startX: number = startStaffEntry.PositionAndShape.AbsolutePosition.x - startXOffset;
  1354. const stopX: number = endStaffEntry.PositionAndShape.AbsolutePosition.x + endXOffset;
  1355. vfOctaveShift.PositionAndShape.Size.width = startX - stopX;
  1356. const textBracket: Vex.Flow.TextBracket = vfOctaveShift.getTextBracket();
  1357. const fontSize: number = (textBracket as any).font.size / 10;
  1358. if ((<any>textBracket).position === Vex.Flow.TextBracket.Positions.TOP) {
  1359. const headroom: number = Math.ceil(parentStaffline.SkyBottomLineCalculator.getSkyLineMinInRange(startX, stopX));
  1360. if (headroom === Infinity) { // will cause Vexflow error
  1361. return;
  1362. }
  1363. (textBracket.start.getStave().options as any).top_text_position = Math.abs(headroom);
  1364. parentStaffline.SkyBottomLineCalculator.updateSkyLineInRange(startX, stopX, headroom - fontSize * 2);
  1365. } else {
  1366. const footroom: number = parentStaffline.SkyBottomLineCalculator.getBottomLineMaxInRange(startX, stopX);
  1367. if (footroom === Infinity) { // will cause Vexflow error
  1368. return;
  1369. }
  1370. (textBracket.start.getStave().options as any).bottom_text_position = footroom;
  1371. if (startStaffEntry.parentMeasure !== endStaffEntry.parentMeasure) {
  1372. (textBracket.stop.getStave().options as any).bottom_text_position = footroom;
  1373. }
  1374. //Vexflow positions top vs. bottom text in a slightly inconsistent way it seems
  1375. parentStaffline.SkyBottomLineCalculator.updateBottomLineInRange(startX, stopX, footroom + fontSize * 1.5);
  1376. }
  1377. }
  1378. /**
  1379. * Calculate all the textual and symbolic [[RepetitionInstruction]]s (e.g. dal segno) for a single [[SourceMeasure]].
  1380. * @param repetitionInstruction
  1381. * @param measureIndex
  1382. */
  1383. protected calculateWordRepetitionInstruction(repetitionInstruction: RepetitionInstruction, measureIndex: number): void {
  1384. // find first visible StaffLine
  1385. let uppermostMeasure: VexFlowMeasure = undefined;
  1386. const measures: VexFlowMeasure[] = <VexFlowMeasure[]>this.graphicalMusicSheet.MeasureList[measureIndex];
  1387. for (let idx: number = 0, len: number = measures.length; idx < len; ++idx) {
  1388. const graphicalMeasure: VexFlowMeasure = measures[idx];
  1389. if (graphicalMeasure && graphicalMeasure.ParentStaffLine && graphicalMeasure.ParentStaff.ParentInstrument.Visible) {
  1390. uppermostMeasure = <VexFlowMeasure>graphicalMeasure;
  1391. break;
  1392. }
  1393. }
  1394. // ToDo: feature/Repetitions
  1395. // now create corresponding graphical symbol or Text in VexFlow:
  1396. // use top measure and staffline for positioning.
  1397. if (uppermostMeasure) {
  1398. uppermostMeasure.addWordRepetition(repetitionInstruction);
  1399. }
  1400. }
  1401. /**
  1402. * Re-adjust the x positioning of expressions. Update the skyline afterwards
  1403. */
  1404. protected calculateExpressionAlignements(): void {
  1405. for (const musicSystem of this.musicSystems) {
  1406. for (const staffLine of musicSystem.StaffLines) {
  1407. try {
  1408. (<VexFlowStaffLine>staffLine).AlignmentManager.alignDynamicExpressions();
  1409. staffLine.AbstractExpressions.forEach(ae => {
  1410. ae.updateSkyBottomLine();
  1411. });
  1412. } catch (e) {
  1413. // TODO still necessary when calculation of expression fails, see calculateDynamicExpressionsForMultiExpression()
  1414. // see calculateGraphicalContinuousDynamic(), also in MusicSheetCalculator.
  1415. }
  1416. }
  1417. }
  1418. }
  1419. /**
  1420. * Check if the tied graphical note belongs to any beams or tuplets and react accordingly.
  1421. * @param tiedGraphicalNote
  1422. * @param beams
  1423. * @param activeClef
  1424. * @param octaveShiftValue
  1425. * @param graphicalStaffEntry
  1426. * @param duration
  1427. * @param openTie
  1428. * @param isLastTieNote
  1429. */
  1430. protected handleTiedGraphicalNote(tiedGraphicalNote: GraphicalNote, beams: Beam[], activeClef: ClefInstruction,
  1431. octaveShiftValue: OctaveEnum, graphicalStaffEntry: GraphicalStaffEntry, duration: Fraction,
  1432. openTie: Tie, isLastTieNote: boolean): void {
  1433. return;
  1434. }
  1435. /**
  1436. * Is called if a note is part of a beam.
  1437. * @param graphicalNote
  1438. * @param beam
  1439. * @param openBeams a list of all currently open beams
  1440. */
  1441. protected handleBeam(graphicalNote: GraphicalNote, beam: Beam, openBeams: Beam[]): void {
  1442. (graphicalNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure).handleBeam(graphicalNote, beam);
  1443. }
  1444. protected handleVoiceEntryLyrics(voiceEntry: VoiceEntry, graphicalStaffEntry: GraphicalStaffEntry, lyricWords: LyricWord[]): void {
  1445. voiceEntry.LyricsEntries.forEach((key: number, lyricsEntry: LyricsEntry) => {
  1446. const graphicalLyricEntry: GraphicalLyricEntry = new GraphicalLyricEntry(lyricsEntry,
  1447. graphicalStaffEntry,
  1448. this.rules.LyricsHeight,
  1449. this.rules.StaffHeight);
  1450. graphicalStaffEntry.LyricsEntries.push(graphicalLyricEntry);
  1451. // create corresponding GraphicalLabel
  1452. const graphicalLabel: GraphicalLabel = graphicalLyricEntry.GraphicalLabel;
  1453. graphicalLabel.setLabelPositionAndShapeBorders();
  1454. if (lyricsEntry.Word) {
  1455. const lyricsEntryIndex: number = lyricsEntry.Word.Syllables.indexOf(lyricsEntry);
  1456. let index: number = lyricWords.indexOf(lyricsEntry.Word);
  1457. if (index === -1) {
  1458. lyricWords.push(lyricsEntry.Word);
  1459. index = lyricWords.indexOf(lyricsEntry.Word);
  1460. }
  1461. if (this.graphicalLyricWords.length === 0 || index > this.graphicalLyricWords.length - 1) {
  1462. const graphicalLyricWord: GraphicalLyricWord = new GraphicalLyricWord(lyricsEntry.Word);
  1463. graphicalLyricEntry.ParentLyricWord = graphicalLyricWord;
  1464. graphicalLyricWord.GraphicalLyricsEntries[lyricsEntryIndex] = graphicalLyricEntry;
  1465. this.graphicalLyricWords.push(graphicalLyricWord);
  1466. } else {
  1467. const graphicalLyricWord: GraphicalLyricWord = this.graphicalLyricWords[index];
  1468. graphicalLyricEntry.ParentLyricWord = graphicalLyricWord;
  1469. graphicalLyricWord.GraphicalLyricsEntries[lyricsEntryIndex] = graphicalLyricEntry;
  1470. if (graphicalLyricWord.isFilled()) {
  1471. lyricWords.splice(index, 1);
  1472. this.graphicalLyricWords.splice(this.graphicalLyricWords.indexOf(graphicalLyricWord), 1);
  1473. }
  1474. }
  1475. }
  1476. });
  1477. }
  1478. protected handleVoiceEntryOrnaments(ornamentContainer: OrnamentContainer, voiceEntry: VoiceEntry, graphicalStaffEntry: GraphicalStaffEntry): void {
  1479. return;
  1480. }
  1481. /**
  1482. * Add articulations to the given vexflow staff entry.
  1483. * @param articulations
  1484. * @param voiceEntry
  1485. * @param graphicalStaffEntry
  1486. */
  1487. protected handleVoiceEntryArticulations(articulations: Articulation[],
  1488. voiceEntry: VoiceEntry, staffEntry: GraphicalStaffEntry): void {
  1489. // uncomment this when implementing:
  1490. // let vfse: VexFlowStaffEntry = (graphicalStaffEntry as VexFlowStaffEntry);
  1491. return;
  1492. }
  1493. /**
  1494. * Add technical instructions to the given vexflow staff entry.
  1495. * @param technicalInstructions
  1496. * @param voiceEntry
  1497. * @param staffEntry
  1498. */
  1499. protected handleVoiceEntryTechnicalInstructions(technicalInstructions: TechnicalInstruction[],
  1500. voiceEntry: VoiceEntry, staffEntry: GraphicalStaffEntry): void {
  1501. // uncomment this when implementing:
  1502. // let vfse: VexFlowStaffEntry = (graphicalStaffEntry as VexFlowStaffEntry);
  1503. return;
  1504. }
  1505. /**
  1506. * Is called if a note is part of a tuplet.
  1507. * @param graphicalNote
  1508. * @param tuplet
  1509. * @param openTuplets a list of all currently open tuplets
  1510. */
  1511. protected handleTuplet(graphicalNote: GraphicalNote, tuplet: Tuplet, openTuplets: Tuplet[]): void {
  1512. (graphicalNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure).handleTuplet(graphicalNote, tuplet);
  1513. }
  1514. /**
  1515. * Find the Index of the item of the array of all VexFlow Slurs that holds a specified slur
  1516. * @param gSlurs
  1517. * @param slur
  1518. */
  1519. public findIndexGraphicalSlurFromSlur(gSlurs: GraphicalSlur[], slur: Slur): number {
  1520. for (let slurIndex: number = 0; slurIndex < gSlurs.length; slurIndex++) {
  1521. if (gSlurs[slurIndex].slur === slur) {
  1522. return slurIndex;
  1523. }
  1524. }
  1525. return -1;
  1526. }
  1527. /* VexFlow Version - for later use
  1528. public findIndexVFSlurFromSlur(vfSlurs: VexFlowSlur[], slur: Slur): number {
  1529. for (let slurIndex: number = 0; slurIndex < vfSlurs.length; slurIndex++) {
  1530. if (vfSlurs[slurIndex].vfSlur === slur) {
  1531. return slurIndex;
  1532. }
  1533. }
  1534. }
  1535. */
  1536. // Generate all Graphical Slurs and attach them to the staffline
  1537. protected calculateSlurs(): void {
  1538. const openSlursDict: { [staffId: number]: GraphicalSlur[] } = {};
  1539. for (const graphicalMeasure of this.graphicalMusicSheet.MeasureList[0]) { //let i: number = 0; i < this.graphicalMusicSheet.MeasureList[0].length; i++) {
  1540. openSlursDict[graphicalMeasure.ParentStaff.idInMusicSheet] = [];
  1541. }
  1542. /* VexFlow Version - for later use
  1543. // Generate an empty dictonary to index an array of VexFlowSlur classes
  1544. const vfOpenSlursDict: { [staffId: number]: VexFlowSlur[]; } = {}; //VexFlowSlur[]; } = {};
  1545. // use first SourceMeasure to get all graphical measures to know how many staves are currently visible in this musicsheet
  1546. // foreach stave: create an empty array. It can later hold open slurs.
  1547. // Measure how many staves are visible and reserve space for them.
  1548. for (const graphicalMeasure of this.graphicalMusicSheet.MeasureList[0]) { //let i: number = 0; i < this.graphicalMusicSheet.MeasureList[0].length; i++) {
  1549. vfOpenSlursDict[graphicalMeasure.ParentStaff.idInMusicSheet] = [];
  1550. }
  1551. */
  1552. for (const musicSystem of this.musicSystems) {
  1553. for (const staffLine of musicSystem.StaffLines) {
  1554. // if a graphical slur reaches out of the last musicsystem, we have to create another graphical slur reaching into this musicsystem
  1555. // (one slur needs 2 graphical slurs)
  1556. const openGraphicalSlurs: GraphicalSlur[] = openSlursDict[staffLine.ParentStaff.idInMusicSheet];
  1557. for (let slurIndex: number = 0; slurIndex < openGraphicalSlurs.length; slurIndex++) {
  1558. const oldGSlur: GraphicalSlur = openGraphicalSlurs[slurIndex];
  1559. const newGSlur: GraphicalSlur = new GraphicalSlur(oldGSlur.slur, this.rules); //Graphicalslur.createFromSlur(oldSlur);
  1560. staffLine.addSlurToStaffline(newGSlur); // every VFSlur is added to the array in the VFStaffline!
  1561. openGraphicalSlurs[slurIndex] = newGSlur;
  1562. }
  1563. /* VexFlow Version - for later use
  1564. const vfOpenSlurs: VexFlowSlur[] = vfOpenSlursDict[staffLine.ParentStaff.idInMusicSheet];
  1565. const vfStaffLine: VexFlowStaffLine = <VexFlowStaffLine> staffLine;
  1566. for (let slurIndex: number = 0; slurIndex < vfOpenSlurs.length; slurIndex++) {
  1567. const oldVFSlur: VexFlowSlur = vfOpenSlurs[slurIndex];
  1568. const newVFSlur: VexFlowSlur = VexFlowSlur.createFromVexflowSlur(oldVFSlur);
  1569. newVFSlur.vfStartNote = undefined;
  1570. vfStaffLine.addVFSlurToVFStaffline(newVFSlur); // every VFSlur is added to the array in the VFStaffline!
  1571. vfOpenSlurs[slurIndex] = newVFSlur;
  1572. }
  1573. */
  1574. // add reference of slur array to the VexFlowStaffline class
  1575. for (const graphicalMeasure of staffLine.Measures) {
  1576. for (const graphicalStaffEntry of graphicalMeasure.staffEntries) {
  1577. // loop over "normal" notes (= no gracenotes)
  1578. for (const graphicalVoiceEntry of graphicalStaffEntry.graphicalVoiceEntries) {
  1579. for (const graphicalNote of graphicalVoiceEntry.notes) {
  1580. for (const slur of graphicalNote.sourceNote.NoteSlurs) {
  1581. // extra check for some MusicSheets that have openSlurs (because only the first Page is available -> Recordare files)
  1582. if (!slur.EndNote || !slur.StartNote) {
  1583. continue;
  1584. }
  1585. // add new VexFlowSlur to List
  1586. if (slur.StartNote === graphicalNote.sourceNote) {
  1587. if (graphicalNote.sourceNote.NoteTie) {
  1588. if (graphicalNote.parentVoiceEntry.parentStaffEntry.getAbsoluteTimestamp() !==
  1589. graphicalNote.sourceNote.NoteTie.StartNote.getAbsoluteTimestamp()) {
  1590. break;
  1591. }
  1592. }
  1593. // Add a Graphical Slur to the staffline, if the recent note is the Startnote of a slur
  1594. const gSlur: GraphicalSlur = new GraphicalSlur(slur, this.rules);
  1595. openGraphicalSlurs.push(gSlur);
  1596. staffLine.addSlurToStaffline(gSlur);
  1597. /* VexFlow Version - for later use
  1598. const vfSlur: VexFlowSlur = new VexFlowSlur(slur);
  1599. vfOpenSlurs.push(vfSlur); //add open... adding / removing is JUST DONE in the open... array
  1600. vfSlur.vfStartNote = (graphicalVoiceEntry as VexFlowVoiceEntry).vfStaveNote;
  1601. vfStaffLine.addVFSlurToVFStaffline(vfSlur); // every VFSlur is added to the array in the VFStaffline!
  1602. */
  1603. }
  1604. if (slur.EndNote === graphicalNote.sourceNote) {
  1605. // Remove the Graphical Slur from the staffline if the note is the Endnote of a slur
  1606. const index: number = this.findIndexGraphicalSlurFromSlur(openGraphicalSlurs, slur);
  1607. if (index >= 0) {
  1608. // save Voice Entry in VFSlur and then remove it from array of open VFSlurs
  1609. const gSlur: GraphicalSlur = openGraphicalSlurs[index];
  1610. if (gSlur.staffEntries.indexOf(graphicalStaffEntry) === -1) {
  1611. gSlur.staffEntries.push(graphicalStaffEntry);
  1612. }
  1613. openGraphicalSlurs.splice(index, 1);
  1614. }
  1615. /* VexFlow Version - for later use
  1616. const vfIndex: number = this.findIndexVFSlurFromSlur(vfOpenSlurs, slur);
  1617. if (vfIndex !== undefined) {
  1618. // save Voice Entry in VFSlur and then remove it from array of open VFSlurs
  1619. const vfSlur: VexFlowSlur = vfOpenSlurs[vfIndex];
  1620. vfSlur.vfEndNote = (graphicalVoiceEntry as VexFlowVoiceEntry).vfStaveNote;
  1621. vfSlur.createVexFlowCurve();
  1622. vfOpenSlurs.splice(vfIndex, 1);
  1623. }
  1624. */
  1625. }
  1626. }
  1627. }
  1628. }
  1629. //add the present Staffentry to all open slurs that don't contain this Staffentry already
  1630. for (const gSlur of openGraphicalSlurs) {
  1631. if (gSlur.staffEntries.indexOf(graphicalStaffEntry) === -1) {
  1632. gSlur.staffEntries.push(graphicalStaffEntry);
  1633. }
  1634. }
  1635. } // loop over StaffEntries
  1636. } // loop over Measures
  1637. } // loop over StaffLines
  1638. // Attach vfSlur array to the vfStaffline to be drawn
  1639. //vfStaffLine.SlursInVFStaffLine = vfSlurs;
  1640. } // loop over MusicSystems
  1641. // order slurs that were saved to the Staffline
  1642. for (const musicSystem of this.musicSystems) {
  1643. for (const staffLine of musicSystem.StaffLines) {
  1644. // Sort all gSlurs in the staffline using the Compare function in class GraphicalSlurSorter
  1645. const sortedGSlurs: GraphicalSlur[] = staffLine.GraphicalSlurs.sort(GraphicalSlur.Compare);
  1646. for (const gSlur of sortedGSlurs) {
  1647. // crossed slurs will be handled later:
  1648. if (gSlur.slur.isCrossed()) {
  1649. continue;
  1650. }
  1651. gSlur.calculateCurve(this.rules);
  1652. }
  1653. }
  1654. }
  1655. }
  1656. }