OpenSheetMusicDisplay.ts 46 KB

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