OpenSheetMusicDisplay.ts 49 KB

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