OpenSheetMusicDisplay.ts 52 KB

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