OpenSheetMusicDisplay.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  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 { Promise } from "es6-promise";
  14. import { AJAX } from "./AJAX";
  15. import * as log from "loglevel";
  16. import { DrawingParametersEnum, DrawingParameters, ColoringModes } from "../MusicalScore/Graphical/DrawingParameters";
  17. import { IOSMDOptions, OSMDOptions, AutoBeamOptions, BackendType } from "./OSMDOptions";
  18. import { EngravingRules, PageFormat } from "../MusicalScore/Graphical/EngravingRules";
  19. import { AbstractExpression } from "../MusicalScore/VoiceData/Expressions/AbstractExpression";
  20. import { Dictionary } from "typescript-collections";
  21. import { NoteEnum } from "..";
  22. import { AutoColorSet, GraphicalMusicPage } from "../MusicalScore";
  23. import jspdf = require("jspdf-yworks/dist/jspdf.min");
  24. import svg2pdf = require("svg2pdf.js/dist/svg2pdf.min");
  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.7.6-release"; // 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. if (str.substr(0, 6).includes("<?xml")) { // first character is sometimes null, making first five characters '<?xm'.
  110. log.debug("[OSMD] Finally parsing XML content, length: " + str.length);
  111. // Parse the string representing an xml file
  112. const parser: DOMParser = new DOMParser();
  113. content = parser.parseFromString(str, "application/xml");
  114. } else if (str.length < 2083) {
  115. log.debug("[OSMD] Retrieve the file at the given URL: " + str);
  116. // Assume now "str" is a URL
  117. // Retrieve the file at the given URL
  118. return AJAX.ajax(str).then(
  119. (s: string) => { return self.load(s); },
  120. (exc: Error) => { throw exc; }
  121. );
  122. } else {
  123. console.error("[OSMD] osmd.load(string): Could not process string. Missing else branch?");
  124. }
  125. }
  126. if (!content || !(<any>content).nodeName) {
  127. return Promise.reject(new Error("OpenSheetMusicDisplay: The document which was provided is invalid"));
  128. }
  129. const xmlDocument: Document = (<Document>content);
  130. const xmlDocumentNodes: NodeList = xmlDocument.childNodes;
  131. log.debug("[OSMD] load(), Document url: " + xmlDocument.URL);
  132. let scorePartwiseElement: Element;
  133. for (let i: number = 0, length: number = xmlDocumentNodes.length; i < length; i += 1) {
  134. const node: Node = xmlDocumentNodes[i];
  135. if (node.nodeType === Node.ELEMENT_NODE && node.nodeName.toLowerCase() === "score-partwise") {
  136. scorePartwiseElement = <Element>node;
  137. break;
  138. }
  139. }
  140. if (!scorePartwiseElement) {
  141. console.error("Could not parse MusicXML, no valid partwise element found");
  142. return Promise.reject(new Error("OpenSheetMusicDisplay: Document is not a valid 'partwise' MusicXML"));
  143. }
  144. const score: IXmlElement = new IXmlElement(scorePartwiseElement);
  145. const reader: MusicSheetReader = new MusicSheetReader(undefined, this.rules);
  146. this.sheet = reader.createMusicSheet(score, "Untitled Score");
  147. if (this.sheet === undefined) {
  148. // error loading sheet, probably already logged, do nothing
  149. return Promise.reject(new Error("given music sheet was incomplete or could not be loaded."));
  150. }
  151. log.info(`[OSMD] Loaded sheet ${this.sheet.TitleString} successfully.`);
  152. this.needBackendUpdate = true;
  153. this.updateGraphic();
  154. return Promise.resolve({});
  155. }
  156. /**
  157. * (Re-)creates the graphic sheet from the music sheet
  158. */
  159. public updateGraphic(): void {
  160. const calc: MusicSheetCalculator = new VexFlowMusicSheetCalculator(this.rules);
  161. this.graphic = new GraphicalMusicSheet(this.sheet, calc);
  162. if (this.drawingParameters.drawCursors && this.cursor) {
  163. this.cursor.init(this.sheet.MusicPartManager, this.graphic);
  164. }
  165. }
  166. /**
  167. * Render the music sheet in the container
  168. */
  169. public render(): void {
  170. if (!this.graphic) {
  171. throw new Error("OpenSheetMusicDisplay: Before rendering a music sheet, please load a MusicXML file");
  172. }
  173. if (this.drawer) {
  174. this.drawer.clear(); // clear canvas before setting width
  175. }
  176. // musicSheetCalculator.clearSystemsAndMeasures() // maybe? don't have reference though
  177. // musicSheetCalculator.clearRecreatedObjects();
  178. // Set page width
  179. let width: number = this.container.offsetWidth;
  180. if (this.rules.RenderSingleHorizontalStaffline) {
  181. width = 32767; // set safe maximum (browser limit), will be reduced later
  182. // reduced later in MusicSheetCalculator.calculatePageLabels (sets sheet.pageWidth to page.PositionAndShape.Size.width before labels)
  183. // rough calculation:
  184. // width = 600 * this.sheet.SourceMeasures.length;
  185. }
  186. // log.debug("[OSMD] render width: " + width);
  187. this.sheet.pageWidth = width / this.zoom / 10.0;
  188. if (this.rules.PageFormat && !this.rules.PageFormat.IsUndefined) {
  189. this.rules.PageHeight = this.sheet.pageWidth / this.rules.PageFormat.aspectRatio;
  190. log.debug("[OSMD] PageHeight: " + this.rules.PageHeight);
  191. } else {
  192. log.debug("[OSMD] endless/undefined pageformat, id: " + this.rules.PageFormat.idString);
  193. this.rules.PageHeight = 100001; // infinite page height // TODO maybe Number.MAX_VALUE or Math.pow(10, 20)?
  194. }
  195. // Before introducing the following optimization (maybe irrelevant), tests
  196. // have to be modified to ensure that width is > 0 when executed
  197. //if (isNaN(width) || width === 0) {
  198. // return;
  199. //}
  200. // Calculate again
  201. this.graphic.reCalculate();
  202. if (this.drawingParameters.drawCursors) {
  203. this.graphic.Cursors.length = 0;
  204. }
  205. // needBackendUpdate is well intentioned, but we need to cover all cases.
  206. // backends also need an update when this.zoom was set from outside, which unfortunately doesn't have a setter method to set this in.
  207. // 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.
  208. if (true || this.needBackendUpdate) {
  209. this.createOrRefreshRenderBackend();
  210. this.needBackendUpdate = false;
  211. }
  212. this.drawer.setZoom(this.zoom);
  213. // Finally, draw
  214. this.drawer.drawSheet(this.graphic);
  215. this.enableOrDisableCursor(this.drawingParameters.drawCursors);
  216. if (this.drawingParameters.drawCursors && this.cursor) {
  217. // Update the cursor position
  218. this.cursor.update();
  219. }
  220. this.zoomUpdated = false;
  221. //console.log("[OSMD] render finished");
  222. }
  223. private createOrRefreshRenderBackend(): void {
  224. // console.log("[OSMD] createOrRefreshRenderBackend()");
  225. // Remove old backends
  226. if (this.drawer && this.drawer.Backends) {
  227. // removing single children to remove all is error-prone, because sometimes a random SVG-child remains.
  228. // for (const backend of this.drawer.Backends) {
  229. // backend.removeFromContainer(this.container);
  230. // }
  231. if (this.drawer.Backends[0]) {
  232. this.drawer.Backends[0].removeAllChildrenFromContainer(this.container);
  233. }
  234. this.drawer.Backends.clear();
  235. }
  236. // Create the drawer
  237. this.drawingParameters.Rules = this.rules;
  238. this.drawer = new VexFlowMusicSheetDrawer(this.drawingParameters); // note that here the drawer.drawableBoundingBoxElement is lost. now saved in OSMD.
  239. this.drawer.drawableBoundingBoxElement = this.DrawBoundingBox;
  240. this.drawer.bottomLineVisible = this.drawBottomLine;
  241. this.drawer.skyLineVisible = this.drawSkyLine;
  242. // Set page width
  243. let width: number = this.container.offsetWidth;
  244. if (this.rules.RenderSingleHorizontalStaffline) {
  245. width = this.graphic.MusicPages[0].PositionAndShape.Size.width * 10 * this.zoom;
  246. // this.container.style.width = width + "px";
  247. // console.log("width: " + width)
  248. }
  249. // TODO width may need to be coordinated with render() where width is also used
  250. let height: number;
  251. const canvasDimensionsLimit: number = 32767; // browser limitation. Chrome/Firefox (16 bit, 32768 causes an error).
  252. // Could be calculated by canvas-size module.
  253. // see #678 on Github and here: https://stackoverflow.com/a/11585939/10295942
  254. // TODO check if resize is necessary. set needResize or something when size was changed
  255. for (const page of this.graphic.MusicPages) {
  256. const backend: VexFlowBackend = this.createBackend(this.backendType, page);
  257. const sizeWarningPartTwo: string = " exceeds CanvasBackend limit of 32767. Cutting off score.";
  258. if (backend.getOSMDBackendType() === BackendType.Canvas && width > canvasDimensionsLimit) {
  259. console.log("[OSMD] Warning: width of " + width + sizeWarningPartTwo);
  260. width = canvasDimensionsLimit;
  261. }
  262. if (this.rules.PageFormat && !this.rules.PageFormat.IsUndefined) {
  263. height = width / this.rules.PageFormat.aspectRatio;
  264. // console.log("pageformat given. height: " + page.PositionAndShape.Size.height);
  265. } else {
  266. height = (page.PositionAndShape.Size.height + 15) * this.zoom * 10.0;
  267. // console.log("pageformat not given. height: " + page.PositionAndShape.Size.height);
  268. }
  269. if (backend.getOSMDBackendType() === BackendType.Canvas && height > canvasDimensionsLimit) {
  270. console.log("[OSMD] Warning: height of " + height + sizeWarningPartTwo);
  271. height = Math.min(height, canvasDimensionsLimit); // this cuts off the the score, but doesn't break rendering.
  272. // TODO optional: reduce zoom to fit the score within the limit.
  273. }
  274. backend.resize(width, height);
  275. backend.clear(); // set bgcolor if defined (this.rules.PageBackgroundColor, see OSMDOptions)
  276. this.drawer.Backends.push(backend);
  277. }
  278. }
  279. /** States whether the render() function can be safely called. */
  280. public IsReadyToRender(): boolean {
  281. return this.graphic !== undefined;
  282. }
  283. /** Clears what OSMD has drawn on its canvas. */
  284. public clear(): void {
  285. this.drawer.clear();
  286. this.reset(); // without this, resize will draw loaded sheet again
  287. }
  288. /** Set OSMD rendering options using an IOSMDOptions object.
  289. * Can be called during runtime. Also called by constructor.
  290. * For example, setOptions({autoResize: false}) will disable autoResize even during runtime.
  291. */
  292. public setOptions(options: IOSMDOptions): void {
  293. if (!this.rules) {
  294. this.rules = new EngravingRules();
  295. }
  296. if (!this.drawingParameters) {
  297. this.drawingParameters = new DrawingParameters();
  298. this.drawingParameters.Rules = this.rules;
  299. }
  300. if (options === undefined || options === null) {
  301. log.warn("warning: osmd.setOptions() called without an options parameter, has no effect."
  302. + "\n" + "example usage: osmd.setOptions({drawCredits: false, drawPartNames: false})");
  303. return;
  304. }
  305. if (options.drawingParameters) {
  306. this.drawingParameters.DrawingParametersEnum =
  307. (<any>DrawingParametersEnum)[options.drawingParameters.toLowerCase()];
  308. if (this.drawingParameters.DrawingParametersEnum === DrawingParametersEnum.compacttight) {
  309. // tight rendering mode, lower margins and safety distances between systems, staffs etc. may cause overlap.
  310. // these options can afterwards be finetuned by setting osmd.rules.BetweenStaffDistance for example
  311. this.rules.BetweenStaffDistance = 2.5;
  312. this.rules.StaffDistance = 3.5;
  313. this.rules.MinimumDistanceBetweenSystems = 1;
  314. // this.rules.PageTopMargin = 0.0; // see this.rules.PageTopMarginNarrow used in compact mode
  315. this.rules.PageBottomMargin = 1.0;
  316. this.rules.PageLeftMargin = 2.0;
  317. this.rules.PageRightMargin = 2.0;
  318. }
  319. }
  320. const backendNotInitialized: boolean = !this.drawer || !this.drawer.Backends || this.drawer.Backends.length < 1;
  321. let needBackendUpdate: boolean = backendNotInitialized;
  322. if (options.backend !== undefined) {
  323. const backendTypeGiven: BackendType = OSMDOptions.BackendTypeFromString(options.backend);
  324. needBackendUpdate = needBackendUpdate || this.backendType !== backendTypeGiven;
  325. this.backendType = backendTypeGiven;
  326. }
  327. this.needBackendUpdate = needBackendUpdate;
  328. // TODO this is a necessary step during the OSMD constructor. Maybe move this somewhere else
  329. // individual drawing parameters options
  330. if (options.autoBeam !== undefined) { // only change an option if it was given in options, otherwise it will be undefined
  331. this.rules.AutoBeamNotes = options.autoBeam;
  332. }
  333. const autoBeamOptions: AutoBeamOptions = options.autoBeamOptions;
  334. if (autoBeamOptions) {
  335. if (autoBeamOptions.maintain_stem_directions === undefined) {
  336. autoBeamOptions.maintain_stem_directions = false;
  337. }
  338. this.rules.AutoBeamOptions = autoBeamOptions;
  339. if (autoBeamOptions.groups && autoBeamOptions.groups.length) {
  340. for (const fraction of autoBeamOptions.groups) {
  341. if (fraction.length !== 2) {
  342. throw new Error("Each fraction in autoBeamOptions.groups must be of length 2, e.g. [3,4] for beaming three fourths");
  343. }
  344. }
  345. }
  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;
  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.drawPartNames !== undefined) {
  383. this.drawingParameters.DrawPartNames = options.drawPartNames; // indirectly writes to EngravingRules
  384. }
  385. if (options.drawPartAbbreviations !== undefined) {
  386. this.rules.RenderPartAbbreviations = options.drawPartAbbreviations;
  387. }
  388. if (options.drawFingerings === false) {
  389. this.rules.RenderFingerings = false;
  390. }
  391. if (options.drawMeasureNumbers !== undefined) {
  392. this.rules.RenderMeasureNumbers = options.drawMeasureNumbers;
  393. }
  394. if (options.drawLyrics !== undefined) {
  395. this.rules.RenderLyrics = options.drawLyrics;
  396. }
  397. if (options.drawSlurs !== undefined) {
  398. this.rules.RenderSlurs = options.drawSlurs;
  399. }
  400. if (options.measureNumberInterval !== undefined) {
  401. this.rules.MeasureNumberLabelOffset = options.measureNumberInterval;
  402. }
  403. if (options.fingeringPosition !== undefined) {
  404. this.rules.FingeringPosition = AbstractExpression.PlacementEnumFromString(options.fingeringPosition);
  405. }
  406. if (options.fingeringInsideStafflines !== undefined) {
  407. this.rules.FingeringInsideStafflines = options.fingeringInsideStafflines;
  408. }
  409. if (options.newSystemFromXML !== undefined) {
  410. this.rules.NewSystemAtXMLNewSystemAttribute = options.newSystemFromXML;
  411. }
  412. if (options.newPageFromXML !== undefined) {
  413. this.rules.NewPageAtXMLNewPageAttribute = options.newPageFromXML;
  414. }
  415. if (options.fillEmptyMeasuresWithWholeRest !== undefined) {
  416. this.rules.FillEmptyMeasuresWithWholeRest = options.fillEmptyMeasuresWithWholeRest;
  417. }
  418. if (options.followCursor !== undefined) {
  419. this.FollowCursor = options.followCursor;
  420. }
  421. if (options.setWantedStemDirectionByXml !== undefined) {
  422. this.rules.SetWantedStemDirectionByXml = options.setWantedStemDirectionByXml;
  423. }
  424. if (options.defaultColorNotehead) {
  425. this.rules.DefaultColorNotehead = options.defaultColorNotehead;
  426. }
  427. if (options.defaultColorRest) {
  428. this.rules.DefaultColorRest = options.defaultColorRest;
  429. }
  430. if (options.defaultColorStem) {
  431. this.rules.DefaultColorStem = options.defaultColorStem;
  432. }
  433. if (options.defaultColorLabel) {
  434. this.rules.DefaultColorLabel = options.defaultColorLabel;
  435. }
  436. if (options.defaultColorTitle) {
  437. this.rules.DefaultColorTitle = options.defaultColorTitle;
  438. }
  439. if (options.defaultFontFamily) {
  440. this.rules.DefaultFontFamily = options.defaultFontFamily; // default "Times New Roman", also used if font family not found
  441. }
  442. if (options.drawUpToMeasureNumber) {
  443. this.rules.MaxMeasureToDrawIndex = options.drawUpToMeasureNumber - 1;
  444. }
  445. if (options.drawFromMeasureNumber) {
  446. this.rules.MinMeasureToDrawIndex = options.drawFromMeasureNumber - 1;
  447. }
  448. if (options.tupletsRatioed) {
  449. this.rules.TupletsRatioed = true;
  450. }
  451. if (options.tupletsBracketed) {
  452. this.rules.TupletsBracketed = true;
  453. }
  454. if (options.tripletsBracketed) {
  455. this.rules.TripletsBracketed = true;
  456. }
  457. if (options.autoResize) {
  458. if (!this.resizeHandlerAttached) {
  459. this.autoResize();
  460. }
  461. this.autoResizeEnabled = true;
  462. } else if (options.autoResize === false) { // not undefined
  463. this.autoResizeEnabled = false;
  464. // we could remove the window EventListener here, but not necessary.
  465. }
  466. if (options.pageFormat !== undefined) { // only change this option if it was given, see above
  467. this.rules.PageFormat = OpenSheetMusicDisplay.StringToPageFormat(options.pageFormat);
  468. }
  469. if (options.pageBackgroundColor !== undefined) {
  470. this.rules.PageBackgroundColor = options.pageBackgroundColor;
  471. }
  472. if (options.renderSingleHorizontalStaffline !== undefined) {
  473. this.rules.RenderSingleHorizontalStaffline = options.renderSingleHorizontalStaffline;
  474. }
  475. }
  476. public setColoringMode(options: IOSMDOptions): void {
  477. if (options.coloringMode === ColoringModes.XML) {
  478. this.rules.ColoringMode = ColoringModes.XML;
  479. return;
  480. }
  481. const noteIndices: NoteEnum[] = [NoteEnum.C, NoteEnum.D, NoteEnum.E, NoteEnum.F, NoteEnum.G, NoteEnum.A, NoteEnum.B, -1];
  482. let colorSetString: string[];
  483. if (options.coloringMode === ColoringModes.CustomColorSet) {
  484. if (!options.coloringSetCustom || options.coloringSetCustom.length !== 8) {
  485. throw new Error("Invalid amount of colors: With coloringModes.customColorSet, " +
  486. "you have to provide a coloringSetCustom parameter with 8 strings (C to B, rest note).");
  487. }
  488. // validate strings input
  489. for (const colorString of options.coloringSetCustom) {
  490. const regExp: RegExp = /^\#[0-9a-fA-F]{6}$/;
  491. if (!regExp.test(colorString)) {
  492. throw new Error(
  493. "One of the color strings in options.coloringSetCustom was not a valid HTML Hex color:\n" + colorString);
  494. }
  495. }
  496. colorSetString = options.coloringSetCustom;
  497. } else if (options.coloringMode === ColoringModes.AutoColoring) {
  498. colorSetString = [];
  499. const keys: string[] = Object.keys(AutoColorSet);
  500. for (let i: number = 0; i < keys.length; i++) {
  501. colorSetString.push(AutoColorSet[keys[i]]);
  502. }
  503. } // for both cases:
  504. const coloringSetCurrent: Dictionary<NoteEnum | number, string> = new Dictionary<NoteEnum | number, string>();
  505. for (let i: number = 0; i < noteIndices.length; i++) {
  506. coloringSetCurrent.setValue(noteIndices[i], colorSetString[i]);
  507. }
  508. coloringSetCurrent.setValue(-1, colorSetString[7]);
  509. this.rules.ColoringSetCurrent = coloringSetCurrent;
  510. this.rules.ColoringMode = options.coloringMode;
  511. }
  512. /**
  513. * Sets the logging level for this OSMD instance. By default, this is set to `warn`.
  514. *
  515. * @param: content can be `trace`, `debug`, `info`, `warn` or `error`.
  516. */
  517. public setLogLevel(level: string): void {
  518. switch (level) {
  519. case "trace":
  520. log.setLevel(log.levels.TRACE);
  521. break;
  522. case "debug":
  523. log.setLevel(log.levels.DEBUG);
  524. break;
  525. case "info":
  526. log.setLevel(log.levels.INFO);
  527. break;
  528. case "warn":
  529. log.setLevel(log.levels.WARN);
  530. break;
  531. case "error":
  532. log.setLevel(log.levels.ERROR);
  533. break;
  534. default:
  535. log.warn(`Could not set log level to ${level}. Using warn instead.`);
  536. log.setLevel(log.levels.WARN);
  537. break;
  538. }
  539. }
  540. public getLogLevel(): number {
  541. return log.getLevel();
  542. }
  543. /**
  544. * Initialize this object to default values
  545. * FIXME: Probably unnecessary
  546. */
  547. private reset(): void {
  548. if (this.drawingParameters.drawCursors && this.cursor) {
  549. this.cursor.hide();
  550. }
  551. this.sheet = undefined;
  552. this.graphic = undefined;
  553. this.zoom = 1.0;
  554. }
  555. /**
  556. * Attach the appropriate handler to the window.onResize event
  557. */
  558. private autoResize(): void {
  559. const self: OpenSheetMusicDisplay = this;
  560. this.handleResize(
  561. () => {
  562. // empty
  563. },
  564. () => {
  565. // The following code is probably not needed
  566. // (the width should adapt itself to the max allowed)
  567. //let width: number = Math.max(
  568. // document.documentElement.clientWidth,
  569. // document.body.scrollWidth,
  570. // document.documentElement.scrollWidth,
  571. // document.body.offsetWidth,
  572. // document.documentElement.offsetWidth
  573. //);
  574. //self.container.style.width = width + "px";
  575. if (self.IsReadyToRender()) {
  576. self.render();
  577. }
  578. }
  579. );
  580. }
  581. /**
  582. * Helper function for managing window's onResize events
  583. * @param startCallback is the function called when resizing starts
  584. * @param endCallback is the function called when resizing (kind-of) ends
  585. */
  586. private handleResize(startCallback: () => void, endCallback: () => void): void {
  587. let rtime: number;
  588. let timeout: number = undefined;
  589. const delta: number = 200;
  590. const self: OpenSheetMusicDisplay = this;
  591. function resizeStart(): void {
  592. if (!self.AutoResizeEnabled) {
  593. return;
  594. }
  595. rtime = (new Date()).getTime();
  596. if (!timeout) {
  597. startCallback();
  598. rtime = (new Date()).getTime();
  599. timeout = window.setTimeout(resizeEnd, delta);
  600. }
  601. }
  602. function resizeEnd(): void {
  603. timeout = undefined;
  604. window.clearTimeout(timeout);
  605. if ((new Date()).getTime() - rtime < delta) {
  606. timeout = window.setTimeout(resizeEnd, delta);
  607. } else {
  608. endCallback();
  609. }
  610. }
  611. if ((<any>window).attachEvent) {
  612. // Support IE<9
  613. (<any>window).attachEvent("onresize", resizeStart);
  614. } else {
  615. window.addEventListener("resize", resizeStart);
  616. }
  617. this.resizeHandlerAttached = true;
  618. window.setTimeout(startCallback, 0);
  619. window.setTimeout(endCallback, 1);
  620. }
  621. /** Enable or disable (hide) the cursor.
  622. * @param enable whether to enable (true) or disable (false) the cursor
  623. */
  624. public enableOrDisableCursor(enable: boolean): void {
  625. this.drawingParameters.drawCursors = enable;
  626. if (enable) {
  627. this.cursor = new Cursor(this.drawer.Backends[0].getInnerElement(), this);
  628. if (this.sheet && this.graphic) { // else init is called in load()
  629. this.cursor.init(this.sheet.MusicPartManager, this.graphic);
  630. }
  631. } else { // disable cursor
  632. if (!this.cursor) {
  633. return;
  634. }
  635. this.cursor.hide();
  636. // this.cursor = undefined;
  637. // TODO cursor should be disabled, not just hidden. otherwise user can just call osmd.cursor.hide().
  638. // however, this could cause null calls (cursor.next() etc), maybe that needs some solution.
  639. }
  640. }
  641. public createBackend(type: BackendType, page: GraphicalMusicPage): VexFlowBackend {
  642. let backend: VexFlowBackend;
  643. if (type === undefined || type === BackendType.SVG) {
  644. backend = new SvgVexFlowBackend(this.rules);
  645. } else {
  646. backend = new CanvasVexFlowBackend(this.rules);
  647. }
  648. backend.graphicalMusicPage = page; // the page the backend renders on. needed to identify DOM element to extract image/SVG
  649. backend.initialize(this.container);
  650. return backend;
  651. }
  652. /** Standard page format options like A4 or Letter, in portrait and landscape. E.g. PageFormatStandards["A4_P"] or PageFormatStandards["Letter_L"]. */
  653. public static PageFormatStandards: { [type: string]: PageFormat } = {
  654. "A3_L": new PageFormat(420, 297, "A3_L"), // id strings should use underscores instead of white spaces to facilitate use as URL parameters.
  655. "A3_P": new PageFormat(297, 420, "A3_P"),
  656. "A4_L": new PageFormat(297, 210, "A4_L"),
  657. "A4_P": new PageFormat(210, 297, "A4_P"),
  658. "A5_L": new PageFormat(210, 148, "A5_L"),
  659. "A5_P": new PageFormat(148, 210, "A5_P"),
  660. "A6_L": new PageFormat(148, 105, "A6_L"),
  661. "A6_P": new PageFormat(105, 148, "A6_P"),
  662. "Endless": PageFormat.UndefinedPageFormat,
  663. "Letter_L": new PageFormat(279.4, 215.9, "Letter_L"),
  664. "Letter_P": new PageFormat(215.9, 279.4, "Letter_P")
  665. };
  666. public static StringToPageFormat(pageFormatString: string): PageFormat {
  667. let pageFormat: PageFormat = PageFormat.UndefinedPageFormat; // default: 'endless' page height, take canvas/container width
  668. // check for widthxheight parameter, e.g. "800x600"
  669. if (pageFormatString.match("^[0-9]+x[0-9]+$")) {
  670. const widthAndHeight: string[] = pageFormatString.split("x");
  671. const width: number = Number.parseInt(widthAndHeight[0], 10);
  672. const height: number = Number.parseInt(widthAndHeight[1], 10);
  673. if (width > 0 && width < 32768 && height > 0 && height < 32768) {
  674. pageFormat = new PageFormat(width, height, `customPageFormat${pageFormatString}`);
  675. }
  676. }
  677. // check for formatId from OpenSheetMusicDisplay.PageFormatStandards
  678. pageFormatString = pageFormatString.replace(" ", "_");
  679. pageFormatString = pageFormatString.replace("Landscape", "L");
  680. pageFormatString = pageFormatString.replace("Portrait", "P");
  681. //console.log("change format to: " + formatId);
  682. if (OpenSheetMusicDisplay.PageFormatStandards.hasOwnProperty(pageFormatString)) {
  683. pageFormat = OpenSheetMusicDisplay.PageFormatStandards[pageFormatString];
  684. return pageFormat;
  685. }
  686. return pageFormat;
  687. }
  688. /** Sets page format by string. Alternative to setOptions({pageFormat: PageFormatStandards.Endless}) for example. */
  689. public setPageFormat(formatId: string): void {
  690. const newPageFormat: PageFormat = OpenSheetMusicDisplay.StringToPageFormat(formatId);
  691. this.needBackendUpdate = !(newPageFormat.Equals(this.rules.PageFormat));
  692. this.rules.PageFormat = newPageFormat;
  693. }
  694. public setCustomPageFormat(width: number, height: number): void {
  695. if (width > 0 && height > 0) {
  696. const f: PageFormat = new PageFormat(width, height);
  697. this.rules.PageFormat = f;
  698. }
  699. }
  700. /**
  701. * Creates a Pdf of the currently rendered MusicXML
  702. * @param pdfName if no name is given, the composer and title of the piece will be used
  703. */
  704. public createPdf(pdfName: string = undefined): void {
  705. if (this.backendType !== BackendType.SVG) {
  706. console.log("[OSMD] osmd.createPdf(): Warning: createPDF is only supported for SVG background for now, not for Canvas." +
  707. " Please use osmd.setOptions({backendType: SVG}).");
  708. return;
  709. }
  710. if (pdfName === undefined) {
  711. pdfName = this.sheet.FullNameString + ".pdf";
  712. }
  713. const backends: VexFlowBackend[] = this.drawer.Backends;
  714. let svgElement: SVGElement = (<SvgVexFlowBackend>backends[0]).getSvgElement();
  715. let pageWidth: number = 210;
  716. let pageHeight: number = 297;
  717. const engravingRulesPageFormat: PageFormat = this.rules.PageFormat;
  718. if (engravingRulesPageFormat && !engravingRulesPageFormat.IsUndefined) {
  719. pageWidth = engravingRulesPageFormat.width;
  720. pageHeight = engravingRulesPageFormat.height;
  721. } else {
  722. pageHeight = pageWidth * svgElement.clientHeight / svgElement.clientWidth;
  723. }
  724. const orientation: string = pageHeight > pageWidth ? "p" : "l";
  725. // create a new jsPDF instance
  726. const pdf: any = new jspdf(orientation, "mm", [pageWidth, pageHeight]);
  727. const scale: number = pageWidth / svgElement.clientWidth;
  728. for (let idx: number = 0, len: number = backends.length; idx < len; ++idx) {
  729. if (idx > 0) {
  730. pdf.addPage();
  731. }
  732. svgElement = (<SvgVexFlowBackend>backends[idx]).getSvgElement();
  733. // render the svg element
  734. svg2pdf(svgElement, pdf, {
  735. scale: scale,
  736. xOffset: 0,
  737. yOffset: 0
  738. });
  739. }
  740. // simply save the created pdf
  741. pdf.save(pdfName);
  742. }
  743. //#region GETTER / SETTER
  744. public set DrawSkyLine(value: boolean) {
  745. this.drawSkyLine = value;
  746. if (this.drawer) {
  747. this.drawer.skyLineVisible = value;
  748. this.render();
  749. }
  750. }
  751. public get DrawSkyLine(): boolean {
  752. return this.drawer.skyLineVisible;
  753. }
  754. public set DrawBottomLine(value: boolean) {
  755. this.drawBottomLine = value;
  756. if (this.drawer) {
  757. this.drawer.bottomLineVisible = value;
  758. this.render();
  759. }
  760. }
  761. public get DrawBottomLine(): boolean {
  762. return this.drawer.bottomLineVisible;
  763. }
  764. public set DrawBoundingBox(value: string) {
  765. this.drawBoundingBox = value;
  766. this.drawer.drawableBoundingBoxElement = value; // drawer is sometimes created anew, losing this value, so it's saved in OSMD now.
  767. this.render(); // may create new Drawer.
  768. }
  769. public get DrawBoundingBox(): string {
  770. return this.drawBoundingBox;
  771. }
  772. public get AutoResizeEnabled(): boolean {
  773. return this.autoResizeEnabled;
  774. }
  775. public set AutoResizeEnabled(value: boolean) {
  776. this.autoResizeEnabled = value;
  777. }
  778. public set Zoom(value: number) {
  779. this.zoom = value;
  780. this.zoomUpdated = true;
  781. (this.graphic.GetCalculator as VexFlowMusicSheetCalculator).beamsNeedUpdate = this.zoomUpdated;
  782. }
  783. public set FollowCursor(value: boolean) {
  784. this.followCursor = value;
  785. }
  786. public get FollowCursor(): boolean {
  787. return this.followCursor;
  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. }