12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139 |
- import { IXmlElement } from "./../Common/FileIO/Xml";
- import { VexFlowMusicSheetCalculator } from "./../MusicalScore/Graphical/VexFlow/VexFlowMusicSheetCalculator";
- import { VexFlowBackend } from "./../MusicalScore/Graphical/VexFlow/VexFlowBackend";
- import { MusicSheetReader } from "./../MusicalScore/ScoreIO/MusicSheetReader";
- import { GraphicalMusicSheet } from "./../MusicalScore/Graphical/GraphicalMusicSheet";
- import { MusicSheetCalculator } from "./../MusicalScore/Graphical/MusicSheetCalculator";
- import { VexFlowMusicSheetDrawer } from "./../MusicalScore/Graphical/VexFlow/VexFlowMusicSheetDrawer";
- import { SvgVexFlowBackend } from "./../MusicalScore/Graphical/VexFlow/SvgVexFlowBackend";
- import { CanvasVexFlowBackend } from "./../MusicalScore/Graphical/VexFlow/CanvasVexFlowBackend";
- import { MusicSheet } from "./../MusicalScore/MusicSheet";
- import { Cursor } from "./Cursor";
- import { MXLHelper } from "../Common/FileIO/Mxl";
- import { AJAX } from "./AJAX";
- import log from "loglevel";
- import { DrawingParameters } from "../MusicalScore/Graphical/DrawingParameters";
- import { DrawingParametersEnum } from "../Common/Enums/DrawingParametersEnum";
- import { ColoringModes } from "../Common/Enums/ColoringModes";
- import { IOSMDOptions, OSMDOptions, AutoBeamOptions, BackendType, CursorOptions } from "./OSMDOptions";
- import { EngravingRules, PageFormat } from "../MusicalScore/Graphical/EngravingRules";
- import { AbstractExpression } from "../MusicalScore/VoiceData/Expressions/AbstractExpression";
- import { Dictionary } from "typescript-collections";
- import { AutoColorSet } from "../MusicalScore/Graphical/DrawingEnums";
- import { GraphicalMusicPage } from "../MusicalScore/Graphical/GraphicalMusicPage";
- import { MusicPartManagerIterator } from "../MusicalScore/MusicParts/MusicPartManagerIterator";
- import { ITransposeCalculator } from "../MusicalScore/Interfaces/ITransposeCalculator";
- import { NoteEnum } from "../Common/DataObjects/Pitch";
- import { PlaybackNoteGenerator } from "../MusicalScore/Playback/PlaybackNoteGenerator";
- import { SheetRenderingManager } from "../Display/SheetRenderingManager";
- import { WebSheetRenderingManager } from "../Display/WebSheetRenderingManager";
- import { WebDisplayInteractionManager } from "../Display/WebDisplayInteractionManager";
- import { AbstractDisplayInteractionManager } from "../Display/AbstractDisplayInteractionManager";
- import { PlaybackManager } from "../Playback";
- import { DynamicsCalculator } from "../MusicalScore/ScoreIO/MusicSymbolModules/DynamicsCalculator";
- export class OpenSheetMusicDisplay {
- private version: string = "1.8.6-audio-extended";
-
-
- constructor(container: string | HTMLElement,
- options: IOSMDOptions = OSMDOptions.OSMDOptionsStandard(),
- rules: EngravingRules = new EngravingRules()) {
- this.rules = rules;
-
- if (typeof container === "string") {
-
- this.container = document.getElementById(<string>container);
- } else if (container && "appendChild" in <any>container) {
-
- this.container = <HTMLElement>container;
- }
- if (!this.container) {
- throw new Error("Please pass a valid div container to OpenSheetMusicDisplay");
- }
- if (options.autoResize === undefined) {
- options.autoResize = true;
- }
- this.backendType = BackendType.SVG;
- this.setOptions(options);
- this.interactionManager = new WebDisplayInteractionManager(this.container);
- this.renderingManager = new WebSheetRenderingManager(this.interactionManager, this.rules);
- }
- private cursorsOptions: CursorOptions[] = [];
- public cursors: Cursor[] = [];
- public get cursor(): Cursor {
- return this.cursors[0];
- }
- public zoom: number = 1.0;
- protected zoomUpdated: boolean = false;
-
- public loadUrlTimeout: number = 5000;
- protected container: HTMLElement;
- protected backendType: BackendType;
- protected needBackendUpdate: boolean;
- protected sheet: MusicSheet;
- protected drawer: VexFlowMusicSheetDrawer;
- protected drawBoundingBox: string;
- protected drawSkyLine: boolean;
- protected drawBottomLine: boolean;
- protected graphic: GraphicalMusicSheet;
- protected renderingManager: SheetRenderingManager;
- protected interactionManager: AbstractDisplayInteractionManager;
- protected drawingParameters: DrawingParameters;
- protected rules: EngravingRules;
- protected autoResizeEnabled: boolean;
- private resizeHandlerAttached: boolean;
- private disposeResizeListener: Function;
- protected followCursor: boolean;
- protected OnXMLRead: Function;
- public get RenderingManager(): SheetRenderingManager {
- return this.renderingManager;
- }
- public set PlaybackManager(manager: PlaybackManager) {
- if (this.renderingManager) {
- this.renderingManager.PlaybackManager = manager;
- }
- }
- public get PlaybackManager(): PlaybackManager {
- return this.renderingManager?.PlaybackManager;
- }
- private isUrl (url: string): boolean {
- if (url.length < 2083) {
- return true;
-
- } else {
- return false;
- }
- }
- private isMxl (data: string): boolean {
- if (data.substr(0, 4) === "\x50\x4b\x03\x04") {
- return true;
- }
- return false;
- }
- private processMxl (data: string, resolveContentPromise: (value?: Document) => void, rejectContentPromise: (reason?: any) => void): void {
- MXLHelper.MXLtoXMLstring(data).then(
- (x: string) => {
- resolveContentPromise(this.processStringXml(x));
- },
- (err: any) => {
- log.error(new Error("[OSMD] Invalid MXL file: " + err));
- rejectContentPromise(new Error("[OSMD] Invalid MXL file: " + err));
- }
- );
- }
- private processStringXml (xmlString: string): Document {
- const parser: DOMParser = new DOMParser();
-
- if (xmlString.substr(0, 3) === "\uf7ef\uf7bb\uf7bf") {
- log.debug("[OSMD] UTF with BOM detected, truncate first three bytes and pass along: " + xmlString);
-
- return parser.parseFromString(xmlString.substr(3), "application/xml");
- }
- if (xmlString.substr(0, 6).includes("<?xml")) {
- const modifiedXml: string = this.OnXMLRead(xmlString);
- log.debug("[OSMD] Finally parsing XML content, length: " + modifiedXml.length);
-
- return parser.parseFromString(modifiedXml, "application/xml");
- }
- }
-
- public load(content: string | Document, tempTitle: string = "Untitled Score"): Promise<{}> {
-
- this.reset();
- const self: OpenSheetMusicDisplay = this;
- const loadPromise: Promise<any> = new Promise(
- function(mainResolve: (value?: any) => void, mainReject: (reason?: any) => void): void {
- const contentPromise: Promise<Document> = new Promise<Document>(
- function(resolveContentPromise: (value?: Document) => void, rejectContentPromise: (reason?: any) => void): void {
-
- if (typeof content === "string") {
- const str: string = <string>content.trim();
- if (self.isMxl(str)) {
- log.debug("[OSMD] This is a zip file, unpack it first: " + str);
-
- self.processMxl(str, resolveContentPromise, rejectContentPromise);
- } else {
- const processedXmlDoc: Document = self.processStringXml(str);
- if (processedXmlDoc) {
- resolveContentPromise(processedXmlDoc);
- } else if (self.isUrl(str)) {
- AJAX.ajax(str).then(
- (s: string) => {
- if (self.isMxl(s)) {
- self.processMxl(s, resolveContentPromise, rejectContentPromise);
- } else {
- resolveContentPromise(self.processStringXml(s));
- }
- },
- (exc: Error) => { rejectContentPromise(exc); throw exc; }
- );
- } else {
- const err: Error = new Error("[OSMD] osmd.load(string): Could not process string. Did not find <?xml at beginning.");
- console.error(err.message);
- rejectContentPromise(err);
- }
- }
- } else if (content instanceof Document) {
- resolveContentPromise(content);
- } else {
- const err: Error = new Error("[OSMD] osmd.load(): content is not string or Document. Could not load.");
- console.error(err.message);
- rejectContentPromise(err);
- }
- });
- contentPromise.then(function(musicXML: Document): void {
- if (!musicXML || !(<any>musicXML).nodeName) {
- mainReject(new Error("OpenSheetMusicDisplay: The document which was provided is invalid"));
- }
- const xmlDocumentNodes: NodeList = musicXML.childNodes;
- log.debug("[OSMD] load(), Document url: " + musicXML.URL);
- let scorePartwiseElement: Element;
- for (let i: number = 0, length: number = xmlDocumentNodes.length; i < length; i += 1) {
- const node: Node = xmlDocumentNodes[i];
- if (node.nodeType === Node.ELEMENT_NODE && node.nodeName.toLowerCase() === "score-partwise") {
- scorePartwiseElement = <Element>node;
- break;
- }
- }
- if (!scorePartwiseElement) {
- console.error("Could not parse MusicXML, no valid partwise element found");
- mainReject(new Error("OpenSheetMusicDisplay: Document is not a valid 'partwise' MusicXML"));
- }
- const score: IXmlElement = new IXmlElement(scorePartwiseElement);
- const dynamicsGenerator: DynamicsCalculator = new DynamicsCalculator();
- const playbackNoteGen: PlaybackNoteGenerator = new PlaybackNoteGenerator();
- const reader: MusicSheetReader = new MusicSheetReader([dynamicsGenerator, playbackNoteGen], self.rules);
- self.sheet = reader.createMusicSheet(score, "Untitled Score");
- if (self.sheet === undefined) {
-
- mainReject(new Error("given music sheet was incomplete or could not be loaded."));
- }
-
-
-
- log.info(`[OSMD] Loaded sheet ${self.sheet.TitleString} successfully.`);
-
- self.needBackendUpdate = true;
- self.updateGraphic();
- mainResolve();
- }).catch(function(reason: any): void {
- log.debug("Content XML Promise was rejected");
- mainReject(reason);
- });
- });
- return loadPromise;
- }
-
- public updateGraphic(): void {
- const calc: MusicSheetCalculator = new VexFlowMusicSheetCalculator(this.rules);
- this.graphic = new GraphicalMusicSheet(this.sheet, calc);
- if (this.drawingParameters.drawCursors) {
- this.cursors.forEach(cursor => {
- cursor.init(this.sheet.MusicPartManager, this.graphic);
- });
- }
- if (this.drawingParameters.DrawingParametersEnum === DrawingParametersEnum.leadsheet) {
- this.graphic.LeadSheet = true;
- }
- this.renderingManager.setMusicSheet(this.graphic);
- this.interactionManager.Initialize();
- }
-
- public render(): void {
- if (!this.graphic) {
- throw new Error("OpenSheetMusicDisplay: Before rendering a music sheet, please load a MusicXML file");
- }
- this.drawer?.clear();
-
-
-
- let width: number = this.container.offsetWidth;
- if (this.rules.RenderSingleHorizontalStaffline) {
- width = this.rules.SheetMaximumWidth;
-
-
-
- }
-
- this.sheet.pageWidth = width / this.zoom / 10.0;
- this.renderingManager.MainViewingRegion.WidthInUnits = this.sheet.pageWidth;
- if (this.rules.PageFormat && !this.rules.PageFormat.IsUndefined) {
- this.rules.PageHeight = this.sheet.pageWidth / this.rules.PageFormat.aspectRatio;
- log.debug("[OSMD] PageHeight: " + this.rules.PageHeight);
- } else {
- log.debug("[OSMD] endless/undefined pageformat, id: " + this.rules.PageFormat.idString);
- this.rules.PageHeight = 100001;
- }
-
-
-
-
-
-
- this.graphic.reCalculate();
- if (this.drawingParameters.drawCursors) {
- this.graphic.Cursors.length = 0;
- }
-
-
-
- if (true || this.needBackendUpdate) {
- this.createOrRefreshRenderBackend();
- this.needBackendUpdate = false;
- }
- this.drawer.setZoom(this.zoom);
- for (const measure of this.sheet.SourceMeasures) {
- measure.WasRendered = false;
- }
-
- this.drawer.drawSheet(this.graphic);
- this.enableOrDisableCursors(this.drawingParameters.drawCursors);
- if (this.drawingParameters.drawCursors) {
-
- this.cursors.forEach(cursor => {
- cursor.update();
- });
- }
- this.zoomUpdated = false;
-
- this.interactionManager.displaySizeChanged(this.container.clientWidth, this.container.clientHeight);
- this.rules.RenderCount++;
-
- }
- protected createOrRefreshRenderBackend(): void {
-
-
- if (this.drawer && this.drawer.Backends) {
-
-
-
-
- if (this.drawer.Backends[0]) {
- this.drawer.Backends[0].removeAllChildrenFromContainer(this.container);
- }
- for (const backend of this.drawer.Backends) {
- backend.free();
- }
- this.drawer.Backends.clear();
- }
-
- this.drawingParameters.Rules = this.rules;
- this.drawer = new VexFlowMusicSheetDrawer(this.drawingParameters);
- this.drawer.drawableBoundingBoxElement = this.DrawBoundingBox;
- this.drawer.bottomLineVisible = this.drawBottomLine;
- this.drawer.skyLineVisible = this.drawSkyLine;
-
- let width: number = this.container.offsetWidth;
- if (this.rules.RenderSingleHorizontalStaffline) {
- width = (this.EngravingRules.PageLeftMargin + this.graphic.MusicPages[0].PositionAndShape.Size.width + this.EngravingRules.PageRightMargin)
- * 10 * this.zoom;
-
-
- }
-
- let height: number;
- const canvasDimensionsLimit: number = 32767;
-
-
-
- for (const page of this.graphic.MusicPages) {
- if (page.PageNumber > this.rules.MaxPageToDrawNumber) {
- break;
- }
- const backend: VexFlowBackend = this.createBackend(this.backendType, page);
- const sizeWarningPartTwo: string = " exceeds CanvasBackend limit of 32767. Cutting off score.";
- if (backend.getOSMDBackendType() === BackendType.Canvas && width > canvasDimensionsLimit) {
- log.warn("[OSMD] Warning: width of " + width + sizeWarningPartTwo);
- width = canvasDimensionsLimit;
- }
- if (this.rules.PageFormat && !this.rules.PageFormat.IsUndefined) {
- height = width / this.rules.PageFormat.aspectRatio;
-
- } else {
- height = page.PositionAndShape.Size.height;
- height += this.rules.PageBottomMargin;
- if (backend.getOSMDBackendType() === BackendType.Canvas) {
- height += 0.1;
-
- }
-
-
- height += page.PositionAndShape.BorderTop;
-
-
-
-
- if (this.rules.RenderTitle) {
- height += this.rules.TitleTopDistance;
- }
- height *= this.zoom * 10.0;
-
- }
- if (backend.getOSMDBackendType() === BackendType.Canvas && height > canvasDimensionsLimit) {
- log.warn("[OSMD] Warning: height of " + height + sizeWarningPartTwo);
- height = Math.min(height, canvasDimensionsLimit);
-
- }
- backend.resize(width, height);
- backend.clear();
- backend.getContext().setFillStyle(this.rules.DefaultColorMusic);
- backend.getContext().setStrokeStyle(this.rules.DefaultColorMusic);
- this.drawer.Backends.push(backend);
- this.graphic.drawer = this.drawer;
- }
- }
-
- public exportSVG(): void {
- for (const backend of this.drawer?.Backends) {
- if (backend instanceof SvgVexFlowBackend) {
- (backend as SvgVexFlowBackend).export();
- }
-
- }
- }
-
- public IsReadyToRender(): boolean {
- return this.graphic !== undefined;
- }
-
- public clear(): void {
- this.drawer?.clear();
- this.reset();
- }
-
- public dispose(): void {
- if (this.disposeResizeListener) {
- this.disposeResizeListener();
- }
- if (this.InteractionManager) {
- this.InteractionManager.Dispose();
- }
- }
-
- public setOptions(options: IOSMDOptions): void {
- if (!this.rules) {
- this.rules = new EngravingRules();
- }
- if (!this.drawingParameters && !options.drawingParameters) {
- this.drawingParameters = new DrawingParameters(DrawingParametersEnum.default, this.rules);
-
- } else if (options.drawingParameters) {
- if (!this.drawingParameters) {
- this.drawingParameters = new DrawingParameters(DrawingParametersEnum[options.drawingParameters], this.rules);
- } else {
- this.drawingParameters.DrawingParametersEnum =
- (<any>DrawingParametersEnum)[options.drawingParameters.toLowerCase()];
-
- }
- }
- if (options === undefined || options === null) {
- log.warn("warning: osmd.setOptions() called without an options parameter, has no effect."
- + "\n" + "example usage: osmd.setOptions({drawCredits: false, drawPartNames: false})");
- return;
- }
- this.OnXMLRead = function(xml): string {return xml;};
- if (options.onXMLRead) {
- this.OnXMLRead = options.onXMLRead;
- }
- const backendNotInitialized: boolean = !this.drawer || !this.drawer.Backends || this.drawer.Backends.length < 1;
- let needBackendUpdate: boolean = backendNotInitialized;
- if (options.backend !== undefined) {
- const backendTypeGiven: BackendType = OSMDOptions.BackendTypeFromString(options.backend);
- needBackendUpdate = needBackendUpdate || this.backendType !== backendTypeGiven;
- this.backendType = backendTypeGiven;
- }
- this.needBackendUpdate = needBackendUpdate;
-
-
- if (options.autoBeam !== undefined) {
- this.rules.AutoBeamNotes = options.autoBeam;
- }
- const autoBeamOptions: AutoBeamOptions = options.autoBeamOptions;
- if (autoBeamOptions) {
- if (autoBeamOptions.maintain_stem_directions === undefined) {
- autoBeamOptions.maintain_stem_directions = false;
- }
- this.rules.AutoBeamOptions = autoBeamOptions;
- if (autoBeamOptions.groups && autoBeamOptions.groups.length) {
- for (const fraction of autoBeamOptions.groups) {
- if (fraction.length !== 2) {
- throw new Error("Each fraction in autoBeamOptions.groups must be of length 2, e.g. [3,4] for beaming three fourths");
- }
- }
- }
- }
- if (options.percussionOneLineCutoff !== undefined) {
- this.rules.PercussionOneLineCutoff = options.percussionOneLineCutoff;
- }
- if (this.rules.PercussionOneLineCutoff !== 0 &&
- options.percussionForceVoicesOneLineCutoff !== undefined) {
- this.rules.PercussionForceVoicesOneLineCutoff = options.percussionForceVoicesOneLineCutoff;
- }
- if (options.alignRests !== undefined) {
- this.rules.AlignRests = options.alignRests;
- }
- if (options.coloringMode !== undefined) {
- this.setColoringMode(options);
- }
- if (options.coloringEnabled !== undefined) {
- this.rules.ColoringEnabled = options.coloringEnabled;
- }
- if (options.colorStemsLikeNoteheads !== undefined) {
- this.rules.ColorStemsLikeNoteheads = options.colorStemsLikeNoteheads;
- }
- if (options.disableCursor) {
- this.drawingParameters.drawCursors = false;
- }
-
-
- if (options.drawHiddenNotes) {
- this.drawingParameters.drawHiddenNotes = true;
- }
- if (options.drawCredits !== undefined) {
- this.drawingParameters.DrawCredits = options.drawCredits;
- }
- if (options.drawComposer !== undefined) {
- this.drawingParameters.DrawComposer = options.drawComposer;
- }
- if (options.drawTitle !== undefined) {
- this.drawingParameters.DrawTitle = options.drawTitle;
- }
- if (options.drawSubtitle !== undefined) {
- this.drawingParameters.DrawSubtitle = options.drawSubtitle;
- }
- if (options.drawLyricist !== undefined) {
- this.drawingParameters.DrawLyricist = options.drawLyricist;
- }
- if (options.drawMetronomeMarks !== undefined) {
- this.rules.MetronomeMarksDrawn = options.drawMetronomeMarks;
- }
- if (options.drawPartNames !== undefined) {
- this.drawingParameters.DrawPartNames = options.drawPartNames;
-
- if (!options.drawPartAbbreviations) {
- this.rules.RenderPartAbbreviations = options.drawPartNames;
- }
- }
- if (options.drawPartAbbreviations !== undefined) {
- this.rules.RenderPartAbbreviations = options.drawPartAbbreviations;
- }
- if (options.drawFingerings === false) {
- this.rules.RenderFingerings = false;
- }
- if (options.drawMeasureNumbers !== undefined) {
- this.rules.RenderMeasureNumbers = options.drawMeasureNumbers;
- }
- if (options.drawMeasureNumbersOnlyAtSystemStart) {
- this.rules.RenderMeasureNumbersOnlyAtSystemStart = options.drawMeasureNumbersOnlyAtSystemStart;
- }
- if (options.drawLyrics !== undefined) {
- this.rules.RenderLyrics = options.drawLyrics;
- }
- if (options.drawTimeSignatures !== undefined) {
- this.rules.RenderTimeSignatures = options.drawTimeSignatures;
- }
- if (options.drawSlurs !== undefined) {
- this.rules.RenderSlurs = options.drawSlurs;
- }
- if (options.measureNumberInterval !== undefined) {
- this.rules.MeasureNumberLabelOffset = options.measureNumberInterval;
- }
- if (options.useXMLMeasureNumbers !== undefined) {
- this.rules.UseXMLMeasureNumbers = options.useXMLMeasureNumbers;
- }
- if (options.fingeringPosition !== undefined) {
- this.rules.FingeringPosition = AbstractExpression.PlacementEnumFromString(options.fingeringPosition);
- }
- if (options.fingeringInsideStafflines !== undefined) {
- this.rules.FingeringInsideStafflines = options.fingeringInsideStafflines;
- }
- if (options.newSystemFromXML !== undefined) {
- this.rules.NewSystemAtXMLNewSystemAttribute = options.newSystemFromXML;
- }
- if (options.newSystemFromNewPageInXML !== undefined) {
- this.rules.NewSystemAtXMLNewPageAttribute = options.newSystemFromNewPageInXML;
- }
- if (options.newPageFromXML !== undefined) {
- this.rules.NewPageAtXMLNewPageAttribute = options.newPageFromXML;
- }
- if (options.fillEmptyMeasuresWithWholeRest !== undefined) {
- this.rules.FillEmptyMeasuresWithWholeRest = options.fillEmptyMeasuresWithWholeRest;
- }
- if (options.followCursor !== undefined) {
- this.FollowCursor = options.followCursor;
- }
- if (options.setWantedStemDirectionByXml !== undefined) {
- this.rules.SetWantedStemDirectionByXml = options.setWantedStemDirectionByXml;
- }
- if (options.darkMode) {
- this.rules.applyDefaultColorMusic("#FFFFFF");
- this.rules.PageBackgroundColor = "#000000";
- } else if (options.darkMode === false) {
- this.rules.applyDefaultColorMusic("#000000");
- this.rules.PageBackgroundColor = undefined;
- }
- if (options.defaultColorMusic) {
- this.rules.applyDefaultColorMusic(options.defaultColorMusic);
- }
- if (options.defaultColorNotehead) {
- this.rules.DefaultColorNotehead = options.defaultColorNotehead;
- }
- if (options.defaultColorRest) {
- this.rules.DefaultColorRest = options.defaultColorRest;
- }
- if (options.defaultColorStem) {
- this.rules.DefaultColorStem = options.defaultColorStem;
- }
- if (options.defaultColorLabel) {
- this.rules.DefaultColorLabel = options.defaultColorLabel;
- }
- if (options.defaultColorTitle) {
- this.rules.DefaultColorTitle = options.defaultColorTitle;
- }
- if (options.defaultFontFamily) {
- this.rules.DefaultFontFamily = options.defaultFontFamily;
- }
- if (options.defaultFontStyle) {
- this.rules.DefaultFontStyle = options.defaultFontStyle;
- }
- if (options.drawUpToMeasureNumber) {
- this.rules.MaxMeasureToDrawIndex = options.drawUpToMeasureNumber - 1;
- }
- if (options.drawFromMeasureNumber) {
- this.rules.MinMeasureToDrawIndex = options.drawFromMeasureNumber - 1;
- }
- if (options.drawUpToPageNumber) {
- this.rules.MaxPageToDrawNumber = options.drawUpToPageNumber;
- }
- if (options.drawUpToSystemNumber) {
- this.rules.MaxSystemToDrawNumber = options.drawUpToSystemNumber;
- }
- if (options.tupletsRatioed) {
- this.rules.TupletsRatioed = true;
- }
- if (options.tupletsBracketed) {
- this.rules.TupletsBracketed = true;
- }
- if (options.tripletsBracketed) {
- this.rules.TripletsBracketed = true;
- }
- if (options.autoResize) {
- if (!this.resizeHandlerAttached) {
- this.autoResize();
- }
- this.autoResizeEnabled = true;
- } else if (options.autoResize === false) {
- this.autoResizeEnabled = false;
-
- }
- if (options.pageFormat !== undefined) {
- this.setPageFormat(options.pageFormat);
- }
- if (options.pageBackgroundColor !== undefined) {
- this.rules.PageBackgroundColor = options.pageBackgroundColor;
- }
- if (options.performanceMode !== undefined) {
- this.rules.PerformanceMode = options.performanceMode;
- }
- if (options.renderSingleHorizontalStaffline !== undefined) {
- this.rules.RenderSingleHorizontalStaffline = options.renderSingleHorizontalStaffline;
- }
- if (options.spacingFactorSoftmax !== undefined) {
- this.rules.SoftmaxFactorVexFlow = options.spacingFactorSoftmax;
- }
- if (options.spacingBetweenTextLines !== undefined) {
- this.rules.SpacingBetweenTextLines = options.spacingBetweenTextLines;
- }
- if (options.stretchLastSystemLine !== undefined) {
- this.rules.StretchLastSystemLine = options.stretchLastSystemLine;
- }
- if (options.autoGenerateMultipleRestMeasuresFromRestMeasures !== undefined) {
- this.rules.AutoGenerateMultipleRestMeasuresFromRestMeasures = options.autoGenerateMultipleRestMeasuresFromRestMeasures;
- }
- if (options.cursorsOptions !== undefined) {
- this.cursorsOptions = options.cursorsOptions;
- } else {
- this.cursorsOptions = [{type: 0, color: this.EngravingRules.DefaultColorCursor, alpha: 0.5, follow: true}];
- }
- if (options.preferredSkyBottomLineBatchCalculatorBackend !== undefined) {
- this.rules.PreferredSkyBottomLineBatchCalculatorBackend = options.preferredSkyBottomLineBatchCalculatorBackend;
- }
- if (options.skyBottomLineBatchMinMeasures !== undefined) {
- this.rules.SkyBottomLineBatchMinMeasures = options.skyBottomLineBatchMinMeasures;
- }
- }
- public setColoringMode(options: IOSMDOptions): void {
- if (options.coloringMode === ColoringModes.XML) {
- this.rules.ColoringMode = ColoringModes.XML;
- return;
- }
- const noteIndices: NoteEnum[] = [NoteEnum.C, NoteEnum.D, NoteEnum.E, NoteEnum.F, NoteEnum.G, NoteEnum.A, NoteEnum.B];
- let colorSetString: string[];
- if (options.coloringMode === ColoringModes.CustomColorSet) {
- if (!options.coloringSetCustom || options.coloringSetCustom.length !== 8) {
- throw new Error("Invalid amount of colors: With coloringModes.customColorSet, " +
- "you have to provide a coloringSetCustom parameter (array) with 8 strings (C to B, rest note).");
- }
-
- for (const colorString of options.coloringSetCustom) {
- const regExp: RegExp = /^\#[0-9a-fA-F]{6}$/;
- if (!regExp.test(colorString)) {
- throw new Error(
- "One of the color strings in options.coloringSetCustom was not a valid HTML Hex color:\n" + colorString);
- }
- }
- colorSetString = options.coloringSetCustom;
- } else if (options.coloringMode === ColoringModes.AutoColoring) {
- colorSetString = [];
- const keys: string[] = Object.keys(AutoColorSet);
- for (let i: number = 0; i < keys.length; i++) {
- colorSetString.push(AutoColorSet[keys[i]]);
- }
- }
- const coloringSetCurrent: Dictionary<NoteEnum | number, string> = new Dictionary<NoteEnum | number, string>();
- for (let i: number = 0; i < noteIndices.length; i++) {
- coloringSetCurrent.setValue(noteIndices[i], colorSetString[i]);
- }
- coloringSetCurrent.setValue(-1, colorSetString.last());
- this.rules.ColoringSetCurrent = coloringSetCurrent;
- this.rules.ColoringMode = options.coloringMode;
- }
-
- public setLogLevel(level: string): void {
- switch (level) {
- case "trace":
- log.setLevel(log.levels.TRACE);
- break;
- case "debug":
- log.setLevel(log.levels.DEBUG);
- break;
- case "info":
- log.setLevel(log.levels.INFO);
- break;
- case "warn":
- log.setLevel(log.levels.WARN);
- break;
- case "error":
- log.setLevel(log.levels.ERROR);
- break;
- case "silent":
- log.setLevel(log.levels.SILENT);
- break;
- default:
- log.warn(`Could not set log level to ${level}. Using warn instead.`);
- log.setLevel(log.levels.WARN);
- break;
- }
- }
- public getLogLevel(): number {
- return log.getLevel();
- }
-
- protected reset(): void {
- if (this.drawingParameters.drawCursors) {
- this.cursors.forEach(cursor => {
- cursor.hide();
- });
- }
- this.sheet = undefined;
- this.graphic = undefined;
- this.zoom = 1.0;
- this.rules.RenderCount = 0;
- }
-
- protected autoResize(): void {
- const self: OpenSheetMusicDisplay = this;
- this.handleResize(
- () => {
-
- },
- () => {
-
-
-
-
-
-
-
-
-
-
-
- if (this.graphic?.GetCalculator instanceof VexFlowMusicSheetCalculator) {
- (this.graphic.GetCalculator as VexFlowMusicSheetCalculator).beamsNeedUpdate = true;
- }
- if (self.IsReadyToRender()) {
- self.render();
- }
- }
- );
- }
-
- protected handleResize(startCallback: () => void, endCallback: () => void): void {
- let rtime: number;
- let timeout: number = undefined;
- const delta: number = 200;
- const self: OpenSheetMusicDisplay = this;
- function resizeStart(): void {
- if (!self.AutoResizeEnabled) {
- return;
- }
- rtime = (new Date()).getTime();
- if (!timeout) {
- startCallback();
- rtime = (new Date()).getTime();
- timeout = window.setTimeout(resizeEnd, delta);
- }
- }
- function resizeEnd(): void {
- timeout = undefined;
- window.clearTimeout(timeout);
- if ((new Date()).getTime() - rtime < delta) {
- timeout = window.setTimeout(resizeEnd, delta);
- } else {
- endCallback();
- }
- }
- if ((<any>window).attachEvent) {
-
- (<any>window).attachEvent("onresize", resizeStart);
- } else {
- window.addEventListener("resize", resizeStart);
- }
- this.disposeResizeListener = (): void => {
- if ((<any>window).detachEvent) {
-
- (<any>window).detachEvent ("onresize", resizeStart);
- } else {
- window.removeEventListener("resize", resizeStart);
- }
- this.resizeHandlerAttached = false;
- };
- this.resizeHandlerAttached = true;
- window.setTimeout(startCallback, 0);
- window.setTimeout(endCallback, 1);
- }
-
- public enableOrDisableCursors(enable: boolean): void {
- this.drawingParameters.drawCursors = enable;
- if (enable) {
- for (let i: number = 0; i < this.cursorsOptions.length; i++){
-
- const hidden: boolean = this.cursors[i]?.Hidden ?? false;
- const previousIterator: MusicPartManagerIterator = this.cursors[i]?.Iterator;
- this.cursors[i]?.hide();
-
- let backendToDrawOn: VexFlowBackend = this.drawer?.Backends[0];
- if (backendToDrawOn && this.rules.RestoreCursorAfterRerender && this.cursors[i]) {
- const newPageNumber: number = this.cursors[i].updateCurrentPage();
- backendToDrawOn = this.drawer.Backends[newPageNumber - 1];
- }
-
- if (backendToDrawOn && backendToDrawOn.getRenderElement()) {
- if (this.cursors[i]) {
- this.PlaybackManager?.removeListener(this.cursors[i]);
- this.cursors[i].Dispose();
- }
- this.cursors[i] = new Cursor(backendToDrawOn.getRenderElement(), this, this.cursorsOptions[i]);
- }
- if (this.sheet && this.graphic && this.cursors[i]) {
- this.cursors[i].init(this.sheet.MusicPartManager, this.graphic);
- }
-
- if (this.rules.RestoreCursorAfterRerender) {
- if (previousIterator) {
- this.cursors[i].iterator = previousIterator;
-
- }
- if (hidden) {
- this.cursors[i].hide();
- } else {
- this.cursors[i].show();
- }
- }
- }
- this.renderingManager.PlaybackManager?.addListener(this.cursor);
- } else {
- this.cursors.forEach(cursor => {
- cursor.hide();
- });
-
-
-
- }
- }
- public createBackend(type: BackendType, page: GraphicalMusicPage): VexFlowBackend {
- let backend: VexFlowBackend;
- if (type === undefined || type === BackendType.SVG) {
- backend = new SvgVexFlowBackend(this.rules);
- } else {
- backend = new CanvasVexFlowBackend(this.rules);
- }
- backend.graphicalMusicPage = page;
- backend.initialize(this.container, this.zoom);
-
-
-
- return backend;
- }
-
- public static PageFormatStandards: { [type: string]: PageFormat } = {
- "A3_L": new PageFormat(420, 297, "A3_L"),
- "A3_P": new PageFormat(297, 420, "A3_P"),
- "A4_L": new PageFormat(297, 210, "A4_L"),
- "A4_P": new PageFormat(210, 297, "A4_P"),
- "A5_L": new PageFormat(210, 148, "A5_L"),
- "A5_P": new PageFormat(148, 210, "A5_P"),
- "A6_L": new PageFormat(148, 105, "A6_L"),
- "A6_P": new PageFormat(105, 148, "A6_P"),
- "Endless": PageFormat.UndefinedPageFormat,
- "Letter_L": new PageFormat(279.4, 215.9, "Letter_L"),
- "Letter_P": new PageFormat(215.9, 279.4, "Letter_P")
- };
- public static StringToPageFormat(pageFormatString: string): PageFormat {
- let pageFormat: PageFormat = PageFormat.UndefinedPageFormat;
-
- if (pageFormatString.match("^[0-9]+x[0-9]+$")) {
- const widthAndHeight: string[] = pageFormatString.split("x");
- const width: number = Number.parseInt(widthAndHeight[0], 10);
- const height: number = Number.parseInt(widthAndHeight[1], 10);
- if (width > 0 && width < 32768 && height > 0 && height < 32768) {
- pageFormat = new PageFormat(width, height, `customPageFormat${pageFormatString}`);
- }
- }
-
- pageFormatString = pageFormatString.replace(" ", "_");
- pageFormatString = pageFormatString.replace("Landscape", "L");
- pageFormatString = pageFormatString.replace("Portrait", "P");
-
- if (OpenSheetMusicDisplay.PageFormatStandards.hasOwnProperty(pageFormatString)) {
- pageFormat = OpenSheetMusicDisplay.PageFormatStandards[pageFormatString];
- return pageFormat;
- }
- return pageFormat;
- }
-
- public setPageFormat(formatId: string): void {
- const newPageFormat: PageFormat = OpenSheetMusicDisplay.StringToPageFormat(formatId);
- this.needBackendUpdate = !(newPageFormat.Equals(this.rules.PageFormat));
- this.rules.PageFormat = newPageFormat;
- }
- public setCustomPageFormat(width: number, height: number): void {
- if (width > 0 && height > 0) {
- const f: PageFormat = new PageFormat(width, height);
- this.rules.PageFormat = f;
- }
- }
-
- public set DrawSkyLine(value: boolean) {
- this.drawSkyLine = value;
- if (this.drawer) {
- this.drawer.skyLineVisible = value;
-
-
- }
- }
- public get DrawSkyLine(): boolean {
- return this.drawer.skyLineVisible;
- }
- public set DrawBottomLine(value: boolean) {
- this.drawBottomLine = value;
- if (this.drawer) {
- this.drawer.bottomLineVisible = value;
-
-
- }
- }
- public get DrawBottomLine(): boolean {
- return this.drawer.bottomLineVisible;
- }
- public set DrawBoundingBox(value: string) {
- this.setDrawBoundingBox(value, true);
- }
- public get DrawBoundingBox(): string {
- return this.drawBoundingBox;
- }
- public setDrawBoundingBox(value: string, render: boolean = false): void {
- this.drawBoundingBox = value;
- if (this.drawer) {
- this.drawer.drawableBoundingBoxElement = value;
- }
- if (render) {
- this.render();
- }
- }
- public get AutoResizeEnabled(): boolean {
- return this.autoResizeEnabled;
- }
- public set AutoResizeEnabled(value: boolean) {
- this.autoResizeEnabled = value;
- }
- public get Zoom(): number {
- return this.zoom;
- }
- public set Zoom(value: number) {
- this.zoom = value;
- this.zoomUpdated = true;
- if (this.graphic?.GetCalculator instanceof VexFlowMusicSheetCalculator) {
- (this.graphic.GetCalculator as VexFlowMusicSheetCalculator).beamsNeedUpdate = this.zoomUpdated;
- }
- }
- public set FollowCursor(value: boolean) {
- this.followCursor = value;
- }
- public get FollowCursor(): boolean {
- return this.followCursor;
- }
- public set TransposeCalculator(calculator: ITransposeCalculator) {
- MusicSheetCalculator.transposeCalculator = calculator;
- }
- public get TransposeCalculator(): ITransposeCalculator {
- return MusicSheetCalculator.transposeCalculator;
- }
- public get Sheet(): MusicSheet {
- return this.sheet;
- }
- public get Drawer(): VexFlowMusicSheetDrawer {
- return this.drawer;
- }
- public get GraphicSheet(): GraphicalMusicSheet {
- return this.graphic;
- }
- public get DrawingParameters(): DrawingParameters {
- return this.drawingParameters;
- }
- public get EngravingRules(): EngravingRules {
- return this.rules;
- }
- public get InteractionManager(): AbstractDisplayInteractionManager {
- return this.interactionManager;
- }
-
- public get Version(): string {
- return this.version;
- }
-
- }
|