OpenSheetMusicDisplay.ts 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  1. import { IXmlElement } from "./../Common/FileIO/Xml";
  2. import { VexFlowMusicSheetCalculator } from "./../MusicalScore/Graphical/VexFlow/VexFlowMusicSheetCalculator";
  3. import { VexFlowBackend } from "./../MusicalScore/Graphical/VexFlow/VexFlowBackend";
  4. import { MusicSheetReader } from "./../MusicalScore/ScoreIO/MusicSheetReader";
  5. import { GraphicalMusicSheet } from "./../MusicalScore/Graphical/GraphicalMusicSheet";
  6. import { MusicSheetCalculator } from "./../MusicalScore/Graphical/MusicSheetCalculator";
  7. import { VexFlowMusicSheetDrawer } from "./../MusicalScore/Graphical/VexFlow/VexFlowMusicSheetDrawer";
  8. import { SvgVexFlowBackend } from "./../MusicalScore/Graphical/VexFlow/SvgVexFlowBackend";
  9. import { CanvasVexFlowBackend } from "./../MusicalScore/Graphical/VexFlow/CanvasVexFlowBackend";
  10. import { MusicSheet } from "./../MusicalScore/MusicSheet";
  11. import { Cursor } from "./Cursor";
  12. import { MXLHelper } from "../Common/FileIO/Mxl";
  13. import { AJAX } from "./AJAX";
  14. import log from "loglevel";
  15. import { DrawingParametersEnum, DrawingParameters, ColoringModes } from "../MusicalScore/Graphical/DrawingParameters";
  16. import { IOSMDOptions, OSMDOptions, AutoBeamOptions, BackendType, CursorOptions } from "./OSMDOptions";
  17. import { EngravingRules, PageFormat } from "../MusicalScore/Graphical/EngravingRules";
  18. import { AbstractExpression } from "../MusicalScore/VoiceData/Expressions/AbstractExpression";
  19. import { Dictionary } from "typescript-collections";
  20. import { AutoColorSet } from "../MusicalScore/Graphical/DrawingEnums";
  21. import { GraphicalMusicPage } from "../MusicalScore/Graphical/GraphicalMusicPage";
  22. import { MusicPartManagerIterator } from "../MusicalScore/MusicParts/MusicPartManagerIterator";
  23. import { ITransposeCalculator } from "../MusicalScore/Interfaces/ITransposeCalculator";
  24. import { NoteEnum } from "../Common/DataObjects/Pitch";
  25. import { PlaybackNoteGenerator } from "../MusicalScore/Playback/PlaybackNoteGenerator";
  26. import { SheetRenderingManager } from "../Display/SheetRenderingManager";
  27. import { WebSheetRenderingManager } from "../Display/WebSheetRenderingManager";
  28. import { WebDisplayInteractionManager } from "../Display/WebDisplayInteractionManager";
  29. import { AbstractDisplayInteractionManager } from "../Display/AbstractDisplayInteractionManager";
  30. import { PlaybackManager } from "../Playback";
  31. import { DynamicsCalculator } from "../MusicalScore/ScoreIO/MusicSymbolModules/DynamicsCalculator";
  32. /**
  33. * The main class and control point of OpenSheetMusicDisplay.<br>
  34. * It can display MusicXML sheet music files in an HTML element container.<br>
  35. * After the constructor, use load() and render() to load and render a MusicXML file.
  36. */
  37. export class OpenSheetMusicDisplay {
  38. private version: string = "1.0.0-audio-extended"; // getter: this.Version
  39. // at release, bump version and change to -release, afterwards to -dev again
  40. /**
  41. * Creates and attaches an OpenSheetMusicDisplay object to an HTML element container.<br>
  42. * After the constructor, use load() and render() to load and render a MusicXML file.
  43. * @param container The container element OSMD will be rendered into.<br>
  44. * Either a string specifying the ID of an HTML container element,<br>
  45. * or a reference to the HTML element itself (e.g. div)
  46. * @param options An object for rendering options like the backend (svg/canvas) or autoResize.<br>
  47. * For defaults see the OSMDOptionsStandard method in the [[OSMDOptions]] class.
  48. */
  49. constructor(container: string | HTMLElement,
  50. options: IOSMDOptions = OSMDOptions.OSMDOptionsStandard()) {
  51. // Store container element
  52. if (typeof container === "string") {
  53. // ID passed
  54. this.container = document.getElementById(<string>container);
  55. } else if (container && "appendChild" in <any>container) {
  56. // Element passed
  57. this.container = <HTMLElement>container;
  58. }
  59. if (!this.container) {
  60. throw new Error("Please pass a valid div container to OpenSheetMusicDisplay");
  61. }
  62. if (options.autoResize === undefined) {
  63. options.autoResize = true;
  64. }
  65. this.backendType = BackendType.SVG; // default, can be changed by options
  66. this.setOptions(options);
  67. this.interactionManager = new WebDisplayInteractionManager(this.container);
  68. this.renderingManager = new WebSheetRenderingManager(this.interactionManager);
  69. }
  70. private cursorsOptions: CursorOptions[] = [];
  71. public cursors: Cursor[] = [];
  72. public get cursor(): Cursor { // lowercase for backwards compatibility since cursor -> cursors change
  73. return this.cursors[0];
  74. }
  75. public zoom: number = 1.0;
  76. protected zoomUpdated: boolean = false;
  77. /** Timeout in milliseconds used in osmd.load(string) when string is a URL. */
  78. public loadUrlTimeout: number = 5000;
  79. protected container: HTMLElement;
  80. protected backendType: BackendType;
  81. protected needBackendUpdate: boolean;
  82. protected sheet: MusicSheet;
  83. protected drawer: VexFlowMusicSheetDrawer;
  84. protected drawBoundingBox: string;
  85. protected drawSkyLine: boolean;
  86. protected drawBottomLine: boolean;
  87. protected graphic: GraphicalMusicSheet;
  88. protected renderingManager: SheetRenderingManager;
  89. protected interactionManager: AbstractDisplayInteractionManager;
  90. protected drawingParameters: DrawingParameters;
  91. protected rules: EngravingRules;
  92. protected autoResizeEnabled: boolean;
  93. private resizeHandlerAttached: boolean;
  94. private disposeResizeListener: Function;
  95. protected followCursor: boolean;
  96. protected OnXMLRead: Function;
  97. public set PlaybackManager(manager: PlaybackManager) {
  98. if (this.renderingManager) {
  99. this.renderingManager.PlaybackManager = manager;
  100. }
  101. }
  102. private isUrl (url: string): boolean {
  103. if (url.length < 2083) {
  104. return true;
  105. /* Nope. Doesn't do it. Still TODO, better URL detection.
  106. try {
  107. const urlObj: URL = new URL(url);
  108. log.debug("[OSMD] found URL, " + urlObj.toString());
  109. return true;
  110. } catch (ex) {
  111. return false;
  112. } */
  113. } else {
  114. return false;
  115. }
  116. }
  117. private isMxl (data: string): boolean {
  118. if (data.substr(0, 4) === "\x50\x4b\x03\x04") {
  119. return true;
  120. }
  121. return false;
  122. }
  123. private processMxl (data: string, resolveContentPromise: (value?: Document) => void, rejectContentPromise: (reason?: any) => void): void {
  124. MXLHelper.MXLtoXMLstring(data).then(
  125. (x: string) => {
  126. resolveContentPromise(this.processStringXml(x));
  127. },
  128. (err: any) => {
  129. log.error(new Error("[OSMD] Invalid MXL file: " + err));
  130. rejectContentPromise(new Error("[OSMD] Invalid MXL file: " + err));
  131. }
  132. );
  133. }
  134. private processStringXml (xmlString: string): Document {
  135. const parser: DOMParser = new DOMParser();
  136. // Javascript loads strings as utf-16, which is wonderful BS if you want to parse UTF-8 :S
  137. if (xmlString.substr(0, 3) === "\uf7ef\uf7bb\uf7bf") {
  138. log.debug("[OSMD] UTF with BOM detected, truncate first three bytes and pass along: " + xmlString);
  139. // UTF with BOM detected, truncate first three bytes and pass along
  140. return parser.parseFromString(xmlString.substr(3), "application/xml");
  141. }
  142. if (xmlString.substr(0, 6).includes("<?xml")) {
  143. const modifiedXml: string = this.OnXMLRead(xmlString); // by default just returns trimmedStr unless a function options.OnXMLRead was set.
  144. log.debug("[OSMD] Finally parsing XML content, length: " + modifiedXml.length);
  145. // Parse the string representing an xml file
  146. return parser.parseFromString(modifiedXml, "application/xml");
  147. }
  148. }
  149. /**
  150. * Load a MusicXML file
  151. * @param content is either the url of a file, or the root node of a MusicXML document, or the string content of a .xml/.mxl file
  152. */
  153. public load(content: string | Document, comments?: (string|Document)[]): Promise<{}> {
  154. // Warning! This function is asynchronous! No error handling is done here.
  155. this.reset();
  156. const self: OpenSheetMusicDisplay = this;
  157. const loadPromise: Promise<any> = new Promise(
  158. function(mainResolve: (value?: any) => void, mainReject: (reason?: any) => void): void {
  159. const contentPromise: Promise<Document> = new Promise<Document>(
  160. function(resolveContentPromise: (value?: Document) => void, rejectContentPromise: (reason?: any) => void): void {
  161. //console.log("typeof content: " + typeof content);
  162. if (typeof content === "string") {
  163. const str: string = <string>content.trim();
  164. if (self.isMxl(str)) {
  165. log.debug("[OSMD] This is a zip file, unpack it first: " + str);
  166. // This is a zip file, unpack it first
  167. self.processMxl(str, resolveContentPromise, rejectContentPromise);
  168. } else {
  169. const processedXmlDoc: Document = self.processStringXml(str);
  170. if (processedXmlDoc) {
  171. resolveContentPromise(processedXmlDoc);
  172. } else if (self.isUrl(str)) {
  173. AJAX.ajax(str).then(
  174. (s: string) => {
  175. if (self.isMxl(s)) {
  176. self.processMxl(s, resolveContentPromise, rejectContentPromise);
  177. } else {
  178. resolveContentPromise(self.processStringXml(s));
  179. }
  180. },
  181. (exc: Error) => { rejectContentPromise(exc); throw exc; }
  182. );
  183. } else {
  184. const err: Error = new Error("[OSMD] osmd.load(string): Could not process string. Did not find <?xml at beginning.");
  185. console.error(err.message);
  186. rejectContentPromise(err);
  187. }
  188. }
  189. } else if (content instanceof Document) {
  190. resolveContentPromise(content);
  191. } else {
  192. const err: Error = new Error("[OSMD] osmd.load(): content is not string or Document. Could not load.");
  193. console.error(err.message);
  194. rejectContentPromise(err);
  195. }
  196. });
  197. contentPromise.then(function(musicXML: Document): void {
  198. if (!musicXML || !(<any>musicXML).nodeName) {
  199. mainReject(new Error("OpenSheetMusicDisplay: The document which was provided is invalid"));
  200. }
  201. const xmlDocumentNodes: NodeList = musicXML.childNodes;
  202. log.debug("[OSMD] load(), Document url: " + musicXML.URL);
  203. let scorePartwiseElement: Element;
  204. for (let i: number = 0, length: number = xmlDocumentNodes.length; i < length; i += 1) {
  205. const node: Node = xmlDocumentNodes[i];
  206. if (node.nodeType === Node.ELEMENT_NODE && node.nodeName.toLowerCase() === "score-partwise") {
  207. scorePartwiseElement = <Element>node;
  208. break;
  209. }
  210. }
  211. if (!scorePartwiseElement) {
  212. console.error("Could not parse MusicXML, no valid partwise element found");
  213. mainReject(new Error("OpenSheetMusicDisplay: Document is not a valid 'partwise' MusicXML"));
  214. }
  215. const score: IXmlElement = new IXmlElement(scorePartwiseElement);
  216. const dynamicsGenerator: DynamicsCalculator = new DynamicsCalculator();
  217. const playbackNoteGen: PlaybackNoteGenerator = new PlaybackNoteGenerator();
  218. const reader: MusicSheetReader = new MusicSheetReader([dynamicsGenerator, playbackNoteGen], self.rules);
  219. self.sheet = reader.createMusicSheet(score, "Untitled Score");
  220. if (self.sheet === undefined) {
  221. // error loading sheet, probably already logged, do nothing
  222. mainReject(new Error("given music sheet was incomplete or could not be loaded."));
  223. }
  224. log.info(`[OSMD] Loaded sheet ${self.sheet.TitleString} successfully.`);
  225. //If we have a comment XML, read it
  226. self.needBackendUpdate = true;
  227. self.updateGraphic();
  228. mainResolve();
  229. }).catch(function(reason: any): void {
  230. log.debug("Content XML Promise was rejected");
  231. mainReject(reason);
  232. });
  233. });
  234. return loadPromise;
  235. }
  236. /**
  237. * (Re-)creates the graphic sheet from the music sheet
  238. */
  239. public updateGraphic(): void {
  240. const calc: MusicSheetCalculator = new VexFlowMusicSheetCalculator(this.rules);
  241. this.graphic = new GraphicalMusicSheet(this.sheet, calc);
  242. if (this.drawingParameters.drawCursors) {
  243. this.cursors.forEach(cursor => {
  244. cursor.init(this.sheet.MusicPartManager, this.graphic);
  245. });
  246. }
  247. this.renderingManager.setMusicSheet(this.graphic);
  248. this.interactionManager.Initialize();
  249. }
  250. /**
  251. * Render the music sheet in the container
  252. */
  253. public render(): void {
  254. if (!this.graphic) {
  255. throw new Error("OpenSheetMusicDisplay: Before rendering a music sheet, please load a MusicXML file");
  256. }
  257. this.drawer?.clear(); // clear canvas before setting width
  258. // this.graphic.GetCalculator.clearSystemsAndMeasures(); // maybe?
  259. // this.graphic.GetCalculator.clearRecreatedObjects();
  260. // Set page width
  261. let width: number = this.container.offsetWidth;
  262. if (this.rules.RenderSingleHorizontalStaffline) {
  263. width = 32767; // set safe maximum (browser limit), will be reduced later
  264. // reduced later in MusicSheetCalculator.calculatePageLabels (sets sheet.pageWidth to page.PositionAndShape.Size.width before labels)
  265. // rough calculation:
  266. // width = 600 * this.sheet.SourceMeasures.length;
  267. }
  268. // log.debug("[OSMD] render width: " + width);
  269. this.sheet.pageWidth = width / this.zoom / 10.0;
  270. this.renderingManager.MainViewingRegion.WidthInUnits = this.sheet.pageWidth;
  271. if (this.rules.PageFormat && !this.rules.PageFormat.IsUndefined) {
  272. this.rules.PageHeight = this.sheet.pageWidth / this.rules.PageFormat.aspectRatio;
  273. log.debug("[OSMD] PageHeight: " + this.rules.PageHeight);
  274. } else {
  275. log.debug("[OSMD] endless/undefined pageformat, id: " + this.rules.PageFormat.idString);
  276. this.rules.PageHeight = 100001; // infinite page height // TODO maybe Number.MAX_VALUE or Math.pow(10, 20)?
  277. }
  278. // Before introducing the following optimization (maybe irrelevant), tests
  279. // have to be modified to ensure that width is > 0 when executed
  280. //if (isNaN(width) || width === 0) {
  281. // return;
  282. //}
  283. // Calculate again
  284. this.graphic.reCalculate();
  285. if (this.drawingParameters.drawCursors) {
  286. this.graphic.Cursors.length = 0;
  287. }
  288. // needBackendUpdate is well intentioned, but we need to cover all cases.
  289. // backends also need an update when this.zoom was set from outside, which unfortunately doesn't have a setter method to set this in.
  290. // so just for compatibility, we need to assume users set osmd.zoom, so we'd need to check whether it was changed compared to last time.
  291. if (true || this.needBackendUpdate) {
  292. this.createOrRefreshRenderBackend();
  293. this.needBackendUpdate = false;
  294. }
  295. this.drawer.setZoom(this.zoom);
  296. // Finally, draw
  297. this.drawer.drawSheet(this.graphic);
  298. this.enableOrDisableCursors(this.drawingParameters.drawCursors);
  299. if (this.drawingParameters.drawCursors) {
  300. // Update the cursor position
  301. this.cursors.forEach(cursor => {
  302. cursor.update();
  303. });
  304. }
  305. this.zoomUpdated = false;
  306. //need to init values
  307. this.interactionManager.displaySizeChanged(this.container.clientWidth, this.container.clientHeight);
  308. //console.log("[OSMD] render finished");
  309. }
  310. protected createOrRefreshRenderBackend(): void {
  311. // console.log("[OSMD] createOrRefreshRenderBackend()");
  312. // Remove old backends
  313. if (this.drawer && this.drawer.Backends) {
  314. // removing single children to remove all is error-prone, because sometimes a random SVG-child remains.
  315. // for (const backend of this.drawer.Backends) {
  316. // backend.removeFromContainer(this.container);
  317. // }
  318. if (this.drawer.Backends[0]) {
  319. this.drawer.Backends[0].removeAllChildrenFromContainer(this.container);
  320. }
  321. this.drawer.Backends.clear();
  322. }
  323. // Create the drawer
  324. this.drawingParameters.Rules = this.rules;
  325. this.drawer = new VexFlowMusicSheetDrawer(this.drawingParameters); // note that here the drawer.drawableBoundingBoxElement is lost. now saved in OSMD.
  326. this.drawer.drawableBoundingBoxElement = this.DrawBoundingBox;
  327. this.drawer.bottomLineVisible = this.drawBottomLine;
  328. this.drawer.skyLineVisible = this.drawSkyLine;
  329. // Set page width
  330. let width: number = this.container.offsetWidth;
  331. if (this.rules.RenderSingleHorizontalStaffline) {
  332. width = this.graphic.MusicPages[0].PositionAndShape.Size.width * 10 * this.zoom;
  333. // this.container.style.width = width + "px";
  334. // console.log("width: " + width)
  335. }
  336. // TODO width may need to be coordinated with render() where width is also used
  337. let height: number;
  338. const canvasDimensionsLimit: number = 32767; // browser limitation. Chrome/Firefox (16 bit, 32768 causes an error).
  339. // Could be calculated by canvas-size module.
  340. // see #678 on Github and here: https://stackoverflow.com/a/11585939/10295942
  341. // TODO check if resize is necessary. set needResize or something when size was changed
  342. for (const page of this.graphic.MusicPages) {
  343. if (page.PageNumber > this.rules.MaxPageToDrawNumber) {
  344. break; // don't add the bounding boxes of pages that aren't drawn to the container height etc
  345. }
  346. const backend: VexFlowBackend = this.createBackend(this.backendType, page);
  347. const sizeWarningPartTwo: string = " exceeds CanvasBackend limit of 32767. Cutting off score.";
  348. if (backend.getOSMDBackendType() === BackendType.Canvas && width > canvasDimensionsLimit) {
  349. log.warn("[OSMD] Warning: width of " + width + sizeWarningPartTwo);
  350. width = canvasDimensionsLimit;
  351. }
  352. if (this.rules.PageFormat && !this.rules.PageFormat.IsUndefined) {
  353. height = width / this.rules.PageFormat.aspectRatio;
  354. // console.log("pageformat given. height: " + page.PositionAndShape.Size.height);
  355. } else {
  356. height = page.PositionAndShape.Size.height;
  357. height += this.rules.PageBottomMargin;
  358. height += this.rules.CompactMode ? this.rules.PageTopMarginNarrow : this.rules.PageTopMargin;
  359. if (this.rules.RenderTitle) {
  360. height += this.rules.TitleTopDistance;
  361. }
  362. height *= this.zoom * 10.0;
  363. // console.log("pageformat not given. height: " + page.PositionAndShape.Size.height);
  364. }
  365. if (backend.getOSMDBackendType() === BackendType.Canvas && height > canvasDimensionsLimit) {
  366. log.warn("[OSMD] Warning: height of " + height + sizeWarningPartTwo);
  367. height = Math.min(height, canvasDimensionsLimit); // this cuts off the the score, but doesn't break rendering.
  368. // TODO optional: reduce zoom to fit the score within the limit.
  369. }
  370. backend.resize(width, height);
  371. backend.clear(); // set bgcolor if defined (this.rules.PageBackgroundColor, see OSMDOptions)
  372. this.drawer.Backends.push(backend);
  373. this.graphic.drawer = this.drawer;
  374. }
  375. }
  376. // for now SVG only, see generateImages_browserless (PNG/SVG)
  377. public exportSVG(): void {
  378. for (const backend of this.drawer?.Backends) {
  379. if (backend instanceof SvgVexFlowBackend) {
  380. (backend as SvgVexFlowBackend).export();
  381. }
  382. // if we add CanvasVexFlowBackend exporting, rename function to export() or exportImages() again
  383. }
  384. }
  385. /** States whether the render() function can be safely called. */
  386. public IsReadyToRender(): boolean {
  387. return this.graphic !== undefined;
  388. }
  389. /** Clears what OSMD has drawn on its canvas. */
  390. public clear(): void {
  391. this.drawer?.clear();
  392. this.reset(); // without this, resize will draw loaded sheet again
  393. }
  394. /** Dispose listeners created by OSMD */
  395. public dispose(): void {
  396. if (this.disposeResizeListener) {
  397. this.disposeResizeListener();
  398. }
  399. if (this.InteractionManager) {
  400. this.InteractionManager.Dispose();
  401. }
  402. }
  403. /** Set OSMD rendering options using an IOSMDOptions object.
  404. * Can be called during runtime. Also called by constructor.
  405. * For example, setOptions({autoResize: false}) will disable autoResize even during runtime.
  406. */
  407. public setOptions(options: IOSMDOptions): void {
  408. if (!this.rules) {
  409. this.rules = new EngravingRules();
  410. }
  411. if (!this.drawingParameters) {
  412. this.drawingParameters = new DrawingParameters();
  413. this.drawingParameters.Rules = this.rules;
  414. }
  415. if (options === undefined || options === null) {
  416. log.warn("warning: osmd.setOptions() called without an options parameter, has no effect."
  417. + "\n" + "example usage: osmd.setOptions({drawCredits: false, drawPartNames: false})");
  418. return;
  419. }
  420. this.OnXMLRead = function(xml): string {return xml;};
  421. if (options.onXMLRead) {
  422. this.OnXMLRead = options.onXMLRead;
  423. }
  424. if (options.drawingParameters) {
  425. this.drawingParameters.DrawingParametersEnum =
  426. (<any>DrawingParametersEnum)[options.drawingParameters.toLowerCase()];
  427. // see DrawingParameters.ts: set DrawingParametersEnum, and DrawingParameters.ts:setForCompactTightMode()
  428. }
  429. const backendNotInitialized: boolean = !this.drawer || !this.drawer.Backends || this.drawer.Backends.length < 1;
  430. let needBackendUpdate: boolean = backendNotInitialized;
  431. if (options.backend !== undefined) {
  432. const backendTypeGiven: BackendType = OSMDOptions.BackendTypeFromString(options.backend);
  433. needBackendUpdate = needBackendUpdate || this.backendType !== backendTypeGiven;
  434. this.backendType = backendTypeGiven;
  435. }
  436. this.needBackendUpdate = needBackendUpdate;
  437. // TODO this is a necessary step during the OSMD constructor. Maybe move this somewhere else
  438. // individual drawing parameters options
  439. if (options.autoBeam !== undefined) { // only change an option if it was given in options, otherwise it will be undefined
  440. this.rules.AutoBeamNotes = options.autoBeam;
  441. }
  442. const autoBeamOptions: AutoBeamOptions = options.autoBeamOptions;
  443. if (autoBeamOptions) {
  444. if (autoBeamOptions.maintain_stem_directions === undefined) {
  445. autoBeamOptions.maintain_stem_directions = false;
  446. }
  447. this.rules.AutoBeamOptions = autoBeamOptions;
  448. if (autoBeamOptions.groups && autoBeamOptions.groups.length) {
  449. for (const fraction of autoBeamOptions.groups) {
  450. if (fraction.length !== 2) {
  451. throw new Error("Each fraction in autoBeamOptions.groups must be of length 2, e.g. [3,4] for beaming three fourths");
  452. }
  453. }
  454. }
  455. }
  456. if (options.percussionOneLineCutoff !== undefined) {
  457. this.rules.PercussionOneLineCutoff = options.percussionOneLineCutoff;
  458. }
  459. if (this.rules.PercussionOneLineCutoff !== 0 &&
  460. options.percussionForceVoicesOneLineCutoff !== undefined) {
  461. this.rules.PercussionForceVoicesOneLineCutoff = options.percussionForceVoicesOneLineCutoff;
  462. }
  463. if (options.alignRests !== undefined) {
  464. this.rules.AlignRests = options.alignRests;
  465. }
  466. if (options.coloringMode !== undefined) {
  467. this.setColoringMode(options);
  468. }
  469. if (options.coloringEnabled !== undefined) {
  470. this.rules.ColoringEnabled = options.coloringEnabled;
  471. }
  472. if (options.colorStemsLikeNoteheads !== undefined) {
  473. this.rules.ColorStemsLikeNoteheads = options.colorStemsLikeNoteheads;
  474. }
  475. if (options.disableCursor) {
  476. this.drawingParameters.drawCursors = false;
  477. }
  478. // alternative to if block: this.drawingsParameters.drawCursors = options.drawCursors !== false. No if, but always sets drawingParameters.
  479. // note that every option can be undefined, which doesn't mean the option should be set to false.
  480. if (options.drawHiddenNotes) {
  481. this.drawingParameters.drawHiddenNotes = true; // not yet supported
  482. }
  483. if (options.drawCredits !== undefined) {
  484. this.drawingParameters.DrawCredits = options.drawCredits; // sets DrawComposer, DrawTitle, DrawSubtitle, DrawLyricist.
  485. }
  486. if (options.drawComposer !== undefined) {
  487. this.drawingParameters.DrawComposer = options.drawComposer;
  488. }
  489. if (options.drawTitle !== undefined) {
  490. this.drawingParameters.DrawTitle = options.drawTitle;
  491. }
  492. if (options.drawSubtitle !== undefined) {
  493. this.drawingParameters.DrawSubtitle = options.drawSubtitle;
  494. }
  495. if (options.drawLyricist !== undefined) {
  496. this.drawingParameters.DrawLyricist = options.drawLyricist;
  497. }
  498. if (options.drawMetronomeMarks !== undefined) {
  499. this.rules.MetronomeMarksDrawn = options.drawMetronomeMarks;
  500. }
  501. if (options.drawPartNames !== undefined) {
  502. this.drawingParameters.DrawPartNames = options.drawPartNames; // indirectly writes to EngravingRules
  503. // by default, disable part abbreviations too, unless set explicitly.
  504. if (!options.drawPartAbbreviations) {
  505. this.rules.RenderPartAbbreviations = options.drawPartNames;
  506. }
  507. }
  508. if (options.drawPartAbbreviations !== undefined) {
  509. this.rules.RenderPartAbbreviations = options.drawPartAbbreviations;
  510. }
  511. if (options.drawFingerings === false) {
  512. this.rules.RenderFingerings = false;
  513. }
  514. if (options.drawMeasureNumbers !== undefined) {
  515. this.rules.RenderMeasureNumbers = options.drawMeasureNumbers;
  516. }
  517. if (options.drawMeasureNumbersOnlyAtSystemStart) {
  518. this.rules.RenderMeasureNumbersOnlyAtSystemStart = options.drawMeasureNumbersOnlyAtSystemStart;
  519. }
  520. if (options.drawLyrics !== undefined) {
  521. this.rules.RenderLyrics = options.drawLyrics;
  522. }
  523. if (options.drawTimeSignatures !== undefined) {
  524. this.rules.RenderTimeSignatures = options.drawTimeSignatures;
  525. }
  526. if (options.drawSlurs !== undefined) {
  527. this.rules.RenderSlurs = options.drawSlurs;
  528. }
  529. if (options.measureNumberInterval !== undefined) {
  530. this.rules.MeasureNumberLabelOffset = options.measureNumberInterval;
  531. }
  532. if (options.useXMLMeasureNumbers !== undefined) {
  533. this.rules.UseXMLMeasureNumbers = options.useXMLMeasureNumbers;
  534. }
  535. if (options.fingeringPosition !== undefined) {
  536. this.rules.FingeringPosition = AbstractExpression.PlacementEnumFromString(options.fingeringPosition);
  537. }
  538. if (options.fingeringInsideStafflines !== undefined) {
  539. this.rules.FingeringInsideStafflines = options.fingeringInsideStafflines;
  540. }
  541. if (options.newSystemFromXML !== undefined) {
  542. this.rules.NewSystemAtXMLNewSystemAttribute = options.newSystemFromXML;
  543. }
  544. if (options.newPageFromXML !== undefined) {
  545. this.rules.NewPageAtXMLNewPageAttribute = options.newPageFromXML;
  546. }
  547. if (options.fillEmptyMeasuresWithWholeRest !== undefined) {
  548. this.rules.FillEmptyMeasuresWithWholeRest = options.fillEmptyMeasuresWithWholeRest;
  549. }
  550. if (options.followCursor !== undefined) {
  551. this.FollowCursor = options.followCursor;
  552. }
  553. if (options.setWantedStemDirectionByXml !== undefined) {
  554. this.rules.SetWantedStemDirectionByXml = options.setWantedStemDirectionByXml;
  555. }
  556. if (options.defaultColorNotehead) {
  557. this.rules.DefaultColorNotehead = options.defaultColorNotehead;
  558. }
  559. if (options.defaultColorRest) {
  560. this.rules.DefaultColorRest = options.defaultColorRest;
  561. }
  562. if (options.defaultColorStem) {
  563. this.rules.DefaultColorStem = options.defaultColorStem;
  564. }
  565. if (options.defaultColorLabel) {
  566. this.rules.DefaultColorLabel = options.defaultColorLabel;
  567. }
  568. if (options.defaultColorTitle) {
  569. this.rules.DefaultColorTitle = options.defaultColorTitle;
  570. }
  571. if (options.defaultFontFamily) {
  572. this.rules.DefaultFontFamily = options.defaultFontFamily; // default "Times New Roman", also used if font family not found
  573. }
  574. if (options.defaultFontStyle) {
  575. this.rules.DefaultFontStyle = options.defaultFontStyle; // e.g. FontStyles.Bold
  576. }
  577. if (options.drawUpToMeasureNumber) {
  578. this.rules.MaxMeasureToDrawIndex = options.drawUpToMeasureNumber - 1;
  579. }
  580. if (options.drawFromMeasureNumber) {
  581. this.rules.MinMeasureToDrawIndex = options.drawFromMeasureNumber - 1;
  582. }
  583. if (options.drawUpToPageNumber) {
  584. this.rules.MaxPageToDrawNumber = options.drawUpToPageNumber;
  585. }
  586. if (options.drawUpToSystemNumber) {
  587. this.rules.MaxSystemToDrawNumber = options.drawUpToSystemNumber;
  588. }
  589. if (options.tupletsRatioed) {
  590. this.rules.TupletsRatioed = true;
  591. }
  592. if (options.tupletsBracketed) {
  593. this.rules.TupletsBracketed = true;
  594. }
  595. if (options.tripletsBracketed) {
  596. this.rules.TripletsBracketed = true;
  597. }
  598. if (options.autoResize) {
  599. if (!this.resizeHandlerAttached) {
  600. this.autoResize();
  601. }
  602. this.autoResizeEnabled = true;
  603. } else if (options.autoResize === false) { // not undefined
  604. this.autoResizeEnabled = false;
  605. // we could remove the window EventListener here, but not necessary.
  606. }
  607. if (options.pageFormat !== undefined) { // only change this option if it was given, see above
  608. this.setPageFormat(options.pageFormat);
  609. }
  610. if (options.pageBackgroundColor !== undefined) {
  611. this.rules.PageBackgroundColor = options.pageBackgroundColor;
  612. }
  613. if (options.performanceMode !== undefined) {
  614. this.rules.PerformanceMode = options.performanceMode;
  615. }
  616. if (options.renderSingleHorizontalStaffline !== undefined) {
  617. this.rules.RenderSingleHorizontalStaffline = options.renderSingleHorizontalStaffline;
  618. }
  619. if (options.spacingFactorSoftmax !== undefined) {
  620. this.rules.SoftmaxFactorVexFlow = options.spacingFactorSoftmax;
  621. }
  622. if (options.spacingBetweenTextLines !== undefined) {
  623. this.rules.SpacingBetweenTextLines = options.spacingBetweenTextLines;
  624. }
  625. if (options.stretchLastSystemLine !== undefined) {
  626. this.rules.StretchLastSystemLine = options.stretchLastSystemLine;
  627. }
  628. if (options.autoGenerateMutipleRestMeasuresFromRestMeasures !== undefined) {
  629. this.rules.AutoGenerateMutipleRestMeasuresFromRestMeasures = options.autoGenerateMutipleRestMeasuresFromRestMeasures;
  630. }
  631. if (options.cursorsOptions !== undefined) {
  632. this.cursorsOptions = options.cursorsOptions;
  633. } else {
  634. this.cursorsOptions = [{type: 0, color: this.EngravingRules.DefaultColorCursor, alpha: 0.5, follow: options.followCursor}];
  635. }
  636. }
  637. public setColoringMode(options: IOSMDOptions): void {
  638. if (options.coloringMode === ColoringModes.XML) {
  639. this.rules.ColoringMode = ColoringModes.XML;
  640. return;
  641. }
  642. const noteIndices: NoteEnum[] = [NoteEnum.C, NoteEnum.D, NoteEnum.E, NoteEnum.F, NoteEnum.G, NoteEnum.A, NoteEnum.B, -1];
  643. let colorSetString: string[];
  644. if (options.coloringMode === ColoringModes.CustomColorSet) {
  645. if (!options.coloringSetCustom || options.coloringSetCustom.length !== 8) {
  646. throw new Error("Invalid amount of colors: With coloringModes.customColorSet, " +
  647. "you have to provide a coloringSetCustom parameter with 8 strings (C to B, rest note).");
  648. }
  649. // validate strings input
  650. for (const colorString of options.coloringSetCustom) {
  651. const regExp: RegExp = /^\#[0-9a-fA-F]{6}$/;
  652. if (!regExp.test(colorString)) {
  653. throw new Error(
  654. "One of the color strings in options.coloringSetCustom was not a valid HTML Hex color:\n" + colorString);
  655. }
  656. }
  657. colorSetString = options.coloringSetCustom;
  658. } else if (options.coloringMode === ColoringModes.AutoColoring) {
  659. colorSetString = [];
  660. const keys: string[] = Object.keys(AutoColorSet);
  661. for (let i: number = 0; i < keys.length; i++) {
  662. colorSetString.push(AutoColorSet[keys[i]]);
  663. }
  664. } // for both cases:
  665. const coloringSetCurrent: Dictionary<NoteEnum | number, string> = new Dictionary<NoteEnum | number, string>();
  666. for (let i: number = 0; i < noteIndices.length; i++) {
  667. coloringSetCurrent.setValue(noteIndices[i], colorSetString[i]);
  668. }
  669. coloringSetCurrent.setValue(-1, colorSetString[7]);
  670. this.rules.ColoringSetCurrent = coloringSetCurrent;
  671. this.rules.ColoringMode = options.coloringMode;
  672. }
  673. /**
  674. * Sets the logging level for this OSMD instance. By default, this is set to `warn`.
  675. *
  676. * @param: content can be `trace`, `debug`, `info`, `warn` or `error`.
  677. */
  678. public setLogLevel(level: string): void {
  679. switch (level) {
  680. case "trace":
  681. log.setLevel(log.levels.TRACE);
  682. break;
  683. case "debug":
  684. log.setLevel(log.levels.DEBUG);
  685. break;
  686. case "info":
  687. log.setLevel(log.levels.INFO);
  688. break;
  689. case "warn":
  690. log.setLevel(log.levels.WARN);
  691. break;
  692. case "error":
  693. log.setLevel(log.levels.ERROR);
  694. break;
  695. case "silent":
  696. log.setLevel(log.levels.SILENT);
  697. break;
  698. default:
  699. log.warn(`Could not set log level to ${level}. Using warn instead.`);
  700. log.setLevel(log.levels.WARN);
  701. break;
  702. }
  703. }
  704. public getLogLevel(): number {
  705. return log.getLevel();
  706. }
  707. /**
  708. * Initialize this object to default values
  709. * FIXME: Probably unnecessary
  710. */
  711. protected reset(): void {
  712. if (this.drawingParameters.drawCursors) {
  713. this.cursors.forEach(cursor => {
  714. cursor.hide();
  715. });
  716. }
  717. this.sheet = undefined;
  718. this.graphic = undefined;
  719. this.zoom = 1.0;
  720. }
  721. /**
  722. * Attach the appropriate handler to the window.onResize event
  723. */
  724. protected autoResize(): void {
  725. const self: OpenSheetMusicDisplay = this;
  726. this.handleResize(
  727. () => {
  728. // empty
  729. },
  730. () => {
  731. // The following code is probably not needed
  732. // (the width should adapt itself to the max allowed)
  733. //let width: number = Math.max(
  734. // document.documentElement.clientWidth,
  735. // document.body.scrollWidth,
  736. // document.documentElement.scrollWidth,
  737. // document.body.offsetWidth,
  738. // document.documentElement.offsetWidth
  739. //);
  740. //self.container.style.width = width + "px";
  741. // recalculate beams, are otherwise not updated and can detach from stems, see #724
  742. if (this.graphic?.GetCalculator instanceof VexFlowMusicSheetCalculator) { // null and type check
  743. (this.graphic.GetCalculator as VexFlowMusicSheetCalculator).beamsNeedUpdate = true;
  744. }
  745. if (self.IsReadyToRender()) {
  746. self.render();
  747. }
  748. }
  749. );
  750. }
  751. /**
  752. * Helper function for managing window's onResize events
  753. * @param startCallback is the function called when resizing starts
  754. * @param endCallback is the function called when resizing (kind-of) ends
  755. */
  756. protected handleResize(startCallback: () => void, endCallback: () => void): void {
  757. let rtime: number;
  758. let timeout: number = undefined;
  759. const delta: number = 200;
  760. const self: OpenSheetMusicDisplay = this;
  761. function resizeStart(): void {
  762. if (!self.AutoResizeEnabled) {
  763. return;
  764. }
  765. rtime = (new Date()).getTime();
  766. if (!timeout) {
  767. startCallback();
  768. rtime = (new Date()).getTime();
  769. timeout = window.setTimeout(resizeEnd, delta);
  770. }
  771. }
  772. function resizeEnd(): void {
  773. timeout = undefined;
  774. window.clearTimeout(timeout);
  775. if ((new Date()).getTime() - rtime < delta) {
  776. timeout = window.setTimeout(resizeEnd, delta);
  777. } else {
  778. endCallback();
  779. }
  780. }
  781. if ((<any>window).attachEvent) {
  782. // Support IE<9
  783. (<any>window).attachEvent("onresize", resizeStart);
  784. } else {
  785. window.addEventListener("resize", resizeStart);
  786. }
  787. this.disposeResizeListener = (): void => {
  788. if ((<any>window).detachEvent) {
  789. // Support IE<9
  790. (<any>window).detachEvent ("onresize", resizeStart);
  791. } else {
  792. window.removeEventListener("resize", resizeStart);
  793. }
  794. this.resizeHandlerAttached = false;
  795. };
  796. this.resizeHandlerAttached = true;
  797. window.setTimeout(startCallback, 0);
  798. window.setTimeout(endCallback, 1);
  799. }
  800. /** Enable or disable (hide) the cursor.
  801. * @param enable whether to enable (true) or disable (false) the cursor
  802. */
  803. public enableOrDisableCursors(enable: boolean): void {
  804. this.drawingParameters.drawCursors = enable;
  805. if (enable) {
  806. for (let i: number = 0; i < this.cursorsOptions.length; i++){
  807. // save previous cursor state
  808. const hidden: boolean = this.cursors[i]?.Hidden;
  809. const previousIterator: MusicPartManagerIterator = this.cursors[i]?.Iterator;
  810. this.cursors[i]?.hide();
  811. // check which page/backend to draw the cursor on (the pages may have changed since last cursor)
  812. let backendToDrawOn: VexFlowBackend = this.drawer?.Backends[0];
  813. if (backendToDrawOn && this.rules.RestoreCursorAfterRerender && this.cursors[i]) {
  814. const newPageNumber: number = this.cursors[i].updateCurrentPage();
  815. backendToDrawOn = this.drawer.Backends[newPageNumber - 1];
  816. }
  817. // create new cursor
  818. if (backendToDrawOn && backendToDrawOn.getRenderElement()) {
  819. this.cursors[i] = new Cursor(backendToDrawOn.getRenderElement(), this, this.cursorsOptions[i]);
  820. }
  821. if (this.sheet && this.graphic && this.cursors[i]) { // else init is called in load()
  822. this.cursors[i].init(this.sheet.MusicPartManager, this.graphic);
  823. }
  824. // restore old cursor state
  825. if (this.rules.RestoreCursorAfterRerender) {
  826. this.cursors[i].hidden = hidden;
  827. if (previousIterator) {
  828. this.cursors[i].iterator = previousIterator;
  829. this.cursors[i].update();
  830. }
  831. }
  832. }
  833. this.renderingManager.PlaybackManager?.addListener(this.cursor);
  834. } else { // disable cursor
  835. this.cursors.forEach(cursor => {
  836. cursor.hide();
  837. });
  838. // this.cursor = undefined;
  839. // TODO cursor should be disabled, not just hidden. otherwise user can just call osmd.cursor.hide().
  840. // however, this could cause null calls (cursor.next() etc), maybe that needs some solution.
  841. }
  842. }
  843. public createBackend(type: BackendType, page: GraphicalMusicPage): VexFlowBackend {
  844. let backend: VexFlowBackend;
  845. if (type === undefined || type === BackendType.SVG) {
  846. backend = new SvgVexFlowBackend(this.rules);
  847. } else {
  848. backend = new CanvasVexFlowBackend(this.rules);
  849. }
  850. backend.graphicalMusicPage = page; // the page the backend renders on. needed to identify DOM element to extract image/SVG
  851. backend.initialize(this.container, this.zoom);
  852. return backend;
  853. }
  854. /** Standard page format options like A4 or Letter, in portrait and landscape. E.g. PageFormatStandards["A4_P"] or PageFormatStandards["Letter_L"]. */
  855. public static PageFormatStandards: { [type: string]: PageFormat } = {
  856. "A3_L": new PageFormat(420, 297, "A3_L"), // id strings should use underscores instead of white spaces to facilitate use as URL parameters.
  857. "A3_P": new PageFormat(297, 420, "A3_P"),
  858. "A4_L": new PageFormat(297, 210, "A4_L"),
  859. "A4_P": new PageFormat(210, 297, "A4_P"),
  860. "A5_L": new PageFormat(210, 148, "A5_L"),
  861. "A5_P": new PageFormat(148, 210, "A5_P"),
  862. "A6_L": new PageFormat(148, 105, "A6_L"),
  863. "A6_P": new PageFormat(105, 148, "A6_P"),
  864. "Endless": PageFormat.UndefinedPageFormat,
  865. "Letter_L": new PageFormat(279.4, 215.9, "Letter_L"),
  866. "Letter_P": new PageFormat(215.9, 279.4, "Letter_P")
  867. };
  868. public static StringToPageFormat(pageFormatString: string): PageFormat {
  869. let pageFormat: PageFormat = PageFormat.UndefinedPageFormat; // default: 'endless' page height, take canvas/container width
  870. // check for widthxheight parameter, e.g. "800x600"
  871. if (pageFormatString.match("^[0-9]+x[0-9]+$")) {
  872. const widthAndHeight: string[] = pageFormatString.split("x");
  873. const width: number = Number.parseInt(widthAndHeight[0], 10);
  874. const height: number = Number.parseInt(widthAndHeight[1], 10);
  875. if (width > 0 && width < 32768 && height > 0 && height < 32768) {
  876. pageFormat = new PageFormat(width, height, `customPageFormat${pageFormatString}`);
  877. }
  878. }
  879. // check for formatId from OpenSheetMusicDisplay.PageFormatStandards
  880. pageFormatString = pageFormatString.replace(" ", "_");
  881. pageFormatString = pageFormatString.replace("Landscape", "L");
  882. pageFormatString = pageFormatString.replace("Portrait", "P");
  883. //console.log("change format to: " + formatId);
  884. if (OpenSheetMusicDisplay.PageFormatStandards.hasOwnProperty(pageFormatString)) {
  885. pageFormat = OpenSheetMusicDisplay.PageFormatStandards[pageFormatString];
  886. return pageFormat;
  887. }
  888. return pageFormat;
  889. }
  890. /** Sets page format by string. Used by setOptions({pageFormat: "A4_P"}) for example. */
  891. public setPageFormat(formatId: string): void {
  892. const newPageFormat: PageFormat = OpenSheetMusicDisplay.StringToPageFormat(formatId);
  893. this.needBackendUpdate = !(newPageFormat.Equals(this.rules.PageFormat));
  894. this.rules.PageFormat = newPageFormat;
  895. }
  896. public setCustomPageFormat(width: number, height: number): void {
  897. if (width > 0 && height > 0) {
  898. const f: PageFormat = new PageFormat(width, height);
  899. this.rules.PageFormat = f;
  900. }
  901. }
  902. //#region GETTER / SETTER
  903. public set DrawSkyLine(value: boolean) {
  904. this.drawSkyLine = value;
  905. if (this.drawer) {
  906. this.drawer.skyLineVisible = value;
  907. // this.render(); // note: we probably shouldn't automatically render when someone sets the setter
  908. // this can cause a lot of rendering time.
  909. }
  910. }
  911. public get DrawSkyLine(): boolean {
  912. return this.drawer.skyLineVisible;
  913. }
  914. public set DrawBottomLine(value: boolean) {
  915. this.drawBottomLine = value;
  916. if (this.drawer) {
  917. this.drawer.bottomLineVisible = value;
  918. // this.render(); // note: we probably shouldn't automatically render when someone sets the setter
  919. // this can cause a lot of rendering time.
  920. }
  921. }
  922. public get DrawBottomLine(): boolean {
  923. return this.drawer.bottomLineVisible;
  924. }
  925. public set DrawBoundingBox(value: string) {
  926. this.setDrawBoundingBox(value, true);
  927. }
  928. public get DrawBoundingBox(): string {
  929. return this.drawBoundingBox;
  930. }
  931. public setDrawBoundingBox(value: string, render: boolean = false): void {
  932. this.drawBoundingBox = value;
  933. if (this.drawer) {
  934. this.drawer.drawableBoundingBoxElement = value; // drawer is sometimes created anew, losing this value, so it's saved in OSMD now.
  935. }
  936. if (render) {
  937. this.render(); // may create new Drawer.
  938. }
  939. }
  940. public get AutoResizeEnabled(): boolean {
  941. return this.autoResizeEnabled;
  942. }
  943. public set AutoResizeEnabled(value: boolean) {
  944. this.autoResizeEnabled = value;
  945. }
  946. public get Zoom(): number {
  947. return this.zoom;
  948. }
  949. public set Zoom(value: number) {
  950. this.zoom = value;
  951. this.zoomUpdated = true;
  952. if (this.graphic?.GetCalculator instanceof VexFlowMusicSheetCalculator) { // null and type check
  953. (this.graphic.GetCalculator as VexFlowMusicSheetCalculator).beamsNeedUpdate = this.zoomUpdated;
  954. }
  955. }
  956. public set FollowCursor(value: boolean) {
  957. this.followCursor = value;
  958. }
  959. public get FollowCursor(): boolean {
  960. return this.followCursor;
  961. }
  962. public set TransposeCalculator(calculator: ITransposeCalculator) {
  963. MusicSheetCalculator.transposeCalculator = calculator;
  964. }
  965. public get TransposeCalculator(): ITransposeCalculator {
  966. return MusicSheetCalculator.transposeCalculator;
  967. }
  968. public get Sheet(): MusicSheet {
  969. return this.sheet;
  970. }
  971. public get Drawer(): VexFlowMusicSheetDrawer {
  972. return this.drawer;
  973. }
  974. public get GraphicSheet(): GraphicalMusicSheet {
  975. return this.graphic;
  976. }
  977. public get DrawingParameters(): DrawingParameters {
  978. return this.drawingParameters;
  979. }
  980. public get EngravingRules(): EngravingRules { // custom getter, useful for engraving parameter setting in Demo
  981. return this.rules;
  982. }
  983. public get InteractionManager(): AbstractDisplayInteractionManager {
  984. return this.interactionManager;
  985. }
  986. /** Returns the version of OSMD this object is built from (the version you are using). */
  987. public get Version(): string {
  988. return this.version;
  989. }
  990. //#endregion
  991. }