VexFlowMusicSheetCalculator.ts 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837
  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.addStaveTie(vfTie1, tie);
  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.addStaveTie(vfTie2, tie);
  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. const tieDirection: PlacementEnum = tie.Tie.getTieDirection(startNote.sourceNote);
  617. if (tieDirection === PlacementEnum.Below) {
  618. vfTie.setDirection(1); // + is down in vexflow
  619. } else if (tieDirection === PlacementEnum.Above) {
  620. vfTie.setDirection(-1);
  621. }
  622. }
  623. const measure: VexFlowMeasure = (endNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure);
  624. measure.addStaveTie(vfTie, tie);
  625. }
  626. }
  627. }
  628. protected calculateDynamicExpressionsForMultiExpression(multiExpression: MultiExpression, measureIndex: number, staffIndex: number): void {
  629. if (measureIndex < this.rules.MinMeasureToDrawIndex || measureIndex > this.rules.MaxMeasureToDrawIndex) {
  630. return;
  631. // we do already use the min/max in MusicSheetCalculator.calculateDynamicsExpressions,
  632. // but this may be necessary for StaffLinkedExpressions, not tested.
  633. }
  634. // calculate absolute Timestamp
  635. const absoluteTimestamp: Fraction = multiExpression.AbsoluteTimestamp;
  636. const measures: GraphicalMeasure[] = this.graphicalMusicSheet.MeasureList[measureIndex];
  637. const staffLine: StaffLine = measures[staffIndex].ParentStaffLine;
  638. const startMeasure: GraphicalMeasure = measures[staffIndex];
  639. if (!staffLine) {
  640. return;
  641. }
  642. // start position in staffline:
  643. const dynamicStartPosition: PointF2D = this.getRelativePositionInStaffLineFromTimestamp(
  644. absoluteTimestamp,
  645. staffIndex,
  646. staffLine,
  647. staffLine?.isPartOfMultiStaffInstrument());
  648. if (dynamicStartPosition.x <= 0) {
  649. dynamicStartPosition.x = startMeasure.beginInstructionsWidth + this.rules.RhythmRightMargin;
  650. }
  651. if (multiExpression.InstantaneousDynamic) {
  652. const graphicalInstantaneousDynamic: VexFlowInstantaneousDynamicExpression = new VexFlowInstantaneousDynamicExpression(
  653. multiExpression.InstantaneousDynamic,
  654. staffLine,
  655. startMeasure);
  656. // compare with multiExpression.InstantaneousDynamic.InMeasureTimestamp or add a relative timestamp? if we ever need a separate timestamp
  657. this.calculateGraphicalInstantaneousDynamicExpression(graphicalInstantaneousDynamic, dynamicStartPosition, absoluteTimestamp);
  658. this.dynamicExpressionMap.set(absoluteTimestamp.RealValue, graphicalInstantaneousDynamic.PositionAndShape);
  659. }
  660. if (multiExpression.StartingContinuousDynamic) {
  661. const continuousDynamic: ContinuousDynamicExpression = multiExpression.StartingContinuousDynamic;
  662. const graphicalContinuousDynamic: VexFlowContinuousDynamicExpression = new VexFlowContinuousDynamicExpression(
  663. multiExpression.StartingContinuousDynamic,
  664. staffLine,
  665. startMeasure.parentSourceMeasure);
  666. graphicalContinuousDynamic.StartMeasure = startMeasure;
  667. if (!graphicalContinuousDynamic.IsVerbal && continuousDynamic.EndMultiExpression) {
  668. try {
  669. this.calculateGraphicalContinuousDynamic(graphicalContinuousDynamic, dynamicStartPosition);
  670. graphicalContinuousDynamic.updateSkyBottomLine();
  671. } catch (e) {
  672. // TODO this sometimes fails when the measure range to draw doesn't include all the dynamic's measures, method needs to be adjusted
  673. // see calculateGraphicalContinuousDynamic(), also in MusicSheetCalculator.
  674. }
  675. } else if (graphicalContinuousDynamic.IsVerbal) {
  676. this.calculateGraphicalVerbalContinuousDynamic(graphicalContinuousDynamic, dynamicStartPosition);
  677. } else {
  678. log.warn("This continuous dynamic is not covered. measure" + multiExpression.SourceMeasureParent.MeasureNumber);
  679. }
  680. }
  681. }
  682. protected createMetronomeMark(metronomeExpression: InstantaneousTempoExpression): void {
  683. // note: sometimes MeasureNumber is 0 here, e.g. in Christbaum, maybe because of pickup measure (auftakt)
  684. const measureNumber: number = Math.max(metronomeExpression.ParentMultiTempoExpression.SourceMeasureParent.MeasureNumber - 1, 0);
  685. const staffNumber: number = Math.max(metronomeExpression.StaffNumber - 1, 0);
  686. const firstMetronomeMark: boolean = measureNumber === 0 && staffNumber === 0;
  687. const vfStave: Vex.Flow.Stave = (this.graphicalMusicSheet.MeasureList[measureNumber][staffNumber] as VexFlowMeasure).getVFStave();
  688. //vfStave.addModifier(new Vex.Flow.StaveTempo( // needs Vexflow PR
  689. let vexflowDuration: string = "q";
  690. if (metronomeExpression.beatUnit) {
  691. const duration: Fraction = NoteTypeHandler.getNoteDurationFromType(metronomeExpression.beatUnit);
  692. vexflowDuration = VexFlowConverter.durations(duration, false)[0];
  693. }
  694. let yShift: number = this.rules.MetronomeMarkYShift;
  695. let hasExpressionsAboveStaffline: boolean = false;
  696. for (const expression of metronomeExpression.parentMeasure.TempoExpressions) {
  697. const isMetronomeExpression: boolean = expression.InstantaneousTempo?.Enum === TempoEnum.metronomeMark;
  698. if (expression.getPlacementOfFirstEntry() === PlacementEnum.Above &&
  699. !isMetronomeExpression) {
  700. hasExpressionsAboveStaffline = true;
  701. break;
  702. }
  703. }
  704. if (hasExpressionsAboveStaffline) {
  705. yShift -= 1.4;
  706. // TODO improve this with proper skyline / collision detection. unfortunately we don't have a skyline here yet.
  707. // let maxSkylineBeginning: number = 0;
  708. // for (let i = 0; i < skyline.length / 1; i++) { // search in first 3rd, disregard end of measure
  709. // maxSkylineBeginning = Math.max(skyline[i], maxSkylineBeginning);
  710. // }
  711. // console.log('max skyline: ' + maxSkylineBeginning);
  712. }
  713. const skyline: number[] = this.graphicalMusicSheet.MeasureList[0][0].ParentStaffLine?.SkyLine;
  714. vfStave.setTempo(
  715. {
  716. bpm: metronomeExpression.TempoInBpm,
  717. dots: metronomeExpression.dotted,
  718. duration: vexflowDuration
  719. },
  720. yShift * unitInPixels);
  721. // -50, -30), 0); //needs Vexflow PR
  722. //.setShiftX(-50);
  723. const xShift: number = firstMetronomeMark ? this.rules.MetronomeMarkXShift * unitInPixels : 0;
  724. (<any>vfStave.getModifiers()[vfStave.getModifiers().length - 1]).setShiftX(
  725. xShift
  726. );
  727. if (skyline) {
  728. // TODO calculate bounding box of metronome mark instead of hacking skyline to fix lyricist collision
  729. skyline[0] = Math.min(skyline[0], -4.5 + yShift);
  730. }
  731. // somehow this is called repeatedly in Clementi, so skyline[0] = Math.min instead of -=
  732. }
  733. protected calculateRehearsalMark(measure: SourceMeasure): void {
  734. const rehearsalExpression: RehearsalExpression = measure.rehearsalExpression;
  735. if (!rehearsalExpression) {
  736. return;
  737. }
  738. const firstMeasureNumber: number = this.graphicalMusicSheet.MeasureList[0][0].MeasureNumber; // 0 for pickup, 1 otherwise
  739. const measureNumber: number = Math.max(measure.MeasureNumber - firstMeasureNumber, 0);
  740. const staffNumber: number = 0;
  741. const vfStave: Vex.Flow.Stave = (this.graphicalMusicSheet.MeasureList[measureNumber][staffNumber] as VexFlowMeasure)?.getVFStave();
  742. if (!vfStave) { // potentially multi measure rest
  743. return;
  744. }
  745. const yOffset: number = -this.rules.RehearsalMarkYOffsetDefault - this.rules.RehearsalMarkYOffset;
  746. let xOffset: number = this.rules.RehearsalMarkXOffsetDefault + this.rules.RehearsalMarkXOffset;
  747. if (measure.IsSystemStartMeasure) {
  748. xOffset += this.rules.RehearsalMarkXOffsetSystemStartMeasure;
  749. }
  750. // const section: Vex.Flow.StaveSection = new Vex.Flow.StaveSection(rehearsalExpression.label, vfStave.getX(), yOffset);
  751. // (vfStave as any).modifiers.push(section);
  752. const fontSize: number = this.rules.RehearsalMarkFontSize;
  753. (vfStave as any).setSection(rehearsalExpression.label, yOffset, xOffset, fontSize); // fontSize is an extra argument from VexFlowPatch
  754. }
  755. /**
  756. * Calculate a single OctaveShift for a [[MultiExpression]].
  757. * @param sourceMeasure
  758. * @param multiExpression
  759. * @param measureIndex
  760. * @param staffIndex
  761. */
  762. protected calculateSingleOctaveShift(sourceMeasure: SourceMeasure, multiExpression: MultiExpression, measureIndex: number, staffIndex: number): void {
  763. // calculate absolute Timestamp and startStaffLine (and EndStaffLine if needed)
  764. const octaveShift: OctaveShift = multiExpression.OctaveShiftStart;
  765. const startTimeStamp: Fraction = octaveShift.ParentStartMultiExpression.Timestamp;
  766. const endTimeStamp: Fraction = octaveShift.ParentEndMultiExpression?.Timestamp;
  767. const minMeasureToDrawIndex: number = this.rules.MinMeasureToDrawIndex;
  768. const maxMeasureToDrawIndex: number = this.rules.MaxMeasureToDrawIndex;
  769. let startStaffLine: StaffLine = this.graphicalMusicSheet.MeasureList[measureIndex][staffIndex].ParentStaffLine;
  770. if (!startStaffLine) { // fix for rendering range set. all of these can probably be done cleaner.
  771. startStaffLine = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex].ParentStaffLine;
  772. }
  773. let endMeasure: GraphicalMeasure = undefined;
  774. if (octaveShift.ParentEndMultiExpression) {
  775. endMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(octaveShift.ParentEndMultiExpression.SourceMeasureParent,
  776. staffIndex);
  777. } else {
  778. endMeasure = this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(staffIndex, true); // get last rendered measure
  779. }
  780. if (endMeasure.MeasureNumber > maxMeasureToDrawIndex + 1) { // octaveshift ends in measure not rendered
  781. endMeasure = this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(staffIndex, true);
  782. }
  783. let startMeasure: GraphicalMeasure = undefined;
  784. if (octaveShift.ParentEndMultiExpression) {
  785. startMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(octaveShift.ParentStartMultiExpression.SourceMeasureParent,
  786. staffIndex);
  787. } else {
  788. startMeasure = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex]; // first rendered measure
  789. }
  790. if (startMeasure.MeasureNumber < minMeasureToDrawIndex + 1) { // octaveshift starts before range of measures selected to render
  791. startMeasure = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex]; // first rendered measure
  792. }
  793. if (startMeasure.parentSourceMeasure.measureListIndex < minMeasureToDrawIndex ||
  794. startMeasure.parentSourceMeasure.measureListIndex > maxMeasureToDrawIndex ||
  795. endMeasure.parentSourceMeasure.measureListIndex < minMeasureToDrawIndex ||
  796. endMeasure.parentSourceMeasure.measureListIndex > maxMeasureToDrawIndex) {
  797. // completely out of drawing range, don't draw anything
  798. return;
  799. }
  800. let endStaffLine: StaffLine = endMeasure.ParentStaffLine;
  801. if (!endStaffLine) {
  802. endStaffLine = startStaffLine;
  803. }
  804. if (endMeasure && startStaffLine && endStaffLine) {
  805. // calculate GraphicalOctaveShift and RelativePositions
  806. const graphicalOctaveShift: VexFlowOctaveShift = new VexFlowOctaveShift(octaveShift, startStaffLine.PositionAndShape);
  807. if (!graphicalOctaveShift.startNote) { // fix for rendering range set
  808. let startGse: GraphicalStaffEntry;
  809. for (const gse of startMeasure.staffEntries) {
  810. if (gse) {
  811. startGse = gse;
  812. break;
  813. } // sometimes the first graphical staff entry is undefined, not sure why.
  814. }
  815. if (!startGse) {
  816. return; // couldn't find a start staffentry, don't draw the octave shift
  817. }
  818. graphicalOctaveShift.setStartNote(startGse);
  819. if (!graphicalOctaveShift.startNote) {
  820. return; // couldn't find a start note, don't draw the octave shift
  821. }
  822. }
  823. if (!graphicalOctaveShift.endNote) { // fix for rendering range set
  824. let endGse: GraphicalStaffEntry;
  825. for (let i: number = endMeasure.staffEntries.length - 1; i >= 0; i++) {
  826. // search backwards from end of measure
  827. if (endMeasure.staffEntries[i]) {
  828. endGse = endMeasure.staffEntries[i];
  829. break;
  830. }
  831. }
  832. graphicalOctaveShift.setEndNote(endGse);
  833. if (!graphicalOctaveShift.endNote) {
  834. return;
  835. }
  836. }
  837. // calculate RelativePosition and Dashes
  838. let startStaffEntry: GraphicalStaffEntry = startMeasure.findGraphicalStaffEntryFromTimestamp(startTimeStamp);
  839. if (!startStaffEntry) { // fix for rendering range set
  840. startStaffEntry = startMeasure.staffEntries[0];
  841. }
  842. let endStaffEntry: GraphicalStaffEntry = endMeasure.findGraphicalStaffEntryFromTimestamp(endTimeStamp);
  843. if (!endStaffEntry) { // fix for rendering range set
  844. endStaffEntry = endMeasure.staffEntries[endMeasure.staffEntries.length - 1];
  845. }
  846. graphicalOctaveShift.setStartNote(startStaffEntry);
  847. if (endStaffLine !== startStaffLine) {
  848. graphicalOctaveShift.endsOnDifferentStaffLine = true;
  849. let lastMeasureOfFirstShift: GraphicalMeasure = startStaffLine.Measures[startStaffLine.Measures.length - 1];
  850. if (lastMeasureOfFirstShift === undefined) { // TODO handle this case correctly (when drawUpToMeasureNumber etc set)
  851. lastMeasureOfFirstShift = endMeasure;
  852. }
  853. const lastNoteOfFirstShift: GraphicalStaffEntry = lastMeasureOfFirstShift.staffEntries[lastMeasureOfFirstShift.staffEntries.length - 1];
  854. graphicalOctaveShift.setEndNote(lastNoteOfFirstShift);
  855. const systemsInBetweenCount: number = endStaffLine.ParentMusicSystem.Id - startStaffLine.ParentMusicSystem.Id;
  856. if (systemsInBetweenCount > 0) {
  857. //Loop through the stafflines in between to the end
  858. for (let i: number = startStaffLine.ParentMusicSystem.Id; i < endStaffLine.ParentMusicSystem.Id; i++) {
  859. const idx: number = i + 1;
  860. const nextShiftMusicSystem: MusicSystem = this.musicSystems[idx];
  861. const nextShiftStaffline: StaffLine = nextShiftMusicSystem.StaffLines[staffIndex];
  862. const nextShiftFirstMeasure: GraphicalMeasure = nextShiftStaffline.Measures[0];
  863. // Shift starts on the first measure
  864. const nextOctaveShift: VexFlowOctaveShift = new VexFlowOctaveShift(octaveShift, nextShiftFirstMeasure.PositionAndShape);
  865. if (i < systemsInBetweenCount) {
  866. nextOctaveShift.endsOnDifferentStaffLine = true;
  867. }
  868. let nextShiftLastMeasure: GraphicalMeasure = nextShiftStaffline.Measures[nextShiftStaffline.Measures.length - 1];
  869. if (nextShiftLastMeasure.IsExtraGraphicalMeasure) { // key/rhythm change measure
  870. nextShiftLastMeasure = nextShiftStaffline.Measures[nextShiftStaffline.Measures.length - 2];
  871. }
  872. const firstNote: GraphicalStaffEntry = nextShiftFirstMeasure.staffEntries[0];
  873. let lastNote: GraphicalStaffEntry = nextShiftLastMeasure.staffEntries[nextShiftLastMeasure.staffEntries.length - 1];
  874. //If the end measure's staffline is the ending staffline, this endMeasure is the end of the shift
  875. if (endMeasure.ParentStaffLine === nextShiftStaffline) {
  876. nextShiftLastMeasure = endMeasure;
  877. lastNote = endStaffEntry;
  878. }
  879. const logPrefix: string = "VexFlowMusicSheetCalculator.calculateSingleOctaveShift: ";
  880. if (!firstNote) {
  881. log.warn(logPrefix + "no firstNote found");
  882. }
  883. if (!lastNote) {
  884. log.warn(logPrefix + "no lastNote found");
  885. }
  886. nextOctaveShift.setStartNote(firstNote);
  887. nextOctaveShift.setEndNote(lastNote);
  888. nextShiftStaffline.OctaveShifts.push(nextOctaveShift);
  889. this.calculateOctaveShiftSkyBottomLine(firstNote, lastNote, nextOctaveShift, nextShiftStaffline);
  890. }
  891. }
  892. this.calculateOctaveShiftSkyBottomLine(startStaffEntry, lastNoteOfFirstShift, graphicalOctaveShift, startStaffLine);
  893. } else {
  894. graphicalOctaveShift.setEndNote(endStaffEntry);
  895. this.calculateOctaveShiftSkyBottomLine(startStaffEntry, endStaffEntry, graphicalOctaveShift, startStaffLine);
  896. }
  897. startStaffLine.OctaveShifts.push(graphicalOctaveShift);
  898. } else {
  899. log.warn("End measure or staffLines for octave shift are undefined! This should not happen!");
  900. }
  901. }
  902. protected calculateSinglePedal(sourceMeasure: SourceMeasure, multiExpression: MultiExpression, measureIndex: number, staffIndex: number): void {
  903. // calculate absolute Timestamp and startStaffLine (and EndStaffLine if needed)
  904. const pedal: Pedal = multiExpression.PedalStart;
  905. const startTimeStamp: Fraction = pedal.ParentStartMultiExpression.Timestamp;
  906. const endTimeStamp: Fraction = pedal.ParentEndMultiExpression?.Timestamp;
  907. const minMeasureToDrawIndex: number = this.rules.MinMeasureToDrawIndex;
  908. const maxMeasureToDrawIndex: number = this.rules.MaxMeasureToDrawIndex;
  909. let startStaffLine: StaffLine = this.graphicalMusicSheet.MeasureList[measureIndex][staffIndex].ParentStaffLine;
  910. if (!startStaffLine) { // fix for rendering range set. all of these can probably be done cleaner.
  911. startStaffLine = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex].ParentStaffLine;
  912. }
  913. let endMeasure: GraphicalMeasure = undefined;
  914. if (pedal.ParentEndMultiExpression) {
  915. endMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(pedal.ParentEndMultiExpression.SourceMeasureParent,
  916. staffIndex);
  917. } else {
  918. endMeasure = this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(staffIndex, true); // get last rendered measure
  919. }
  920. if (endMeasure.MeasureNumber > maxMeasureToDrawIndex + 1) { // ends in measure not rendered
  921. endMeasure = this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(staffIndex, true);
  922. }
  923. let startMeasure: GraphicalMeasure = undefined;
  924. if (pedal.ParentEndMultiExpression) {
  925. startMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(pedal.ParentStartMultiExpression.SourceMeasureParent,
  926. staffIndex);
  927. } else {
  928. startMeasure = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex]; // first rendered measure
  929. }
  930. if (startMeasure.MeasureNumber < minMeasureToDrawIndex + 1) { // starts before range of measures selected to render
  931. startMeasure = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex]; // first rendered measure
  932. }
  933. if (startMeasure.parentSourceMeasure.measureListIndex < minMeasureToDrawIndex ||
  934. startMeasure.parentSourceMeasure.measureListIndex > maxMeasureToDrawIndex ||
  935. endMeasure.parentSourceMeasure.measureListIndex < minMeasureToDrawIndex ||
  936. endMeasure.parentSourceMeasure.measureListIndex > maxMeasureToDrawIndex) {
  937. // completely out of drawing range, don't draw anything
  938. return;
  939. }
  940. let endStaffLine: StaffLine = endMeasure.ParentStaffLine;
  941. if (!endStaffLine) {
  942. endStaffLine = startStaffLine;
  943. }
  944. if (endMeasure && startStaffLine && endStaffLine) {
  945. let openEnd: boolean = false;
  946. if (startStaffLine !== endStaffLine) {
  947. openEnd = true;
  948. }
  949. // calculate GraphicalPedal and RelativePositions
  950. const graphicalPedal: VexFlowPedal = new VexFlowPedal(pedal, startStaffLine.PositionAndShape, false, openEnd);
  951. // calculate RelativePosition
  952. let startStaffEntry: GraphicalStaffEntry = startMeasure.findGraphicalStaffEntryFromTimestamp(startTimeStamp);
  953. if (!startStaffEntry) { // fix for rendering range set
  954. startStaffEntry = startMeasure.staffEntries[0];
  955. }
  956. let endStaffEntry: GraphicalStaffEntry = endMeasure.findGraphicalStaffEntryFromTimestamp(endTimeStamp);
  957. if (!endStaffEntry) { // fix for rendering range set
  958. endStaffEntry = endMeasure.staffEntries[endMeasure.staffEntries.length - 1];
  959. // TODO can be undefined if no notes in end measure
  960. }
  961. if(!graphicalPedal.setStartNote(startStaffEntry)){
  962. return;
  963. }
  964. if (endStaffLine !== startStaffLine) {
  965. if(graphicalPedal.pedalSymbol === MusicSymbol.PEDAL_SYMBOL){
  966. graphicalPedal.setEndNote(endStaffEntry);
  967. graphicalPedal.setEndMeasure(endMeasure);
  968. graphicalPedal.ReleaseText = " ";
  969. graphicalPedal.CalculateBoundingBox();
  970. this.calculatePedalSkyBottomLine(graphicalPedal.startVfVoiceEntry, graphicalPedal.endVfVoiceEntry, graphicalPedal, startStaffLine);
  971. const nextPedalFirstMeasure: GraphicalMeasure = endStaffLine.Measures[0];
  972. // pedal starts on the first measure
  973. const nextPedal: VexFlowPedal = new VexFlowPedal(pedal, nextPedalFirstMeasure.PositionAndShape);
  974. const firstNote: GraphicalStaffEntry = nextPedalFirstMeasure.staffEntries[0];
  975. if(!nextPedal.setStartNote(firstNote)){
  976. return;
  977. }
  978. nextPedal.setEndNote(endStaffEntry);
  979. graphicalPedal.setEndMeasure(endMeasure);
  980. endStaffLine.Pedals.push(nextPedal);
  981. nextPedal.CalculateBoundingBox();
  982. nextPedal.DepressText = " ";
  983. this.calculatePedalSkyBottomLine(nextPedal.startVfVoiceEntry, nextPedal.endVfVoiceEntry, nextPedal, endStaffLine);
  984. } else {
  985. let lastMeasureOfFirstShift: GraphicalMeasure = startStaffLine.Measures[startStaffLine.Measures.length - 1];
  986. if (lastMeasureOfFirstShift === undefined) { // TODO handle this case correctly (when drawUpToMeasureNumber etc set)
  987. lastMeasureOfFirstShift = endMeasure;
  988. }
  989. const lastNoteOfFirstShift: GraphicalStaffEntry = lastMeasureOfFirstShift.staffEntries[lastMeasureOfFirstShift.staffEntries.length - 1];
  990. graphicalPedal.setEndNote(lastNoteOfFirstShift);
  991. graphicalPedal.setEndMeasure(endMeasure);
  992. graphicalPedal.ChangeEnd = false;
  993. const systemsInBetweenCount: number = endStaffLine.ParentMusicSystem.Id - startStaffLine.ParentMusicSystem.Id;
  994. if (systemsInBetweenCount > 0) {
  995. //Loop through the stafflines in between to the end
  996. let currentCount: number = 1;
  997. for (let i: number = startStaffLine.ParentMusicSystem.Id; i < endStaffLine.ParentMusicSystem.Id; i++) {
  998. const nextPedalMusicSystem: MusicSystem = this.musicSystems[i + 1];
  999. const nextPedalStaffline: StaffLine = nextPedalMusicSystem.StaffLines[staffIndex];
  1000. const nextPedalFirstMeasure: GraphicalMeasure = nextPedalStaffline.Measures[0];
  1001. let nextOpenEnd: boolean = false;
  1002. let nextChangeEndFromParent: boolean = false;
  1003. if (currentCount < systemsInBetweenCount) {
  1004. nextOpenEnd = true;
  1005. } else {
  1006. nextChangeEndFromParent = true;
  1007. }
  1008. currentCount++;
  1009. // pedal starts on the first measure
  1010. const nextPedal: VexFlowPedal = new VexFlowPedal(pedal, nextPedalFirstMeasure.PositionAndShape, true, nextOpenEnd);
  1011. nextPedal.ChangeBegin = false;
  1012. if(nextChangeEndFromParent){
  1013. nextPedal.ChangeEnd = pedal.ChangeEnd;
  1014. } else {
  1015. nextPedal.ChangeEnd = false;
  1016. }
  1017. let nextPedalLastMeasure: GraphicalMeasure = nextPedalStaffline.Measures[nextPedalStaffline.Measures.length - 1];
  1018. const firstNote: GraphicalStaffEntry = nextPedalFirstMeasure.staffEntries[0];
  1019. let lastNote: GraphicalStaffEntry = nextPedalLastMeasure.staffEntries[nextPedalLastMeasure.staffEntries.length - 1];
  1020. //If the end measure's staffline is the ending staffline, this endMeasure is the end of the pedal
  1021. if (endMeasure.ParentStaffLine === nextPedalStaffline) {
  1022. nextPedalLastMeasure = endMeasure;
  1023. lastNote = endStaffEntry;
  1024. }
  1025. if(!nextPedal.setStartNote(firstNote)){
  1026. break;
  1027. }
  1028. nextPedal.setEndNote(lastNote);
  1029. graphicalPedal.setEndMeasure(endMeasure);
  1030. nextPedalStaffline.Pedals.push(nextPedal);
  1031. nextPedal.CalculateBoundingBox();
  1032. this.calculatePedalSkyBottomLine(nextPedal.startVfVoiceEntry, nextPedal.endVfVoiceEntry, nextPedal, nextPedalStaffline);
  1033. }
  1034. }
  1035. graphicalPedal.CalculateBoundingBox();
  1036. this.calculatePedalSkyBottomLine(graphicalPedal.startVfVoiceEntry, graphicalPedal.endVfVoiceEntry, graphicalPedal, startStaffLine);
  1037. }
  1038. } else {
  1039. graphicalPedal.setEndNote(endStaffEntry);
  1040. graphicalPedal.setEndMeasure(endMeasure);
  1041. graphicalPedal.CalculateBoundingBox();
  1042. this.calculatePedalSkyBottomLine(graphicalPedal.startVfVoiceEntry, graphicalPedal.endVfVoiceEntry, graphicalPedal, startStaffLine);
  1043. }
  1044. startStaffLine.Pedals.push(graphicalPedal);
  1045. } else {
  1046. log.warn("End measure or staffLines for pedal are undefined! This should not happen!");
  1047. }
  1048. }
  1049. protected calculateSingleWavyLine(sourceMeasure: SourceMeasure, multiExpression: MultiExpression, measureIndex: number, staffIndex: number): void {
  1050. // calculate absolute Timestamp and startStaffLine (and EndStaffLine if needed)
  1051. const wavyLine: WavyLine = multiExpression.WavyLineStart;
  1052. const startTimeStamp: Fraction = wavyLine.ParentStartMultiExpression.Timestamp;
  1053. const endTimeStamp: Fraction = wavyLine.ParentEndMultiExpression?.Timestamp;
  1054. const minMeasureToDrawIndex: number = this.rules.MinMeasureToDrawIndex;
  1055. const maxMeasureToDrawIndex: number = this.rules.MaxMeasureToDrawIndex;
  1056. let startStaffLine: StaffLine = this.graphicalMusicSheet.MeasureList[measureIndex][staffIndex].ParentStaffLine;
  1057. if (!startStaffLine) { // fix for rendering range set. all of these can probably be done cleaner.
  1058. startStaffLine = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex].ParentStaffLine;
  1059. }
  1060. let endMeasure: GraphicalMeasure = undefined;
  1061. if (wavyLine.ParentEndMultiExpression) {
  1062. endMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(wavyLine.ParentEndMultiExpression.SourceMeasureParent,
  1063. staffIndex);
  1064. } else {
  1065. endMeasure = this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(staffIndex, true); // get last rendered measure
  1066. }
  1067. if (endMeasure.MeasureNumber > maxMeasureToDrawIndex + 1) { // ends in measure not rendered
  1068. endMeasure = this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(staffIndex, true);
  1069. }
  1070. let startMeasure: GraphicalMeasure = undefined;
  1071. if (wavyLine.ParentEndMultiExpression) {
  1072. startMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(wavyLine.ParentStartMultiExpression.SourceMeasureParent,
  1073. staffIndex);
  1074. } else {
  1075. startMeasure = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex]; // first rendered measure
  1076. }
  1077. if (startMeasure.MeasureNumber < minMeasureToDrawIndex + 1) { // starts before range of measures selected to render
  1078. startMeasure = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex]; // first rendered measure
  1079. }
  1080. if (startMeasure.parentSourceMeasure.measureListIndex < minMeasureToDrawIndex ||
  1081. startMeasure.parentSourceMeasure.measureListIndex > maxMeasureToDrawIndex ||
  1082. endMeasure.parentSourceMeasure.measureListIndex < minMeasureToDrawIndex ||
  1083. endMeasure.parentSourceMeasure.measureListIndex > maxMeasureToDrawIndex) {
  1084. // completely out of drawing range, don't draw anything
  1085. return;
  1086. }
  1087. let endStaffLine: StaffLine = endMeasure.ParentStaffLine;
  1088. if (!endStaffLine) {
  1089. endStaffLine = startStaffLine;
  1090. }
  1091. if (endMeasure && startStaffLine && endStaffLine) {
  1092. const graphicalWavyLine: VexflowVibratoBracket = new VexflowVibratoBracket(wavyLine, startStaffLine.PositionAndShape, startMeasure.ParentStaff.isTab);
  1093. // calculate RelativePosition
  1094. let startStaffEntry: GraphicalStaffEntry = startMeasure.findGraphicalStaffEntryFromTimestamp(startTimeStamp);
  1095. if (!startStaffEntry) { // fix for rendering range set
  1096. startStaffEntry = startMeasure.staffEntries[0];
  1097. }
  1098. let endStaffEntry: GraphicalStaffEntry = endMeasure.findGraphicalStaffEntryFromTimestamp(endTimeStamp);
  1099. if (!endStaffEntry) { // fix for rendering range set
  1100. endStaffEntry = endMeasure.staffEntries[endMeasure.staffEntries.length - 1];
  1101. }
  1102. graphicalWavyLine.setStartNote(startStaffEntry);
  1103. if (endStaffLine !== startStaffLine) {
  1104. let lastMeasureOfFirstShift: GraphicalMeasure = startStaffLine.Measures[startStaffLine.Measures.length - 1];
  1105. if (lastMeasureOfFirstShift === undefined) { // TODO handle this case correctly (when drawUpToMeasureNumber etc set)
  1106. lastMeasureOfFirstShift = endMeasure;
  1107. }
  1108. const lastNoteOfFirstShift: GraphicalStaffEntry = lastMeasureOfFirstShift.staffEntries[lastMeasureOfFirstShift.staffEntries.length - 1];
  1109. graphicalWavyLine.setEndNote(lastNoteOfFirstShift);
  1110. const systemsInBetweenCount: number = endStaffLine.ParentMusicSystem.Id - startStaffLine.ParentMusicSystem.Id;
  1111. if (systemsInBetweenCount > 0) {
  1112. for (let i: number = startStaffLine.ParentMusicSystem.Id; i < endStaffLine.ParentMusicSystem.Id; i++) {
  1113. const nextWavyLineMusicSystem: MusicSystem = this.musicSystems[i + 1];
  1114. const nextWavyLineStaffline: StaffLine = nextWavyLineMusicSystem.StaffLines[staffIndex];
  1115. const nextWavyLineFirstMeasure: GraphicalMeasure = nextWavyLineStaffline.Measures[0];
  1116. // vibrato starts on the first measure
  1117. const nextWavyLine: VexflowVibratoBracket = new VexflowVibratoBracket(wavyLine, nextWavyLineFirstMeasure.PositionAndShape,
  1118. nextWavyLineStaffline.ParentStaff.isTab);
  1119. let nextWavyLineLastMeasure: GraphicalMeasure = nextWavyLineStaffline.Measures[nextWavyLineStaffline.Measures.length - 1];
  1120. const firstNote: GraphicalStaffEntry = nextWavyLineFirstMeasure.staffEntries[0];
  1121. let lastNote: GraphicalStaffEntry = nextWavyLineLastMeasure.staffEntries[nextWavyLineLastMeasure.staffEntries.length - 1];
  1122. //If the end measure's is the ending staffline, this endMeasure is the end of the wavy line
  1123. if (endMeasure.ParentStaffLine === nextWavyLineStaffline) {
  1124. nextWavyLineLastMeasure = endMeasure;
  1125. lastNote = endStaffEntry;
  1126. }
  1127. nextWavyLine.setStartNote(firstNote);
  1128. nextWavyLine.setEndNote(lastNote);
  1129. nextWavyLineStaffline.WavyLines.push(nextWavyLine);
  1130. nextWavyLine.CalculateBoundingBox();
  1131. this.calculateWavyLineSkyBottomLine(nextWavyLine.startVfVoiceEntry, nextWavyLine.endVfVoiceEntry, nextWavyLine, nextWavyLineStaffline);
  1132. }
  1133. }
  1134. graphicalWavyLine.CalculateBoundingBox();
  1135. this.calculateWavyLineSkyBottomLine(graphicalWavyLine.startVfVoiceEntry, graphicalWavyLine.endVfVoiceEntry, graphicalWavyLine, startStaffLine);
  1136. } else {
  1137. graphicalWavyLine.setEndNote(endStaffEntry);
  1138. graphicalWavyLine.CalculateBoundingBox();
  1139. this.calculateWavyLineSkyBottomLine(graphicalWavyLine.startVfVoiceEntry, graphicalWavyLine.endVfVoiceEntry, graphicalWavyLine, startStaffLine);
  1140. }
  1141. startStaffLine.WavyLines.push(graphicalWavyLine);
  1142. } else {
  1143. log.warn("End measure or staffLines for wavy line are undefined! This should not happen!");
  1144. }
  1145. }
  1146. private calculateWavyLineSkyBottomLine(startVfVoiceEntry: VexFlowVoiceEntry, endVfVoiceEntry: VexFlowVoiceEntry,
  1147. vfVibratoBracket: VexflowVibratoBracket, parentStaffline: StaffLine): void {
  1148. const startStave: Vex.Flow.Stave = vfVibratoBracket.startNote.getStave();
  1149. const endStave: Vex.Flow.Stave = vfVibratoBracket.endNote.getStave();
  1150. //In VF Line positions, need to negate for our units
  1151. const highestVFTopTextPosition: number = Math.max(
  1152. startStave.options.top_text_position,
  1153. endStave.options.top_text_position
  1154. );
  1155. //Whichever is higher, set the other to match
  1156. startStave.options.top_text_position = highestVFTopTextPosition;
  1157. endStave.options.top_text_position = highestVFTopTextPosition;
  1158. let headroom: number = -highestVFTopTextPosition;
  1159. let trillStartX: number = 0;
  1160. let trillEndX: number = 0;
  1161. let trillSkyline: number = Infinity;
  1162. let trillWavyLineBottom: number = Infinity;
  1163. const TRILL_HEIGHT: number = 1.85;
  1164. let startX: number = startVfVoiceEntry.PositionAndShape.AbsolutePosition.x + startVfVoiceEntry.PositionAndShape.BorderLeft;
  1165. if (startVfVoiceEntry.parentVoiceEntry?.OrnamentContainer?.GetOrnament === OrnamentEnum.Trill) {
  1166. trillStartX = startX;
  1167. //Width of trill mark
  1168. startX += 2;
  1169. trillEndX = startX;
  1170. //Since the trill mark is not managed or calculated by our bounding boxes, we have to get the location this way
  1171. //Also at this point the skyline has already been updated with the trill mark. So we can't determine if it should go lower
  1172. //Need to trust Vexflow later on, unless the wavy line must be rendered higher
  1173. trillSkyline = parentStaffline.SkyBottomLineCalculator.getSkyLineMinInRange(trillStartX, trillEndX);
  1174. //height of the trill mark
  1175. trillWavyLineBottom = trillSkyline + TRILL_HEIGHT;
  1176. }
  1177. let stopX: number = undefined;
  1178. //If the end of the line is the last note in the measure, go all the way to the end of the stave
  1179. if(vfVibratoBracket.ToEndOfStopStave) {
  1180. //vexflow backs off by 1 unit (10 pixels) from stave edge
  1181. stopX = endVfVoiceEntry.parentStaffEntry.parentMeasure.PositionAndShape.AbsolutePosition.x +
  1182. endVfVoiceEntry.parentStaffEntry.parentMeasure.PositionAndShape.BorderRight - 1;
  1183. } else {
  1184. stopX = endVfVoiceEntry.PositionAndShape.AbsolutePosition.x + endVfVoiceEntry.PositionAndShape.BorderRight;
  1185. //Take into account in-staff clefs associated with the staff entry (they modify the bounding box position)
  1186. const vfClefBefore: Vex.Flow.ClefNote = (endVfVoiceEntry.parentStaffEntry as VexFlowStaffEntry).vfClefBefore;
  1187. if (vfClefBefore) {
  1188. const clefWidth: number = vfClefBefore.getWidth() / 10;
  1189. stopX += clefWidth;
  1190. }
  1191. }
  1192. headroom = parentStaffline.SkyBottomLineCalculator.getSkyLineMinInRange(startX, stopX);
  1193. if (headroom === Infinity) { // will cause Vexflow error
  1194. return;
  1195. }
  1196. //If somewhere in our wavy line path we have to render higher than where the trill mark is set...
  1197. if (headroom < trillSkyline) {
  1198. startStave.options.top_text_position = -headroom;
  1199. endStave.options.top_text_position = -headroom;
  1200. //A decent enough approximation. Better than recalculating via Canvas or SVG sampling
  1201. parentStaffline.SkyBottomLineCalculator.updateSkyLineInRange(trillStartX, trillEndX, headroom - TRILL_HEIGHT);
  1202. } else { //Else just render where Vexflow has set the trill mark
  1203. vfVibratoBracket.line = -trillWavyLineBottom;
  1204. headroom = trillWavyLineBottom;
  1205. }
  1206. //Update skyline to include height of the wavy line
  1207. headroom -= vfVibratoBracket.PositionAndShape.Size.height;
  1208. parentStaffline.SkyBottomLineCalculator.updateSkyLineInRange(startX, stopX, headroom);
  1209. }
  1210. private calculatePedalSkyBottomLine(startVfVoiceEntry: VexFlowVoiceEntry, endVfVoiceEntry: VexFlowVoiceEntry,
  1211. vfPedal: VexFlowPedal, parentStaffline: StaffLine): void {
  1212. let endBbox: BoundingBox = endVfVoiceEntry?.PositionAndShape;
  1213. if (!endBbox) {
  1214. endBbox = vfPedal.endMeasure.PositionAndShape;
  1215. }
  1216. //Just for shorthand. Easier readability below
  1217. const PEDAL_STYLES_ENUM: any = Vex.Flow.PedalMarking.Styles;
  1218. const pedalMarking: any = vfPedal.getPedalMarking();
  1219. //VF adds 3 lines to whatever the pedal line is set to.
  1220. //VF also measures from the bottom line, whereas our bottom line is from the top staff line
  1221. const yLineForPedalMarking: number = (pedalMarking.line + 3 + (parentStaffline.StaffLines.length - 1));
  1222. //VF Uses a margin offset for rendering. Take this into account
  1223. const pedalMarkingMarginXOffset: number = pedalMarking.render_options.text_margin_right / 10;
  1224. //TODO: Most of this should be in the bounding box calculation
  1225. let startX: number = startVfVoiceEntry.PositionAndShape.AbsolutePosition.x - pedalMarkingMarginXOffset;
  1226. if (pedalMarking.style === PEDAL_STYLES_ENUM.MIXED ||
  1227. pedalMarking.style === PEDAL_STYLES_ENUM.MIXED_OPEN_END ||
  1228. pedalMarking.style === PEDAL_STYLES_ENUM.TEXT) {
  1229. //Accomodate the Ped. sign
  1230. startX -= 1;
  1231. }
  1232. let stopX: number = undefined;
  1233. let footroom: number = (parentStaffline.StaffLines.length - 1);
  1234. //Find the highest foot room in our staffline
  1235. for (const otherPedal of parentStaffline.Pedals) {
  1236. const vfOtherPedal: VexFlowPedal = otherPedal as VexFlowPedal;
  1237. const otherPedalMarking: any = vfOtherPedal.getPedalMarking();
  1238. const yLineForOtherPedalMarking: number = (otherPedalMarking.line + 3 + (parentStaffline.StaffLines.length - 1));
  1239. footroom = Math.max(yLineForOtherPedalMarking, footroom);
  1240. }
  1241. //We have the two seperate symbols, with two bounding boxes
  1242. if (vfPedal.EndSymbolPositionAndShape) {
  1243. const symbolHalfHeight: number = pedalMarking.render_options.glyph_point_size / 20;
  1244. //Width of the Ped. symbol
  1245. stopX = startX + 3.4;
  1246. const startX2: number = endBbox.AbsolutePosition.x - pedalMarkingMarginXOffset;
  1247. //Width of * symbol
  1248. const stopX2: number = startX2 + 1.5;
  1249. footroom = Math.max(parentStaffline.SkyBottomLineCalculator.getBottomLineMaxInRange(startX, stopX), footroom);
  1250. footroom = Math.max(yLineForPedalMarking + symbolHalfHeight * 2, footroom);
  1251. const footroom2: number = parentStaffline.SkyBottomLineCalculator.getBottomLineMaxInRange(startX2, stopX2);
  1252. //If Depress text is set, means we are not rendering the begin label (we are just rendering the end one)
  1253. if (!vfPedal.DepressText) {
  1254. footroom = Math.max(footroom, footroom2);
  1255. }
  1256. vfPedal.setLine(footroom - 3 - (parentStaffline.StaffLines.length - 1));
  1257. parentStaffline.SkyBottomLineCalculator.updateBottomLineInRange(startX, stopX, footroom + symbolHalfHeight);
  1258. parentStaffline.SkyBottomLineCalculator.updateBottomLineInRange(startX2, stopX2, footroom + symbolHalfHeight);
  1259. } else {
  1260. const bracketHeight: number = pedalMarking.render_options.bracket_height / 10;
  1261. if(pedalMarking.EndsStave){
  1262. if(endVfVoiceEntry){
  1263. stopX = endVfVoiceEntry.parentStaffEntry.parentMeasure.PositionAndShape.AbsolutePosition.x +
  1264. endVfVoiceEntry.parentStaffEntry.parentMeasure.PositionAndShape.Size.width - pedalMarkingMarginXOffset;
  1265. } else {
  1266. stopX = endBbox.AbsolutePosition.x + endBbox.Size.width;
  1267. }
  1268. } else {
  1269. switch (pedalMarking.style) {
  1270. case PEDAL_STYLES_ENUM.BRACKET_OPEN_END:
  1271. case PEDAL_STYLES_ENUM.BRACKET_OPEN_BOTH:
  1272. case PEDAL_STYLES_ENUM.MIXED_OPEN_END:
  1273. stopX = endBbox.AbsolutePosition.x + endBbox.BorderRight - pedalMarkingMarginXOffset;
  1274. break;
  1275. default:
  1276. stopX = endBbox.AbsolutePosition.x + endBbox.BorderLeft - pedalMarkingMarginXOffset;
  1277. break;
  1278. }
  1279. }
  1280. //Take into account in-staff clefs associated with the staff entry (they modify the bounding box position)
  1281. const vfClefBefore: Vex.Flow.ClefNote = (endVfVoiceEntry?.parentStaffEntry as VexFlowStaffEntry)?.vfClefBefore;
  1282. if (vfClefBefore) {
  1283. const clefWidth: number = vfClefBefore.getWidth() / 10;
  1284. stopX += clefWidth;
  1285. }
  1286. footroom = Math.max(parentStaffline.SkyBottomLineCalculator.getBottomLineMaxInRange(startX, stopX), footroom);
  1287. if (footroom === Infinity) { // will cause Vexflow error
  1288. return;
  1289. }
  1290. //Whatever is currently lower - the set render height of the begin vf stave, the set render height of the end vf stave,
  1291. //or the bottom line. Use that as the render height of both staves
  1292. footroom = Math.max(footroom, yLineForPedalMarking + bracketHeight);
  1293. vfPedal.setLine(footroom - 3 - (parentStaffline.StaffLines.length - 1));
  1294. if (startX > stopX) { // TODO hotfix for skybottomlinecalculator after pedal no endNote fix
  1295. const newStart: number = stopX;
  1296. stopX = startX;
  1297. startX = newStart;
  1298. }
  1299. parentStaffline.SkyBottomLineCalculator.updateBottomLineInRange(startX, stopX, footroom + bracketHeight);
  1300. }
  1301. //If our current pedal is below the other pedals in this staffline, set them all to this height
  1302. for (const otherPedal of parentStaffline.Pedals) {
  1303. const vfOtherPedal: VexFlowPedal = otherPedal as VexFlowPedal;
  1304. const otherPedalMarking: any = vfOtherPedal.getPedalMarking();
  1305. const yLineForOtherPedalMarking: number = (otherPedalMarking.line + 3 + (parentStaffline.StaffLines.length - 1));
  1306. //Only do these changes if current footroom is higher
  1307. if(footroom > yLineForOtherPedalMarking) {
  1308. const otherPedalMarkingMarginXOffset: number = otherPedalMarking.render_options.text_margin_right / 10;
  1309. const otherPedalStartX: number = vfOtherPedal.startVfVoiceEntry.PositionAndShape.AbsolutePosition.x - otherPedalMarkingMarginXOffset;
  1310. let otherPedalStopX: number = undefined;
  1311. vfOtherPedal.setLine(footroom - 3 - (parentStaffline.StaffLines.length - 1));
  1312. let otherPedalEndBBox: BoundingBox = vfOtherPedal.endVfVoiceEntry?.PositionAndShape;
  1313. if (!otherPedalEndBBox) {
  1314. otherPedalEndBBox = vfOtherPedal.endMeasure.PositionAndShape;
  1315. }
  1316. if (vfOtherPedal.EndSymbolPositionAndShape) {
  1317. const otherSymbolHalfHeight: number = pedalMarking.render_options.glyph_point_size / 20;
  1318. //Width of the Ped. symbol
  1319. otherPedalStopX = otherPedalStartX + 3.4;
  1320. const otherPedalStartX2: number = otherPedalEndBBox.AbsolutePosition.x - otherPedalMarkingMarginXOffset;
  1321. //Width of * symbol
  1322. const otherPedalStopX2: number = otherPedalStartX2 + 1.5;
  1323. parentStaffline.SkyBottomLineCalculator.updateBottomLineInRange(otherPedalStartX, otherPedalStopX, footroom + otherSymbolHalfHeight);
  1324. parentStaffline.SkyBottomLineCalculator.updateBottomLineInRange(otherPedalStartX2, otherPedalStopX2, footroom + otherSymbolHalfHeight);
  1325. } else {
  1326. const otherPedalBracketHeight: number = otherPedalMarking.render_options.bracket_height / 10;
  1327. if(otherPedalMarking.EndsStave){
  1328. otherPedalStopX = otherPedalEndBBox.AbsolutePosition.x + otherPedalEndBBox.Size.width - otherPedalMarkingMarginXOffset;
  1329. } else {
  1330. switch (pedalMarking.style) {
  1331. case PEDAL_STYLES_ENUM.BRACKET_OPEN_END:
  1332. case PEDAL_STYLES_ENUM.BRACKET_OPEN_BOTH:
  1333. case PEDAL_STYLES_ENUM.MIXED_OPEN_END:
  1334. otherPedalStopX = otherPedalEndBBox.AbsolutePosition.x + otherPedalEndBBox.BorderRight - otherPedalMarkingMarginXOffset;
  1335. break;
  1336. default:
  1337. otherPedalStopX = otherPedalEndBBox.AbsolutePosition.x + otherPedalEndBBox.BorderLeft - otherPedalMarkingMarginXOffset;
  1338. break;
  1339. }
  1340. }
  1341. //Take into account in-staff clefs associated with the staff entry (they modify the bounding box position)
  1342. const vfOtherClefBefore: Vex.Flow.ClefNote = (vfOtherPedal.endVfVoiceEntry?.parentStaffEntry as VexFlowStaffEntry)?.vfClefBefore;
  1343. if (vfOtherClefBefore) {
  1344. const otherClefWidth: number = vfOtherClefBefore.getWidth() / 10;
  1345. otherPedalStopX += otherClefWidth;
  1346. }
  1347. parentStaffline.SkyBottomLineCalculator.updateBottomLineInRange(otherPedalStartX, otherPedalStopX, footroom + otherPedalBracketHeight);
  1348. }
  1349. }
  1350. }
  1351. }
  1352. private calculateOctaveShiftSkyBottomLine(startStaffEntry: GraphicalStaffEntry, endStaffEntry: GraphicalStaffEntry,
  1353. vfOctaveShift: VexFlowOctaveShift, parentStaffline: StaffLine): void {
  1354. if (!endStaffEntry) {
  1355. log.warn("octaveshift: no endStaffEntry");
  1356. return;
  1357. }
  1358. let startXOffset: number = startStaffEntry.PositionAndShape.Size.width;
  1359. let endXOffset: number = endStaffEntry.PositionAndShape.Size.width;
  1360. //Vexflow renders differently with rests
  1361. if (startStaffEntry.hasOnlyRests()) {
  1362. startXOffset = -startXOffset;
  1363. } else {
  1364. startXOffset /= 2;
  1365. }
  1366. if (!endStaffEntry.hasOnlyRests()) {
  1367. endXOffset /= 2;
  1368. } else {
  1369. endXOffset *= 2;
  1370. }
  1371. if (startStaffEntry === endStaffEntry) {
  1372. endXOffset *= 2;
  1373. }
  1374. const startX: number = startStaffEntry.PositionAndShape.AbsolutePosition.x - startXOffset;
  1375. const stopX: number = endStaffEntry.PositionAndShape.AbsolutePosition.x + endXOffset;
  1376. vfOctaveShift.PositionAndShape.Size.width = startX - stopX;
  1377. const textBracket: Vex.Flow.TextBracket = vfOctaveShift.getTextBracket();
  1378. const fontSize: number = (textBracket as any).font.size / 10;
  1379. if ((<any>textBracket).position === Vex.Flow.TextBracket.Positions.TOP) {
  1380. const headroom: number = Math.ceil(parentStaffline.SkyBottomLineCalculator.getSkyLineMinInRange(startX, stopX));
  1381. if (headroom === Infinity) { // will cause Vexflow error
  1382. return;
  1383. }
  1384. (textBracket.start.getStave().options as any).top_text_position = Math.abs(headroom);
  1385. parentStaffline.SkyBottomLineCalculator.updateSkyLineInRange(startX, stopX, headroom - fontSize * 2);
  1386. } else {
  1387. const footroom: number = parentStaffline.SkyBottomLineCalculator.getBottomLineMaxInRange(startX, stopX);
  1388. if (footroom === Infinity) { // will cause Vexflow error
  1389. return;
  1390. }
  1391. (textBracket.start.getStave().options as any).bottom_text_position = footroom;
  1392. if (startStaffEntry.parentMeasure !== endStaffEntry.parentMeasure) {
  1393. (textBracket.stop.getStave().options as any).bottom_text_position = footroom;
  1394. }
  1395. //Vexflow positions top vs. bottom text in a slightly inconsistent way it seems
  1396. parentStaffline.SkyBottomLineCalculator.updateBottomLineInRange(startX, stopX, footroom + fontSize * 1.5);
  1397. }
  1398. }
  1399. /**
  1400. * Calculate all the textual and symbolic [[RepetitionInstruction]]s (e.g. dal segno) for a single [[SourceMeasure]].
  1401. * @param repetitionInstruction
  1402. * @param measureIndex
  1403. */
  1404. protected calculateWordRepetitionInstruction(repetitionInstruction: RepetitionInstruction, measureIndex: number): void {
  1405. // find first visible StaffLine
  1406. let uppermostMeasure: VexFlowMeasure = undefined;
  1407. const measures: VexFlowMeasure[] = <VexFlowMeasure[]>this.graphicalMusicSheet.MeasureList[measureIndex];
  1408. for (let idx: number = 0, len: number = measures.length; idx < len; ++idx) {
  1409. const graphicalMeasure: VexFlowMeasure = measures[idx];
  1410. if (graphicalMeasure && graphicalMeasure.ParentStaffLine && graphicalMeasure.ParentStaff.ParentInstrument.Visible) {
  1411. uppermostMeasure = <VexFlowMeasure>graphicalMeasure;
  1412. break;
  1413. }
  1414. }
  1415. // ToDo: feature/Repetitions
  1416. // now create corresponding graphical symbol or Text in VexFlow:
  1417. // use top measure and staffline for positioning.
  1418. if (uppermostMeasure) {
  1419. uppermostMeasure.addWordRepetition(repetitionInstruction);
  1420. }
  1421. }
  1422. /**
  1423. * Re-adjust the x positioning of expressions. Update the skyline afterwards
  1424. */
  1425. protected calculateExpressionAlignements(): void {
  1426. for (const musicSystem of this.musicSystems) {
  1427. for (const staffLine of musicSystem.StaffLines) {
  1428. try {
  1429. (<VexFlowStaffLine>staffLine).AlignmentManager.alignDynamicExpressions();
  1430. staffLine.AbstractExpressions.forEach(ae => {
  1431. ae.updateSkyBottomLine();
  1432. });
  1433. } catch (e) {
  1434. // TODO still necessary when calculation of expression fails, see calculateDynamicExpressionsForMultiExpression()
  1435. // see calculateGraphicalContinuousDynamic(), also in MusicSheetCalculator.
  1436. }
  1437. }
  1438. }
  1439. }
  1440. /**
  1441. * Check if the tied graphical note belongs to any beams or tuplets and react accordingly.
  1442. * @param tiedGraphicalNote
  1443. * @param beams
  1444. * @param activeClef
  1445. * @param octaveShiftValue
  1446. * @param graphicalStaffEntry
  1447. * @param duration
  1448. * @param openTie
  1449. * @param isLastTieNote
  1450. */
  1451. protected handleTiedGraphicalNote(tiedGraphicalNote: GraphicalNote, beams: Beam[], activeClef: ClefInstruction,
  1452. octaveShiftValue: OctaveEnum, graphicalStaffEntry: GraphicalStaffEntry, duration: Fraction,
  1453. openTie: Tie, isLastTieNote: boolean): void {
  1454. return;
  1455. }
  1456. /**
  1457. * Is called if a note is part of a beam.
  1458. * @param graphicalNote
  1459. * @param beam
  1460. * @param openBeams a list of all currently open beams
  1461. */
  1462. protected handleBeam(graphicalNote: GraphicalNote, beam: Beam, openBeams: Beam[]): void {
  1463. (graphicalNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure).handleBeam(graphicalNote, beam);
  1464. }
  1465. protected handleVoiceEntryLyrics(voiceEntry: VoiceEntry, graphicalStaffEntry: GraphicalStaffEntry, lyricWords: LyricWord[]): void {
  1466. voiceEntry.LyricsEntries.forEach((key: number, lyricsEntry: LyricsEntry) => {
  1467. const graphicalLyricEntry: GraphicalLyricEntry = new GraphicalLyricEntry(lyricsEntry,
  1468. graphicalStaffEntry,
  1469. this.rules.LyricsHeight,
  1470. this.rules.StaffHeight);
  1471. graphicalStaffEntry.LyricsEntries.push(graphicalLyricEntry);
  1472. // create corresponding GraphicalLabel
  1473. const graphicalLabel: GraphicalLabel = graphicalLyricEntry.GraphicalLabel;
  1474. graphicalLabel.setLabelPositionAndShapeBorders();
  1475. if (lyricsEntry.Word) {
  1476. const lyricsEntryIndex: number = lyricsEntry.Word.Syllables.indexOf(lyricsEntry);
  1477. let index: number = lyricWords.indexOf(lyricsEntry.Word);
  1478. if (index === -1) {
  1479. lyricWords.push(lyricsEntry.Word);
  1480. index = lyricWords.indexOf(lyricsEntry.Word);
  1481. }
  1482. if (this.graphicalLyricWords.length === 0 || index > this.graphicalLyricWords.length - 1) {
  1483. const graphicalLyricWord: GraphicalLyricWord = new GraphicalLyricWord(lyricsEntry.Word);
  1484. graphicalLyricEntry.ParentLyricWord = graphicalLyricWord;
  1485. graphicalLyricWord.GraphicalLyricsEntries[lyricsEntryIndex] = graphicalLyricEntry;
  1486. this.graphicalLyricWords.push(graphicalLyricWord);
  1487. } else {
  1488. const graphicalLyricWord: GraphicalLyricWord = this.graphicalLyricWords[index];
  1489. graphicalLyricEntry.ParentLyricWord = graphicalLyricWord;
  1490. graphicalLyricWord.GraphicalLyricsEntries[lyricsEntryIndex] = graphicalLyricEntry;
  1491. if (graphicalLyricWord.isFilled()) {
  1492. lyricWords.splice(index, 1);
  1493. this.graphicalLyricWords.splice(this.graphicalLyricWords.indexOf(graphicalLyricWord), 1);
  1494. }
  1495. }
  1496. }
  1497. });
  1498. }
  1499. protected handleVoiceEntryOrnaments(ornamentContainer: OrnamentContainer, voiceEntry: VoiceEntry, graphicalStaffEntry: GraphicalStaffEntry): void {
  1500. return;
  1501. }
  1502. /**
  1503. * Add articulations to the given vexflow staff entry.
  1504. * @param articulations
  1505. * @param voiceEntry
  1506. * @param graphicalStaffEntry
  1507. */
  1508. protected handleVoiceEntryArticulations(articulations: Articulation[],
  1509. voiceEntry: VoiceEntry, staffEntry: GraphicalStaffEntry): void {
  1510. // uncomment this when implementing:
  1511. // let vfse: VexFlowStaffEntry = (graphicalStaffEntry as VexFlowStaffEntry);
  1512. return;
  1513. }
  1514. /**
  1515. * Add technical instructions to the given vexflow staff entry.
  1516. * @param technicalInstructions
  1517. * @param voiceEntry
  1518. * @param staffEntry
  1519. */
  1520. protected handleVoiceEntryTechnicalInstructions(technicalInstructions: TechnicalInstruction[],
  1521. voiceEntry: VoiceEntry, staffEntry: GraphicalStaffEntry): void {
  1522. // uncomment this when implementing:
  1523. // let vfse: VexFlowStaffEntry = (graphicalStaffEntry as VexFlowStaffEntry);
  1524. return;
  1525. }
  1526. /**
  1527. * Is called if a note is part of a tuplet.
  1528. * @param graphicalNote
  1529. * @param tuplet
  1530. * @param openTuplets a list of all currently open tuplets
  1531. */
  1532. protected handleTuplet(graphicalNote: GraphicalNote, tuplet: Tuplet, openTuplets: Tuplet[]): void {
  1533. (graphicalNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure).handleTuplet(graphicalNote, tuplet);
  1534. }
  1535. /**
  1536. * Find the Index of the item of the array of all VexFlow Slurs that holds a specified slur
  1537. * @param gSlurs
  1538. * @param slur
  1539. */
  1540. public findIndexGraphicalSlurFromSlur(gSlurs: GraphicalSlur[], slur: Slur): number {
  1541. for (let slurIndex: number = 0; slurIndex < gSlurs.length; slurIndex++) {
  1542. if (gSlurs[slurIndex].slur === slur) {
  1543. return slurIndex;
  1544. }
  1545. }
  1546. return -1;
  1547. }
  1548. /* VexFlow Version - for later use
  1549. public findIndexVFSlurFromSlur(vfSlurs: VexFlowSlur[], slur: Slur): number {
  1550. for (let slurIndex: number = 0; slurIndex < vfSlurs.length; slurIndex++) {
  1551. if (vfSlurs[slurIndex].vfSlur === slur) {
  1552. return slurIndex;
  1553. }
  1554. }
  1555. }
  1556. */
  1557. // Generate all Graphical Slurs and attach them to the staffline
  1558. protected calculateSlurs(): void {
  1559. const openSlursDict: { [staffId: number]: GraphicalSlur[] } = {};
  1560. for (const graphicalMeasure of this.graphicalMusicSheet.MeasureList[0]) { //let i: number = 0; i < this.graphicalMusicSheet.MeasureList[0].length; i++) {
  1561. openSlursDict[graphicalMeasure.ParentStaff.idInMusicSheet] = [];
  1562. }
  1563. /* VexFlow Version - for later use
  1564. // Generate an empty dictonary to index an array of VexFlowSlur classes
  1565. const vfOpenSlursDict: { [staffId: number]: VexFlowSlur[]; } = {}; //VexFlowSlur[]; } = {};
  1566. // use first SourceMeasure to get all graphical measures to know how many staves are currently visible in this musicsheet
  1567. // foreach stave: create an empty array. It can later hold open slurs.
  1568. // Measure how many staves are visible and reserve space for them.
  1569. for (const graphicalMeasure of this.graphicalMusicSheet.MeasureList[0]) { //let i: number = 0; i < this.graphicalMusicSheet.MeasureList[0].length; i++) {
  1570. vfOpenSlursDict[graphicalMeasure.ParentStaff.idInMusicSheet] = [];
  1571. }
  1572. */
  1573. for (const musicSystem of this.musicSystems) {
  1574. for (const staffLine of musicSystem.StaffLines) {
  1575. // if a graphical slur reaches out of the last musicsystem, we have to create another graphical slur reaching into this musicsystem
  1576. // (one slur needs 2 graphical slurs)
  1577. const openGraphicalSlurs: GraphicalSlur[] = openSlursDict[staffLine.ParentStaff.idInMusicSheet];
  1578. for (let slurIndex: number = 0; slurIndex < openGraphicalSlurs.length; slurIndex++) {
  1579. const oldGSlur: GraphicalSlur = openGraphicalSlurs[slurIndex];
  1580. const newGSlur: GraphicalSlur = new GraphicalSlur(oldGSlur.slur, this.rules); //Graphicalslur.createFromSlur(oldSlur);
  1581. staffLine.addSlurToStaffline(newGSlur); // every VFSlur is added to the array in the VFStaffline!
  1582. openGraphicalSlurs[slurIndex] = newGSlur;
  1583. }
  1584. /* VexFlow Version - for later use
  1585. const vfOpenSlurs: VexFlowSlur[] = vfOpenSlursDict[staffLine.ParentStaff.idInMusicSheet];
  1586. const vfStaffLine: VexFlowStaffLine = <VexFlowStaffLine> staffLine;
  1587. for (let slurIndex: number = 0; slurIndex < vfOpenSlurs.length; slurIndex++) {
  1588. const oldVFSlur: VexFlowSlur = vfOpenSlurs[slurIndex];
  1589. const newVFSlur: VexFlowSlur = VexFlowSlur.createFromVexflowSlur(oldVFSlur);
  1590. newVFSlur.vfStartNote = undefined;
  1591. vfStaffLine.addVFSlurToVFStaffline(newVFSlur); // every VFSlur is added to the array in the VFStaffline!
  1592. vfOpenSlurs[slurIndex] = newVFSlur;
  1593. }
  1594. */
  1595. // add reference of slur array to the VexFlowStaffline class
  1596. for (const graphicalMeasure of staffLine.Measures) {
  1597. for (const graphicalStaffEntry of graphicalMeasure.staffEntries) {
  1598. // loop over "normal" notes (= no gracenotes)
  1599. for (const graphicalVoiceEntry of graphicalStaffEntry.graphicalVoiceEntries) {
  1600. for (const graphicalNote of graphicalVoiceEntry.notes) {
  1601. for (const slur of graphicalNote.sourceNote.NoteSlurs) {
  1602. // extra check for some MusicSheets that have openSlurs (because only the first Page is available -> Recordare files)
  1603. if (!slur.EndNote || !slur.StartNote) {
  1604. continue;
  1605. }
  1606. // add new VexFlowSlur to List
  1607. if (slur.StartNote === graphicalNote.sourceNote) {
  1608. // TODO the following seems to have been intended to prevent unnecessary slurs that overlap ties,
  1609. // but it simply leads to correct slurs being left out where the tie end note is the slur start note.
  1610. // visual regression tests simply show valid slurs being left out in 4 samples.
  1611. // if (graphicalNote.sourceNote.NoteTie) {
  1612. // if (graphicalNote.parentVoiceEntry.parentStaffEntry.getAbsoluteTimestamp() !==
  1613. // graphicalNote.sourceNote.NoteTie.StartNote.getAbsoluteTimestamp()) {
  1614. // break;
  1615. // }
  1616. // }
  1617. // Add a Graphical Slur to the staffline, if the recent note is the Startnote of a slur
  1618. const gSlur: GraphicalSlur = new GraphicalSlur(slur, this.rules);
  1619. openGraphicalSlurs.push(gSlur);
  1620. staffLine.addSlurToStaffline(gSlur);
  1621. /* VexFlow Version - for later use
  1622. const vfSlur: VexFlowSlur = new VexFlowSlur(slur);
  1623. vfOpenSlurs.push(vfSlur); //add open... adding / removing is JUST DONE in the open... array
  1624. vfSlur.vfStartNote = (graphicalVoiceEntry as VexFlowVoiceEntry).vfStaveNote;
  1625. vfStaffLine.addVFSlurToVFStaffline(vfSlur); // every VFSlur is added to the array in the VFStaffline!
  1626. */
  1627. }
  1628. if (slur.EndNote === graphicalNote.sourceNote) {
  1629. // Remove the Graphical Slur from the staffline if the note is the Endnote of a slur
  1630. const index: number = this.findIndexGraphicalSlurFromSlur(openGraphicalSlurs, slur);
  1631. if (index >= 0) {
  1632. // save Voice Entry in VFSlur and then remove it from array of open VFSlurs
  1633. const gSlur: GraphicalSlur = openGraphicalSlurs[index];
  1634. if (gSlur.staffEntries.indexOf(graphicalStaffEntry) === -1) {
  1635. gSlur.staffEntries.push(graphicalStaffEntry);
  1636. }
  1637. openGraphicalSlurs.splice(index, 1);
  1638. }
  1639. /* VexFlow Version - for later use
  1640. const vfIndex: number = this.findIndexVFSlurFromSlur(vfOpenSlurs, slur);
  1641. if (vfIndex !== undefined) {
  1642. // save Voice Entry in VFSlur and then remove it from array of open VFSlurs
  1643. const vfSlur: VexFlowSlur = vfOpenSlurs[vfIndex];
  1644. vfSlur.vfEndNote = (graphicalVoiceEntry as VexFlowVoiceEntry).vfStaveNote;
  1645. vfSlur.createVexFlowCurve();
  1646. vfOpenSlurs.splice(vfIndex, 1);
  1647. }
  1648. */
  1649. }
  1650. }
  1651. }
  1652. }
  1653. //add the present Staffentry to all open slurs that don't contain this Staffentry already
  1654. for (const gSlur of openGraphicalSlurs) {
  1655. if (gSlur.staffEntries.indexOf(graphicalStaffEntry) === -1) {
  1656. gSlur.staffEntries.push(graphicalStaffEntry);
  1657. }
  1658. }
  1659. } // loop over StaffEntries
  1660. } // loop over Measures
  1661. } // loop over StaffLines
  1662. // Attach vfSlur array to the vfStaffline to be drawn
  1663. //vfStaffLine.SlursInVFStaffLine = vfSlurs;
  1664. } // loop over MusicSystems
  1665. // order slurs that were saved to the Staffline
  1666. for (const musicSystem of this.musicSystems) {
  1667. for (const staffLine of musicSystem.StaffLines) {
  1668. // Sort all gSlurs in the staffline using the Compare function in class GraphicalSlurSorter
  1669. const sortedGSlurs: GraphicalSlur[] = staffLine.GraphicalSlurs.sort(GraphicalSlur.Compare);
  1670. for (const gSlur of sortedGSlurs) {
  1671. // crossed slurs will be handled later:
  1672. if (gSlur.slur.isCrossed()) {
  1673. continue;
  1674. }
  1675. gSlur.calculateCurve(this.rules);
  1676. }
  1677. }
  1678. }
  1679. }
  1680. }