OpenSheetMusicDisplay.ts 52 KB

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