OpenSheetMusicDisplay.ts 39 KB

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