OpenSheetMusicDisplay.ts 49 KB

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