VexFlowConverter.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. import Vex from "vexflow";
  2. import {ClefEnum} from "../../VoiceData/Instructions/ClefInstruction";
  3. import {ClefInstruction} from "../../VoiceData/Instructions/ClefInstruction";
  4. import {Pitch} from "../../../Common/DataObjects/Pitch";
  5. import {Fraction} from "../../../Common/DataObjects/Fraction";
  6. import {RhythmInstruction} from "../../VoiceData/Instructions/RhythmInstruction";
  7. import {RhythmSymbolEnum} from "../../VoiceData/Instructions/RhythmInstruction";
  8. import {KeyInstruction} from "../../VoiceData/Instructions/KeyInstruction";
  9. import {KeyEnum} from "../../VoiceData/Instructions/KeyInstruction";
  10. import {AccidentalEnum} from "../../../Common/DataObjects/Pitch";
  11. import {NoteEnum} from "../../../Common/DataObjects/Pitch";
  12. import {VexFlowGraphicalNote} from "./VexFlowGraphicalNote";
  13. import {GraphicalNote} from "../GraphicalNote";
  14. import {SystemLinesEnum} from "../SystemLinesEnum";
  15. import {FontStyles} from "../../../Common/Enums/FontStyles";
  16. import {Fonts} from "../../../Common/Enums/Fonts";
  17. import {OutlineAndFillStyleEnum, OUTLINE_AND_FILL_STYLE_DICT} from "../DrawingEnums";
  18. import log from "loglevel";
  19. import { ArticulationEnum, StemDirectionType } from "../../VoiceData/VoiceEntry";
  20. import { SystemLinePosition } from "../SystemLinePosition";
  21. import { GraphicalVoiceEntry } from "../GraphicalVoiceEntry";
  22. import { OrnamentEnum, OrnamentContainer } from "../../VoiceData/OrnamentContainer";
  23. import { Notehead, NoteHeadShape } from "../../VoiceData/Notehead";
  24. import { unitInPixels } from "./VexFlowMusicSheetDrawer";
  25. import { EngravingRules } from "../EngravingRules";
  26. import { Note } from "../..";
  27. import StaveNote = Vex.Flow.StaveNote;
  28. import { ArpeggioType } from "../../VoiceData";
  29. import { TabNote } from "../../VoiceData/TabNote";
  30. /**
  31. * Helper class, which contains static methods which actually convert
  32. * from OSMD objects to VexFlow objects.
  33. */
  34. export class VexFlowConverter {
  35. /**
  36. * Mapping from numbers of alterations on the key signature to major keys
  37. * @type {[alterationsNo: number]: string; }
  38. */
  39. private static majorMap: {[_: number]: string; } = {
  40. "-1": "F", "-2": "Bb", "-3": "Eb", "-4": "Ab", "-5": "Db", "-6": "Gb", "-7": "Cb", "-8": "Fb",
  41. "0": "C", "1": "G", "2": "D", "3": "A", "4": "E", "5": "B", "6": "F#", "7": "C#", "8": "G#"
  42. };
  43. /**
  44. * Mapping from numbers of alterations on the key signature to minor keys
  45. * @type {[alterationsNo: number]: string; }
  46. */
  47. private static minorMap: {[_: number]: string; } = {
  48. "-1": "D", "-2": "G", "-3": "C", "-4": "F", "-5": "Bb", "-6": "Eb", "-7": "Ab", "-8": "Db",
  49. "0": "A", "1": "E", "2": "B", "3": "F#", "4": "C#", "5": "G#", "6": "D#", "7": "A#", "8": "E#"
  50. };
  51. /**
  52. * Convert a fraction to a string which represents a duration in VexFlow
  53. * @param fraction a fraction representing the duration of a note
  54. * @returns {string}
  55. */
  56. public static duration(fraction: Fraction, isTuplet: boolean): string {
  57. const dur: number = fraction.RealValue;
  58. if (dur >= 1) {
  59. return "w";
  60. } else if (dur < 1 && dur >= 0.5) {
  61. // change to the next higher straight note to get the correct note display type
  62. if (isTuplet && dur > 0.5) {
  63. return "w";
  64. }
  65. return "h";
  66. } else if (dur < 0.5 && dur >= 0.25) {
  67. // change to the next higher straight note to get the correct note display type
  68. if (isTuplet && dur > 0.25) {
  69. return "h";
  70. }
  71. return "q";
  72. } else if (dur < 0.25 && dur >= 0.125) {
  73. // change to the next higher straight note to get the correct note display type
  74. if (isTuplet && dur > 0.125) {
  75. return "q";
  76. }
  77. return "8";
  78. } else if (dur < 0.125 && dur >= 0.0625) {
  79. // change to the next higher straight note to get the correct note display type
  80. if (isTuplet && dur > 0.0625) {
  81. return "8";
  82. }
  83. return "16";
  84. } else if (dur < 0.0625 && dur >= 0.03125) {
  85. // change to the next higher straight note to get the correct note display type
  86. if (isTuplet && dur > 0.03125) {
  87. return "16";
  88. }
  89. return "32";
  90. } else if (dur < 0.03125 && dur >= 0.015625) {
  91. // change to the next higher straight note to get the correct note display type
  92. if (isTuplet && dur > 0.015625) {
  93. return "32";
  94. }
  95. return "64";
  96. }
  97. if (isTuplet) {
  98. return "64";
  99. }
  100. return "128";
  101. }
  102. /**
  103. * Takes a Pitch and returns a string representing a VexFlow pitch,
  104. * which has the form "b/4", plus its alteration (accidental)
  105. * @param pitch
  106. * @returns {string[]}
  107. */
  108. public static pitch(note: VexFlowGraphicalNote, pitch: Pitch): [string, string, ClefInstruction] {
  109. const fund: string = NoteEnum[pitch.FundamentalNote].toLowerCase();
  110. const acc: string = Pitch.accidentalVexflow(pitch.Accidental);
  111. // The octave seems to need a shift of three FIXME?
  112. const octave: number = pitch.Octave - note.Clef().OctaveOffset + 3;
  113. const notehead: Notehead = note.sourceNote.Notehead;
  114. let noteheadCode: string = "";
  115. if (notehead !== undefined) {
  116. noteheadCode = this.NoteHeadCode(notehead);
  117. }
  118. return [fund + "n/" + octave + noteheadCode, acc, note.Clef()];
  119. }
  120. /** returns the Vexflow code for a note head. Some are still unsupported, see Vexflow/tables.js */
  121. public static NoteHeadCode(notehead: Notehead): string {
  122. const codeStart: string = "/";
  123. const codeFilled: string = notehead.Filled ? "2" : "1"; // filled/unfilled notehead code in most vexflow glyphs
  124. switch (notehead.Shape) {
  125. case NoteHeadShape.NORMAL:
  126. return "";
  127. case NoteHeadShape.DIAMOND:
  128. return codeStart + "D" + codeFilled;
  129. case NoteHeadShape.TRIANGLE:
  130. return codeStart + "T" + codeFilled;
  131. case NoteHeadShape.X:
  132. return codeStart + "X" + codeFilled;
  133. case NoteHeadShape.CIRCLEX:
  134. return codeStart + "X3";
  135. case NoteHeadShape.RECTANGLE:
  136. return codeStart + "R" + codeFilled;
  137. case NoteHeadShape.SQUARE:
  138. return codeStart + "S" + codeFilled;
  139. case NoteHeadShape.SLASH:
  140. return ""; // slash is specified at end of duration string in Vexflow
  141. default:
  142. return "";
  143. }
  144. }
  145. public static GhostNote(frac: Fraction): Vex.Flow.GhostNote {
  146. return new Vex.Flow.GhostNote({
  147. duration: VexFlowConverter.duration(frac, false),
  148. });
  149. }
  150. /**
  151. * Convert a GraphicalVoiceEntry to a VexFlow StaveNote
  152. * @param gve the GraphicalVoiceEntry which can hold a note or a chord on the staff belonging to one voice
  153. * @returns {Vex.Flow.StaveNote}
  154. */
  155. public static StaveNote(gve: GraphicalVoiceEntry): Vex.Flow.StaveNote {
  156. // sort notes
  157. /* seems unnecessary for now
  158. if (gve.octaveShiftValue !== undefined && gve.octaveShiftValue !== OctaveEnum.NONE) {
  159. gve.sort(); // gves with accidentals in octave shift brackets can be unsorted
  160. } */
  161. // VexFlow needs the notes ordered vertically in the other direction:
  162. const notes: GraphicalNote[] = gve.notes.reverse();
  163. const rules: EngravingRules = gve.parentStaffEntry.parentMeasure.parentSourceMeasure.Rules;
  164. const baseNote: GraphicalNote = notes[0];
  165. let keys: string[] = [];
  166. const accidentals: string[] = [];
  167. const frac: Fraction = baseNote.graphicalNoteLength;
  168. const isTuplet: boolean = baseNote.sourceNote.NoteTuplet !== undefined;
  169. let duration: string = VexFlowConverter.duration(frac, isTuplet);
  170. if (baseNote.sourceNote.TypeLength !== undefined && baseNote.sourceNote.TypeLength !== frac) {
  171. duration = VexFlowConverter.duration(baseNote.sourceNote.TypeLength, isTuplet);
  172. }
  173. let vfClefType: string = undefined;
  174. let numDots: number = baseNote.numberOfDots;
  175. let alignCenter: boolean = false;
  176. let xShift: number = 0;
  177. let slashNoteHead: boolean = false;
  178. let isRest: boolean = false;
  179. for (const note of notes) {
  180. if (numDots < note.numberOfDots) {
  181. numDots = note.numberOfDots;
  182. }
  183. // if it is a rest:
  184. if (note.sourceNote.isRest()) {
  185. isRest = true;
  186. keys = ["b/4"];
  187. // TODO do collision checking, place rest e.g. either below staff (A3, for stem direction below voice) or above (C5)
  188. // if it is a full measure rest:
  189. if (note.parentVoiceEntry.parentStaffEntry.parentMeasure.parentSourceMeasure.Duration.RealValue <= frac.RealValue) {
  190. keys = ["d/5"];
  191. duration = "w";
  192. numDots = 0;
  193. // If it's a whole rest we want it smack in the middle. Apparently there is still an issue in vexflow:
  194. // https://github.com/0xfe/vexflow/issues/579 The author reports that he needs to add some negative x shift
  195. // if the measure has no modifiers.
  196. alignCenter = true;
  197. xShift = rules.WholeRestXShiftVexflow * unitInPixels; // TODO find way to make dependent on the modifiers
  198. // affects VexFlowStaffEntry.calculateXPosition()
  199. }
  200. if (note.sourceNote.ParentStaff.Voices.length > 1) {
  201. let visibleVoiceEntries: number = 0;
  202. //Find all visible voice entries (don't want invisible rests/notes causing visible shift)
  203. for (let idx: number = 0; idx < note.sourceNote.ParentStaffEntry.VoiceEntries.length ; idx++) {
  204. if (note.sourceNote.ParentStaffEntry.VoiceEntries[idx].Notes[0].PrintObject) {
  205. visibleVoiceEntries++;
  206. }
  207. }
  208. //If we have more than one visible voice entry, shift the rests so no collision occurs
  209. if (visibleVoiceEntries > 1) {
  210. switch (note.sourceNote.ParentVoiceEntry?.ParentVoice?.VoiceId) {
  211. case 1:
  212. keys = ["e/5"];
  213. break;
  214. case 2:
  215. keys = ["f/4"];
  216. break;
  217. default:
  218. break;
  219. }
  220. }
  221. }
  222. break;
  223. }
  224. if (note.sourceNote.Notehead) {
  225. if (note.sourceNote.Notehead.Shape === NoteHeadShape.SLASH) {
  226. slashNoteHead = true;
  227. // if we have slash heads and other heads in the voice entry, this will create the same head for all.
  228. // same problem with numDots. The slash case should be extremely rare though.
  229. }
  230. }
  231. const pitch: [string, string, ClefInstruction] = (note as VexFlowGraphicalNote).vfpitch;
  232. keys.push(pitch[0]);
  233. accidentals.push(pitch[1]);
  234. if (!vfClefType) {
  235. const vfClef: {type: string, annotation: string} = VexFlowConverter.Clef(pitch[2]);
  236. vfClefType = vfClef.type;
  237. }
  238. }
  239. for (let i: number = 0, len: number = numDots; i < len; ++i) {
  240. duration += "d";
  241. }
  242. if (slashNoteHead) {
  243. duration += "s"; // we have to specify a slash note head like this in Vexflow
  244. }
  245. if (isRest) {
  246. // "r" has to be put after the "d"s for rest notes.
  247. duration += "r";
  248. }
  249. let vfnote: Vex.Flow.StaveNote;
  250. const vfnoteStruct: any = {
  251. align_center: alignCenter,
  252. auto_stem: true,
  253. clef: vfClefType,
  254. duration: duration,
  255. keys: keys,
  256. slash: gve.parentVoiceEntry.GraceNoteSlash,
  257. };
  258. const firstNote: Note = gve.notes[0].sourceNote;
  259. if (firstNote.IsCueNote) {
  260. vfnoteStruct.glyph_font_scale = Vex.Flow.DEFAULT_NOTATION_FONT_SCALE * Vex.Flow.GraceNote.SCALE;
  261. vfnoteStruct.stroke_px = Vex.Flow.GraceNote.LEDGER_LINE_OFFSET;
  262. }
  263. if (gve.parentVoiceEntry.IsGrace || gve.notes[0].sourceNote.IsCueNote) {
  264. vfnote = new Vex.Flow.GraceNote(vfnoteStruct);
  265. } else {
  266. vfnote = new Vex.Flow.StaveNote(vfnoteStruct);
  267. }
  268. if (rules.LedgerLineWidth || rules.LedgerLineStrokeStyle) {
  269. if (!((vfnote as any).ledgerLineStyle)) {
  270. (vfnote as any).ledgerLineStyle = {};
  271. }
  272. if (rules.LedgerLineWidth) {
  273. (vfnote as any).ledgerLineStyle.lineWidth = rules.LedgerLineWidth;
  274. }
  275. if (rules.LedgerLineStrokeStyle) {
  276. (vfnote as any).ledgerLineStyle.strokeStyle = rules.LedgerLineStrokeStyle;
  277. }
  278. }
  279. if (rules.ColoringEnabled) {
  280. const defaultColorStem: string = rules.DefaultColorStem;
  281. let stemColor: string = gve.parentVoiceEntry.StemColor;
  282. if (!stemColor && defaultColorStem) {
  283. stemColor = defaultColorStem;
  284. }
  285. const stemStyle: Object = { fillStyle: stemColor, strokeStyle: stemColor };
  286. if (stemColor) {
  287. gve.parentVoiceEntry.StemColor = stemColor;
  288. vfnote.setStemStyle(stemStyle);
  289. if (vfnote.flag && rules.ColorFlags) {
  290. vfnote.setFlagStyle(stemStyle);
  291. }
  292. }
  293. }
  294. vfnote.x_shift = xShift;
  295. if (gve.parentVoiceEntry.IsGrace && gve.notes[0].sourceNote.NoteBeam) {
  296. // Vexflow seems to have issues with wanted stem direction for beamed grace notes,
  297. // when the stem is connected to a beamed main note (e.g. Haydn Concertante bar 57)
  298. gve.parentVoiceEntry.WantedStemDirection = gve.notes[0].sourceNote.NoteBeam.Notes[0].ParentVoiceEntry.WantedStemDirection;
  299. }
  300. if (gve.parentVoiceEntry !== undefined) {
  301. const wantedStemDirection: StemDirectionType = gve.parentVoiceEntry.WantedStemDirection;
  302. switch (wantedStemDirection) {
  303. case(StemDirectionType.Up):
  304. vfnote.setStemDirection(Vex.Flow.Stem.UP);
  305. break;
  306. case (StemDirectionType.Down):
  307. vfnote.setStemDirection(Vex.Flow.Stem.DOWN);
  308. break;
  309. default:
  310. }
  311. }
  312. // add accidentals
  313. for (let i: number = 0, len: number = notes.length; i < len; i += 1) {
  314. (notes[i] as VexFlowGraphicalNote).setIndex(vfnote, i);
  315. if (accidentals[i]) {
  316. if (accidentals[i] === "++") { // triple sharp
  317. vfnote.addAccidental(i, new Vex.Flow.Accidental("##"));
  318. vfnote.addAccidental(i, new Vex.Flow.Accidental("#"));
  319. continue;
  320. } else if (accidentals[i] === "bbs") { // triple flat
  321. vfnote.addAccidental(i, new Vex.Flow.Accidental("bb"));
  322. vfnote.addAccidental(i, new Vex.Flow.Accidental("b"));
  323. continue;
  324. }
  325. vfnote.addAccidental(i, new Vex.Flow.Accidental(accidentals[i])); // normal accidental
  326. }
  327. // add Tremolo strokes (only single note tremolos for now, Vexflow doesn't have beams for two-note tremolos yet)
  328. const tremoloStrokes: number = notes[i].sourceNote.TremoloStrokes;
  329. if (tremoloStrokes > 0) {
  330. vfnote.addModifier(i, new Vex.Flow.Tremolo(tremoloStrokes));
  331. }
  332. }
  333. // half note tremolo: set notehead to half note (Vexflow otherwise takes the notehead from duration) (Hack)
  334. if (firstNote.Length.RealValue === 0.25 && firstNote.Notehead && firstNote.Notehead.Filled === false) {
  335. const keyProps: Object[] = vfnote.getKeyProps();
  336. for (let i: number = 0; i < keyProps.length; i++) {
  337. (<any>keyProps[i]).code = "v81";
  338. }
  339. }
  340. for (let i: number = 0, len: number = numDots; i < len; ++i) {
  341. vfnote.addDotToAll();
  342. }
  343. return vfnote;
  344. }
  345. public static generateArticulations(vfnote: Vex.Flow.StemmableNote, articulations: ArticulationEnum[]): void {
  346. if (vfnote === undefined || vfnote.getAttribute("type") === "GhostNote") {
  347. return;
  348. }
  349. // Articulations:
  350. let vfArtPosition: number = Vex.Flow.Modifier.Position.ABOVE;
  351. if (vfnote.getStemDirection() === Vex.Flow.Stem.UP) {
  352. vfArtPosition = Vex.Flow.Modifier.Position.BELOW;
  353. }
  354. for (const articulation of articulations) {
  355. // tslint:disable-next-line:switch-default
  356. let vfArt: Vex.Flow.Articulation = undefined;
  357. switch (articulation) {
  358. case ArticulationEnum.accent: {
  359. vfArt = new Vex.Flow.Articulation("a>");
  360. break;
  361. }
  362. case ArticulationEnum.downbow: {
  363. vfArt = new Vex.Flow.Articulation("am");
  364. break;
  365. }
  366. case ArticulationEnum.fermata: {
  367. vfArt = new Vex.Flow.Articulation("a@a");
  368. vfArtPosition = Vex.Flow.Modifier.Position.ABOVE;
  369. break;
  370. }
  371. case ArticulationEnum.invertedfermata: {
  372. vfArt = new Vex.Flow.Articulation("a@u");
  373. vfArtPosition = Vex.Flow.Modifier.Position.BELOW;
  374. break;
  375. }
  376. case ArticulationEnum.lefthandpizzicato: {
  377. vfArt = new Vex.Flow.Articulation("a+");
  378. break;
  379. }
  380. case ArticulationEnum.snappizzicato: {
  381. vfArt = new Vex.Flow.Articulation("ao");
  382. break;
  383. }
  384. case ArticulationEnum.staccatissimo: {
  385. vfArt = new Vex.Flow.Articulation("av");
  386. break;
  387. }
  388. case ArticulationEnum.staccato: {
  389. vfArt = new Vex.Flow.Articulation("a.");
  390. break;
  391. }
  392. case ArticulationEnum.tenuto: {
  393. vfArt = new Vex.Flow.Articulation("a-");
  394. break;
  395. }
  396. case ArticulationEnum.upbow: {
  397. vfArt = new Vex.Flow.Articulation("a|");
  398. break;
  399. }
  400. case ArticulationEnum.strongaccent: {
  401. vfArt = new Vex.Flow.Articulation("a^");
  402. break;
  403. }
  404. default: {
  405. break;
  406. }
  407. }
  408. if (vfArt !== undefined) {
  409. vfArt.setPosition(vfArtPosition);
  410. (vfnote as StaveNote).addModifier(0, vfArt);
  411. }
  412. }
  413. }
  414. public static generateOrnaments(vfnote: Vex.Flow.StemmableNote, oContainer: OrnamentContainer): void {
  415. let vfPosition: number = Vex.Flow.Modifier.Position.ABOVE;
  416. if (vfnote.getStemDirection() === Vex.Flow.Stem.UP) {
  417. vfPosition = Vex.Flow.Modifier.Position.BELOW;
  418. }
  419. let vfOrna: Vex.Flow.Ornament = undefined;
  420. switch (oContainer.GetOrnament) {
  421. case OrnamentEnum.DelayedInvertedTurn: {
  422. vfOrna = new Vex.Flow.Ornament("turn_inverted");
  423. vfOrna.setDelayed(true);
  424. break;
  425. }
  426. case OrnamentEnum.DelayedTurn: {
  427. vfOrna = new Vex.Flow.Ornament("turn");
  428. vfOrna.setDelayed(true);
  429. break;
  430. }
  431. case OrnamentEnum.InvertedMordent: {
  432. vfOrna = new Vex.Flow.Ornament("mordent_inverted");
  433. vfOrna.setDelayed(false);
  434. break;
  435. }
  436. case OrnamentEnum.InvertedTurn: {
  437. vfOrna = new Vex.Flow.Ornament("turn_inverted");
  438. vfOrna.setDelayed(false);
  439. break;
  440. }
  441. case OrnamentEnum.Mordent: {
  442. vfOrna = new Vex.Flow.Ornament("mordent");
  443. vfOrna.setDelayed(false);
  444. break;
  445. }
  446. case OrnamentEnum.Trill: {
  447. vfOrna = new Vex.Flow.Ornament("tr");
  448. vfOrna.setDelayed(false);
  449. break;
  450. }
  451. case OrnamentEnum.Turn: {
  452. vfOrna = new Vex.Flow.Ornament("turn");
  453. vfOrna.setDelayed(false);
  454. break;
  455. }
  456. default: {
  457. log.warn("unhandled OrnamentEnum type: " + oContainer.GetOrnament);
  458. return;
  459. }
  460. }
  461. if (vfOrna !== undefined) {
  462. if (oContainer.AccidentalBelow !== AccidentalEnum.NONE) {
  463. vfOrna.setLowerAccidental(Pitch.accidentalVexflow(oContainer.AccidentalBelow));
  464. }
  465. if (oContainer.AccidentalAbove !== AccidentalEnum.NONE) {
  466. vfOrna.setUpperAccidental(Pitch.accidentalVexflow(oContainer.AccidentalAbove));
  467. }
  468. vfOrna.setPosition(vfPosition);
  469. (vfnote as StaveNote).addModifier(0, vfOrna);
  470. }
  471. }
  472. public static StrokeTypeFromArpeggioType(arpeggioType: ArpeggioType): Vex.Flow.Stroke.Type {
  473. switch (arpeggioType) {
  474. case ArpeggioType.ARPEGGIO_DIRECTIONLESS:
  475. return Vex.Flow.Stroke.Type.ARPEGGIO_DIRECTIONLESS;
  476. case ArpeggioType.BRUSH_DOWN:
  477. return Vex.Flow.Stroke.Type.BRUSH_UP; // TODO somehow up and down are mixed up in Vexflow right now
  478. case ArpeggioType.BRUSH_UP:
  479. return Vex.Flow.Stroke.Type.BRUSH_DOWN; // TODO somehow up and down are mixed up in Vexflow right now
  480. case ArpeggioType.RASQUEDO_DOWN:
  481. return Vex.Flow.Stroke.Type.RASQUEDO_UP;
  482. case ArpeggioType.RASQUEDO_UP:
  483. return Vex.Flow.Stroke.Type.RASQUEDO_DOWN;
  484. case ArpeggioType.ROLL_DOWN:
  485. return Vex.Flow.Stroke.Type.ROLL_UP; // TODO somehow up and down are mixed up in Vexflow right now
  486. case ArpeggioType.ROLL_UP:
  487. return Vex.Flow.Stroke.Type.ROLL_DOWN; // TODO somehow up and down are mixed up in Vexflow right now
  488. default:
  489. return Vex.Flow.Stroke.Type.ARPEGGIO_DIRECTIONLESS;
  490. }
  491. }
  492. /**
  493. * Convert a set of GraphicalNotes to a VexFlow StaveNote
  494. * @param notes form a chord on the staff
  495. * @returns {Vex.Flow.StaveNote}
  496. */
  497. public static CreateTabNote(gve: GraphicalVoiceEntry): Vex.Flow.TabNote {
  498. const tabPositions: {str: number, fret: number}[] = [];
  499. const frac: Fraction = gve.notes[0].graphicalNoteLength;
  500. const isTuplet: boolean = gve.notes[0].sourceNote.NoteTuplet !== undefined;
  501. let duration: string = VexFlowConverter.duration(frac, isTuplet);
  502. let numDots: number = 0;
  503. for (const note of gve.notes) {
  504. const tabNote: TabNote = note.sourceNote as TabNote;
  505. const tabPosition: {str: number, fret: number} = {str: tabNote.StringNumber, fret: tabNote.FretNumber};
  506. tabPositions.push(tabPosition);
  507. if (numDots < note.numberOfDots) {
  508. numDots = note.numberOfDots;
  509. }
  510. }
  511. for (let i: number = 0, len: number = numDots; i < len; ++i) {
  512. duration += "d";
  513. }
  514. const vfnote: Vex.Flow.TabNote = new Vex.Flow.TabNote({
  515. duration: duration,
  516. positions: tabPositions,
  517. });
  518. return vfnote;
  519. }
  520. /**
  521. * Convert a ClefInstruction to a string represention of a clef type in VexFlow.
  522. *
  523. * @param clef The OSMD object to be converted representing the clef
  524. * @param size The VexFlow size to be used. Can be `default` or `small`. As soon as
  525. * #118 is done, this parameter will be dispensable.
  526. * @returns A string representation of a VexFlow clef
  527. * @see https://github.com/0xfe/vexflow/blob/master/src/clef.js
  528. * @see https://github.com/0xfe/vexflow/blob/master/tests/clef_tests.js
  529. */
  530. public static Clef(clef: ClefInstruction, size: string = "default"): { type: string, size: string, annotation: string } {
  531. let type: string;
  532. let annotation: string;
  533. // Make sure size is either "default" or "small"
  534. if (size !== "default" && size !== "small") {
  535. log.warn(`Invalid VexFlow clef size "${size}" specified. Using "default".`);
  536. size = "default";
  537. }
  538. /*
  539. * For all of the following conversions, OSMD uses line numbers 1-5 starting from
  540. * the bottom, while VexFlow uses 0-4 starting from the top.
  541. */
  542. switch (clef.ClefType) {
  543. // G Clef
  544. case ClefEnum.G:
  545. switch (clef.Line) {
  546. case 1:
  547. type = "french"; // VexFlow line 4
  548. break;
  549. case 2:
  550. type = "treble"; // VexFlow line 3
  551. break;
  552. default:
  553. type = "treble";
  554. log.error(`Clef ${ClefEnum[clef.ClefType]} on line ${clef.Line} not supported by VexFlow. Using default value "${type}".`);
  555. }
  556. break;
  557. // F Clef
  558. case ClefEnum.F:
  559. switch (clef.Line) {
  560. case 4:
  561. type = "bass"; // VexFlow line 1
  562. break;
  563. case 3:
  564. type = "baritone-f"; // VexFlow line 2
  565. break;
  566. case 5:
  567. type = "subbass"; // VexFlow line 0
  568. break;
  569. default:
  570. type = "bass";
  571. log.error(`Clef ${ClefEnum[clef.ClefType]} on line ${clef.Line} not supported by VexFlow. Using default value "${type}".`);
  572. }
  573. break;
  574. // C Clef
  575. case ClefEnum.C:
  576. switch (clef.Line) {
  577. case 3:
  578. type = "alto"; // VexFlow line 2
  579. break;
  580. case 4:
  581. type = "tenor"; // VexFlow line 1
  582. break;
  583. case 1:
  584. type = "soprano"; // VexFlow line 4
  585. break;
  586. case 2:
  587. type = "mezzo-soprano"; // VexFlow line 3
  588. break;
  589. default:
  590. type = "alto";
  591. log.error(`Clef ${ClefEnum[clef.ClefType]} on line ${clef.Line} not supported by VexFlow. Using default value "${type}".`);
  592. }
  593. break;
  594. // Percussion Clef
  595. case ClefEnum.percussion:
  596. type = "percussion";
  597. break;
  598. // TAB Clef
  599. case ClefEnum.TAB:
  600. // only used currently for creating the notes in the normal stave: There we need a normal treble clef
  601. type = "treble";
  602. break;
  603. default:
  604. }
  605. // annotations in vexflow don't allow bass and 8va. No matter the offset :(
  606. if (clef.OctaveOffset === 1 && type !== "bass" ) {
  607. annotation = "8va";
  608. } else if (clef.OctaveOffset === -1) {
  609. annotation = "8vb";
  610. }
  611. return { type, size, annotation };
  612. }
  613. /**
  614. * Convert a RhythmInstruction to a VexFlow TimeSignature object
  615. * @param rhythm
  616. * @returns {Vex.Flow.TimeSignature}
  617. * @constructor
  618. */
  619. public static TimeSignature(rhythm: RhythmInstruction): Vex.Flow.TimeSignature {
  620. let timeSpec: string;
  621. switch (rhythm.SymbolEnum) {
  622. case RhythmSymbolEnum.NONE:
  623. timeSpec = rhythm.Rhythm.Numerator + "/" + rhythm.Rhythm.Denominator;
  624. break;
  625. case RhythmSymbolEnum.COMMON:
  626. timeSpec = "C";
  627. break;
  628. case RhythmSymbolEnum.CUT:
  629. timeSpec = "C|";
  630. break;
  631. default:
  632. }
  633. return new Vex.Flow.TimeSignature(timeSpec);
  634. }
  635. /**
  636. * Convert a KeyInstruction to a string representing in VexFlow a key
  637. * @param key
  638. * @returns {string}
  639. */
  640. public static keySignature(key: KeyInstruction): string {
  641. if (key === undefined) {
  642. return undefined;
  643. }
  644. let ret: string;
  645. switch (key.Mode) {
  646. case KeyEnum.minor:
  647. ret = VexFlowConverter.minorMap[key.Key] + "m";
  648. break;
  649. case KeyEnum.major:
  650. ret = VexFlowConverter.majorMap[key.Key];
  651. break;
  652. // some XMLs don't have the mode set despite having a key signature.
  653. case KeyEnum.none:
  654. ret = VexFlowConverter.majorMap[key.Key];
  655. break;
  656. default:
  657. ret = "C";
  658. }
  659. return ret;
  660. }
  661. /**
  662. * Converts a lineType to a VexFlow StaveConnector type
  663. * @param lineType
  664. * @returns {any}
  665. */
  666. public static line(lineType: SystemLinesEnum, linePosition: SystemLinePosition): any {
  667. switch (lineType) {
  668. case SystemLinesEnum.SingleThin:
  669. if (linePosition === SystemLinePosition.MeasureBegin) {
  670. return Vex.Flow.StaveConnector.type.SINGLE;
  671. }
  672. return Vex.Flow.StaveConnector.type.SINGLE_RIGHT;
  673. case SystemLinesEnum.DoubleThin:
  674. return Vex.Flow.StaveConnector.type.DOUBLE;
  675. case SystemLinesEnum.ThinBold:
  676. return Vex.Flow.StaveConnector.type.BOLD_DOUBLE_RIGHT;
  677. case SystemLinesEnum.BoldThinDots:
  678. return Vex.Flow.StaveConnector.type.BOLD_DOUBLE_LEFT;
  679. case SystemLinesEnum.DotsThinBold:
  680. return Vex.Flow.StaveConnector.type.BOLD_DOUBLE_RIGHT;
  681. case SystemLinesEnum.DotsBoldBoldDots:
  682. return Vex.Flow.StaveConnector.type.BOLD_DOUBLE_RIGHT;
  683. case SystemLinesEnum.None:
  684. return Vex.Flow.StaveConnector.type.NONE;
  685. default:
  686. }
  687. }
  688. /**
  689. * Construct a string which can be used in a CSS font property
  690. * @param fontSize
  691. * @param fontStyle
  692. * @param font
  693. * @returns {string}
  694. */
  695. public static font(fontSize: number, fontStyle: FontStyles = FontStyles.Regular,
  696. font: Fonts = Fonts.TimesNewRoman, rules: EngravingRules, fontFamily: string = undefined): string {
  697. let style: string = "normal";
  698. let weight: string = "normal";
  699. let family: string = `'${rules.DefaultFontFamily}'`; // default "'Times New Roman'"
  700. switch (fontStyle) {
  701. case FontStyles.Bold:
  702. weight = "bold";
  703. break;
  704. case FontStyles.Italic:
  705. style = "italic";
  706. break;
  707. case FontStyles.BoldItalic:
  708. style = "italic";
  709. weight = "bold";
  710. break;
  711. case FontStyles.Underlined:
  712. // TODO
  713. break;
  714. default:
  715. break;
  716. }
  717. switch (font) { // currently not used
  718. case Fonts.Kokila:
  719. // TODO Not Supported
  720. break;
  721. default:
  722. }
  723. if (fontFamily && fontFamily !== "default") {
  724. family = `'${fontFamily}'`;
  725. }
  726. return style + " " + weight + " " + Math.floor(fontSize) + "px " + family;
  727. }
  728. /**
  729. * Converts the style into a string that VexFlow RenderContext can understand
  730. * as the weight of the font
  731. */
  732. public static fontStyle(style: FontStyles): string {
  733. switch (style) {
  734. case FontStyles.Bold:
  735. return "bold";
  736. case FontStyles.Italic:
  737. return "italic";
  738. case FontStyles.BoldItalic:
  739. return "italic bold";
  740. default:
  741. return "normal";
  742. }
  743. }
  744. /**
  745. * Convert OutlineAndFillStyle to CSS properties
  746. * @param styleId
  747. * @returns {string}
  748. */
  749. public static style(styleId: OutlineAndFillStyleEnum): string {
  750. const ret: string = OUTLINE_AND_FILL_STYLE_DICT.getValue(styleId);
  751. return ret;
  752. }
  753. }