OpenSheetMusicDisplay.ts 41 KB

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