var Al=Object.defineProperty,Il=Object.defineProperties;var kl=Object.getOwnPropertyDescriptors;var Bo=Object.getOwnPropertySymbols;var Bl=Object.prototype.hasOwnProperty,Dl=Object.prototype.propertyIsEnumerable;var Do=(n,t,e)=>t in n?Al(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,be=(n,t)=>{for(var e in t||(t={}))Bl.call(t,e)&&Do(n,e,t[e]);if(Bo)for(var e of Bo(t))Dl.call(t,e)&&Do(n,e,t[e]);return n},os=(n,t)=>Il(n,kl(t));import{aE as We,aR as Oi,aS as Fl}from"./base.d7a641ab.js";class Ol{static ajax(t,e=9e3){let i;const s=t.indexOf(".mxl")>-1?"text/plain; charset=x-user-defined":"application/xml";if(XMLHttpRequest)i=new XMLHttpRequest;else if(ActiveXObject)i=new ActiveXObject("Microsoft.XMLHTTP");else return Promise.reject(new Error("XMLHttp not supported."));return i.timeout=e,new Promise((r,o)=>{i.onreadystatechange=()=>{i.readyState===XMLHttpRequest.DONE&&(i.status===200||i.status===0&&i.responseText?r(i.responseText):o(new Error("Could not retrieve requested URL "+i.status)))},i.ontimeout=a=>{o(new Error("Server request Timeout"))},i.overrideMimeType(s),i.open("GET",t,!0),i.send()})}}const Fe=class{constructor(n=0,t=1,e=0,i=!0){this.numerator=0,this.denominator=1,this.wholeValue=0,this.numerator=n,this.denominator=t,this.wholeValue=e,i&&this.simplify(),this.setRealValue()}static max(n,t){return n.RealValue>t.RealValue?n:t}static Equal(n,t){return n.wholeValue===t.wholeValue&&n.Denominator===t.Denominator&&n.Numerator===t.Numerator}static createFromFraction(n){return new Fe(n.numerator,n.denominator,n.wholeValue,!1)}static plus(n,t){const e=n.clone();return e.Add(t),e}static minus(n,t){const e=n.clone();return e.Sub(t),e}static multiply(n,t){return new Fe((n.wholeValue*n.denominator+n.numerator)*(t.wholeValue*t.denominator+t.numerator),n.denominator*t.denominator)}static greatestCommonDenominator(n,t){if(n===0)return t;if(t===1)return 1;for(;Math.abs(t)>1e-8;)n>t?n-=t:t-=n;return Math.round(n)}toString(){let n=this.numerator+"/"+this.denominator;return this.wholeValue!==0&&(n=this.wholeValue+" "+n),n}clone(){return new Fe(this.numerator,this.denominator,this.wholeValue,!1)}get Numerator(){return this.numerator}set Numerator(n){this.numerator!==n&&(this.numerator=n,this.simplify(),this.setRealValue())}get Denominator(){return this.denominator}set Denominator(n){this.denominator!==n&&(this.denominator=n,this.numerator!==0&&this.simplify(),this.setRealValue())}get WholeValue(){return this.wholeValue}set WholeValue(n){this.wholeValue!==n&&(this.wholeValue=n,this.setRealValue())}GetExpandedNumerator(){return this.wholeValue*this.denominator+this.numerator}calculateNumberOfNeededDots(){let n=1,t=2;const e=this.GetExpandedNumerator();for(;tn;)t.Numerator++;if(this.numerator>this.denominator){const e=new Fe(this.numerator-1,this.denominator,this.wholeValue);for(;e.Denominator>n;)e.Numerator--;if(e.DenominatorFe.maximumAllowedNumber){const e=this.denominator/Fe.maximumAllowedNumber;this.numerator=Math.round(this.numerator/e),this.denominator=Math.round(this.denominator/e)}if(this.numerator>Fe.maximumAllowedNumber){const e=this.numerator/Fe.maximumAllowedNumber;this.numerator=Math.round(this.numerator/e),this.denominator=Math.round(this.denominator/e)}}isOnBeat(n){const t=this.distanceFromBeat(n);return Math.abs(t)(n[n.Above=0]="Above",n[n.Below=1]="Below",n[n.Left=2]="Left",n[n.Right=3]="Right",n[n.NotYetDefined=4]="NotYetDefined",n[n.AboveOrBelow=5]="AboveOrBelow",n))(z||{});const vi=class extends Ii{constructor(n,t,e,i,s,r,o=""){super(t),super.parentMeasure=i,this.NumberXml=r,this.dynamicType=n,this.label=o,this.staffNumber=e,this.activeInstantaneousDynamic=s,this.startVolume=1,this.endVolume=1,this.setStartAndEndVolume(),o!==""&&this.setType()}setStartAndEndVolume(){this.activeInstantaneousDynamic&&(this.dynamicType===Re.crescendo&&(this.startVolume=this.activeInstantaneousDynamic.Volume,this.endVolume=this.activeInstantaneousDynamic.Volume*1.2),this.dynamicType===Re.diminuendo&&(this.startVolume=this.activeInstantaneousDynamic.Volume,this.endVolume=this.activeInstantaneousDynamic.Volume*.8))}get DynamicType(){return this.dynamicType}set DynamicType(n){this.dynamicType=n}get StartMultiExpression(){return this.startMultiExpression}set StartMultiExpression(n){this.startMultiExpression=n}get EndMultiExpression(){return this.endMultiExpression}set EndMultiExpression(n){this.endMultiExpression=n}get Placement(){return this.placement}set Placement(n){this.placement=n}get StartVolume(){return this.startVolume}set StartVolume(n){this.startVolume=n}get EndVolume(){return this.endVolume}set EndVolume(n){this.endVolume=n}get StaffNumber(){return this.staffNumber}set StaffNumber(n){this.staffNumber=n}get Label(){return this.label}set Label(n){this.label=n,this.setType()}static isInputStringContinuousDynamic(n){return n?vi.isStringInStringList(vi.listContinuousDynamicIncreasing,n)||vi.isStringInStringList(vi.listContinuousDynamicDecreasing,n):!1}getInterpolatedDynamic(n){const t=this.StartMultiExpression.AbsoluteTimestamp;let e;if(this.EndMultiExpression?e=this.EndMultiExpression.AbsoluteTimestamp:e=W.plus(this.startMultiExpression.SourceMeasureParent.AbsoluteTimestamp,this.startMultiExpression.SourceMeasureParent.Duration),n.lt(t))return-1;if(e.lt(n))return-2;const i=W.minus(n,t).RealValue/W.minus(e,t).RealValue;return Math.max(0,Math.min(99.9,this.startVolume+(this.endVolume-this.startVolume)*i))}isWedge(){return!this.label}setType(){vi.isStringInStringList(vi.listContinuousDynamicIncreasing,this.label)?this.dynamicType=Re.crescendo:vi.isStringInStringList(vi.listContinuousDynamicDecreasing,this.label)&&(this.dynamicType=Re.diminuendo)}};let ei=vi;ei.listContinuousDynamicIncreasing=["crescendo","cresc","cresc.","cres."];ei.listContinuousDynamicDecreasing=["decrescendo","decresc","decr.","diminuendo","dim.","dim"];var Re=(n=>(n[n.crescendo=0]="crescendo",n[n.diminuendo=1]="diminuendo",n))(Re||{}),Ki=(n=>(n[n.p=0]="p",n[n.f=1]="f",n[n.s=2]="s",n[n.z=3]="z",n[n.m=4]="m",n[n.r=5]="r",n))(Ki||{});class Ee{constructor(t,e){this.message=t,e&&(this.message+=" "+e.toString())}}class Li{constructor(t){this.message=t}}class Vl{constructor(t){this.message=t}}var _a={exports:{}};(function(n){(function(t,e){n.exports?n.exports=e():t.log=e()})(We,function(){var t=function(){},e="undefined",i=typeof window!==e&&typeof window.navigator!==e&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"];function r(g,m){var S=g[m];if(typeof S.bind=="function")return S.bind(g);try{return Function.prototype.bind.call(S,g)}catch{return function(){return Function.prototype.apply.apply(S,[g,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function a(g){return g==="debug"&&(g="log"),typeof console===e?!1:g==="trace"&&i?o:console[g]!==void 0?r(console,g):console.log!==void 0?r(console,"log"):t}function l(g,m){for(var S=0;S=0&&P<=b.levels.SILENT){if(y=P,I!==!1&&w(P),l.call(b,P,g),typeof console===e&&P=0;r--)if(i(n[r],t))return r;return-1}ke.lastIndexOf=Gl;function Wl(n,t,e){return Zr(n,t,e)>=0}ke.contains=Wl;function Ul(n,t,e){var i=Zr(n,t,e);return i<0?!1:(n.splice(i,1),!0)}ke.remove=Ul;function zl(n,t,e){for(var i=e||Yn.defaultEquals,s=n.length,r=0,o=0;o=n.length||e<0||e>=n.length)return!1;var i=n[t];return n[t]=n[e],n[e]=i,!0}ke.swap=Yl;function jl(n){return"["+n.toString()+"]"}ke.toString=jl;function Kl(n,t){for(var e=0,i=n;et.size())return!1;var e=!0;return this.forEach(function(i){return t.contains(i)?!0:(e=!1,!1)}),e},n.prototype.remove=function(t){return this.contains(t)?(this.dictionary.remove(t),!0):!1},n.prototype.forEach=function(t){this.dictionary.forEach(function(e,i){return t(i)})},n.prototype.toArray=function(){return this.dictionary.values()},n.prototype.isEmpty=function(){return this.dictionary.isEmpty()},n.prototype.size=function(){return this.dictionary.size()},n.prototype.clear=function(){this.dictionary.clear()},n.prototype.toString=function(){return Ql.toString(this.toArray())},n}();jn.default=th;Object.defineProperty(Qr,"__esModule",{value:!0});var or=Ke,eh=zi,ih=jn,sh=function(){function n(t){this.toStrF=t||or.defaultToString,this.dictionary=new eh.default(this.toStrF),this.nElements=0}return n.prototype.add=function(t,e){if(e===void 0&&(e=1),or.isUndefined(t)||e<=0)return!1;if(this.contains(t))this.dictionary.getValue(t).copies+=e;else{var i={value:t,copies:e};this.dictionary.setValue(t,i)}return this.nElements+=e,!0},n.prototype.count=function(t){return this.contains(t)?this.dictionary.getValue(t).copies:0},n.prototype.contains=function(t){return this.dictionary.containsKey(t)},n.prototype.remove=function(t,e){if(e===void 0&&(e=1),or.isUndefined(t)||e<=0)return!1;if(this.contains(t)){var i=this.dictionary.getValue(t);return e>i.copies?this.nElements-=i.copies:this.nElements-=e,i.copies-=e,i.copies<=0&&this.dictionary.remove(t),!0}else return!1},n.prototype.toArray=function(){for(var t=[],e=this.dictionary.values(),i=0,s=e;ithis.nElements||Xi.isUndefined(t))return!1;var i=this.createNode(t);if(this.nElements===0||this.lastNode===null)this.firstNode=i,this.lastNode=i;else if(e===this.nElements)this.lastNode.next=i,this.lastNode=i;else if(e===0)i.next=this.firstNode,this.firstNode=i;else{var s=this.nodeAtIndex(e-1);if(s===null)return!1;i.next=s.next,s.next=i}return this.nElements++,!0},n.prototype.first=function(){if(this.firstNode!==null)return this.firstNode.element},n.prototype.last=function(){if(this.lastNode!==null)return this.lastNode.element},n.prototype.elementAtIndex=function(t){var e=this.nodeAtIndex(t);if(e!==null)return e.element},n.prototype.indexOf=function(t,e){var i=e||Xi.defaultEquals;if(Xi.isUndefined(t))return-1;for(var s=this.firstNode,r=0;s!==null;){if(i(s.element,t))return r;r++,s=s.next}return-1},n.prototype.contains=function(t,e){return this.indexOf(t,e)>=0},n.prototype.remove=function(t,e){var i=e||Xi.defaultEquals;if(this.nElements<1||Xi.isUndefined(t))return!1;for(var s=null,r=this.firstNode;r!==null;){if(i(r.element,t))return s===null?(this.firstNode=r.next,r===this.lastNode&&(this.lastNode=null)):r===this.lastNode?(this.lastNode=s,s.next=r.next,r.next=null):(s.next=r.next,r.next=null),this.nElements--,!0;s=r,r=r.next}return!1},n.prototype.clear=function(){this.firstNode=null,this.lastNode=null,this.nElements=0},n.prototype.equals=function(t,e){var i=e||Xi.defaultEquals;return!(t instanceof n)||this.size()!==t.size()?!1:this.equalsAux(this.firstNode,t.firstNode,i)},n.prototype.equalsAux=function(t,e,i){for(;t!==null&&e!==null;){if(!i(t.element,e.element))return!1;t=t.next,e=e.next}return!0},n.prototype.removeElementAtIndex=function(t){if(!(t<0||t>=this.nElements||this.firstNode===null||this.lastNode===null)){var e;if(this.nElements===1)e=this.firstNode.element,this.firstNode=null,this.lastNode=null;else{var i=this.nodeAtIndex(t-1);i===null?(e=this.firstNode.element,this.firstNode=this.firstNode.next):i.next===this.lastNode&&(e=this.lastNode.element,this.lastNode=i),i!==null&&i.next!==null&&(e=i.next.element,i.next=i.next.next)}return this.nElements--,e}},n.prototype.forEach=function(t){for(var e=this.firstNode;e!==null&&t(e.element)!==!1;)e=e.next},n.prototype.reverse=function(){for(var t=null,e=this.firstNode,i=null;e!==null;)i=e.next,e.next=t,t=e,e=i;i=this.firstNode,this.firstNode=this.lastNode,this.lastNode=i},n.prototype.toArray=function(){for(var t=[],e=this.firstNode;e!==null;)t.push(e.element),e=e.next;return t},n.prototype.size=function(){return this.nElements},n.prototype.isEmpty=function(){return this.nElements<=0},n.prototype.toString=function(){return nh.toString(this.toArray())},n.prototype.nodeAtIndex=function(t){if(t<0||t>=this.nElements)return null;if(t===this.nElements-1)return this.lastNode;for(var e=this.firstNode,i=0;i0&&(t=t.rightCh);return t},n.prototype.transplant=function(t,e){t.parent===null?this.root=e:t===t.parent.leftCh?t.parent.leftCh=e:t.parent.rightCh=e,e!==null&&(e.parent=t.parent)},n.prototype.removeNode=function(t){if(t.leftCh===null)this.transplant(t,t.rightCh);else if(t.rightCh===null)this.transplant(t,t.leftCh);else{var e=this.minimumAux(t.rightCh);e.parent!==t&&(this.transplant(e,e.rightCh),e.rightCh=t.rightCh,e.rightCh.parent=e),this.transplant(t,e),e.leftCh=t.leftCh,e.leftCh.parent=e}},n.prototype.inorderTraversalAux=function(t,e,i){t===null||i.stop||(this.inorderTraversalAux(t.leftCh,e,i),!i.stop&&(i.stop=e(t.element)===!1,!i.stop&&this.inorderTraversalAux(t.rightCh,e,i)))},n.prototype.levelTraversalAux=function(t,e){var i=new lh.default;for(t!==null&&i.enqueue(t),t=i.dequeue()||null;t!=null;){if(e(t.element)===!1)return;t.leftCh!==null&&i.enqueue(t.leftCh),t.rightCh!==null&&i.enqueue(t.rightCh),t=i.dequeue()||null}},n.prototype.preorderTraversalAux=function(t,e,i){t===null||i.stop||(i.stop=e(t.element)===!1,!i.stop&&(this.preorderTraversalAux(t.leftCh,e,i),!i.stop&&this.preorderTraversalAux(t.rightCh,e,i)))},n.prototype.postorderTraversalAux=function(t,e,i){t===null||i.stop||(this.postorderTraversalAux(t.leftCh,e,i),!i.stop&&(this.postorderTraversalAux(t.rightCh,e,i),!i.stop&&(i.stop=e(t.element)===!1)))},n.prototype.minimumAux=function(t){for(;t!=null&&t.leftCh!==null;)t=t.leftCh;return t},n.prototype.maximumAux=function(t){for(;t!=null&&t.rightCh!==null;)t=t.rightCh;return t},n.prototype.heightAux=function(t){return t===null?-1:Math.max(this.heightAux(t.leftCh),this.heightAux(t.rightCh))+1},n.prototype.insertNode=function(t){for(var e=null,i=this.root;i!==null;){var s=this.compare(t.element,i.element);if(s===0)return null;s<0?(e=i,i=i.leftCh):(e=i,i=i.rightCh)}return t.parent=e,e===null?this.root=t:this.compare(t.element,e.element)<0?e.leftCh=t:e.rightCh=t,t},n.prototype.createNode=function(t){return{element:t,leftCh:null,rightCh:null,parent:null}},n}();Kn.default=hh;var ch=We&&We.__extends||function(){var n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(t,e){n(t,e);function i(){this.constructor=t}t.prototype=e===null?Object.create(e):(i.prototype=e.prototype,new i)}}();Object.defineProperty($r,"__esModule",{value:!0});var uh=Kn,fh=function(n){ch(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t}(uh.default);$r.default=fh;var Jn={};Object.defineProperty(Jn,"__esModule",{value:!0});var lr=Ke,fn=ke,dh=function(){function n(t){this.data=[],this.compare=t||lr.defaultCompare}return n.prototype.leftChildIndex=function(t){return 2*t+1},n.prototype.rightChildIndex=function(t){return 2*t+2},n.prototype.parentIndex=function(t){return Math.floor((t-1)/2)},n.prototype.minIndex=function(t,e){return e>=this.data.length?t>=this.data.length?-1:t:this.compare(this.data[t],this.data[e])<=0?t:e},n.prototype.siftUp=function(t){for(var e=this.parentIndex(t);t>0&&this.compare(this.data[e],this.data[t])>0;)fn.swap(this.data,e,t),t=e,e=this.parentIndex(t)},n.prototype.siftDown=function(t){for(var e=this.minIndex(this.leftChildIndex(t),this.rightChildIndex(t));e>=0&&this.compare(this.data[t],this.data[e])>0;)fn.swap(this.data,e,t),t=e,e=this.minIndex(this.leftChildIndex(t),this.rightChildIndex(t))},n.prototype.peek=function(){if(this.data.length>0)return this.data[0]},n.prototype.add=function(t){return lr.isUndefined(t)?!1:(this.data.push(t),this.siftUp(this.data.length-1),!0)},n.prototype.removeRoot=function(){if(this.data.length>0){var t=this.data[0];return this.data[0]=this.data[this.data.length-1],this.data.splice(this.data.length-1,1),this.data.length>0&&this.siftDown(0),t}},n.prototype.contains=function(t){var e=lr.compareToEquals(this.compare);return fn.contains(this.data,t,e)},n.prototype.size=function(){return this.data.length},n.prototype.isEmpty=function(){return this.data.length<=0},n.prototype.clear=function(){this.data.length=0},n.prototype.forEach=function(t){fn.forEach(this.data,t)},n}();Jn.default=dh;var to={},ph=We&&We.__extends||function(){var n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])};return function(t,e){n(t,e);function i(){this.constructor=t}t.prototype=e===null?Object.create(e):(i.prototype=e.prototype,new i)}}();Object.defineProperty(to,"__esModule",{value:!0});var mh=zi,as=Ke,gh=function(){function n(t,e){this.key=t,this.value=e}return n.prototype.unlink=function(){this.prev.next=this.next,this.next.prev=this.prev},n}(),Fo=function(){function n(){this.key=null,this.value=null}return n.prototype.unlink=function(){this.prev.next=this.next,this.next.prev=this.prev},n}();function bh(n){return!n.next}var Sh=function(n){ph(t,n);function t(e){var i=n.call(this,e)||this;return i.head=new Fo,i.tail=new Fo,i.head.next=i.tail,i.tail.prev=i.head,i}return t.prototype.appendToTail=function(e){var i=this.tail.prev;i.next=e,e.prev=i,e.next=this.tail,this.tail.prev=e},t.prototype.getLinkedDictionaryPair=function(e){if(!as.isUndefined(e)){var i="$"+this.toStr(e),s=this.table[i];return s}},t.prototype.getValue=function(e){var i=this.getLinkedDictionaryPair(e);if(!as.isUndefined(i))return i.value},t.prototype.remove=function(e){var i=this.getLinkedDictionaryPair(e);if(!as.isUndefined(i))return n.prototype.remove.call(this,e),i.unlink(),i.value},t.prototype.clear=function(){n.prototype.clear.call(this),this.head.next=this.tail,this.tail.prev=this.head},t.prototype.replace=function(e,i){var s="$"+this.toStr(i.key);i.next=e.next,i.prev=e.prev,this.remove(e.key),i.prev.next=i,i.next.prev=i,this.table[s]=i,++this.nElements},t.prototype.setValue=function(e,i){if(!(as.isUndefined(e)||as.isUndefined(i))){var s=this.getLinkedDictionaryPair(e),r=new gh(e,i),o="$"+this.toStr(e);if(as.isUndefined(s)){this.appendToTail(r),this.table[o]=r,++this.nElements;return}else return this.replace(s,r),s.value}},t.prototype.keys=function(){var e=[];return this.forEach(function(i,s){e.push(i)}),e},t.prototype.values=function(){var e=[];return this.forEach(function(i,s){e.push(s)}),e},t.prototype.forEach=function(e){for(var i=this.head.next;!bh(i);){var s=e(i.key,i.value);if(s===!1)return;i=i.next}},t}(mh.default);to.default=Sh;var eo={};Object.defineProperty(eo,"__esModule",{value:!0});var Bi=Ke,yh=zi,hr=ke,xh=function(){function n(t,e,i){i===void 0&&(i=!1),this.dict=new yh.default(t),this.equalsF=e||Bi.defaultEquals,this.allowDuplicate=i}return n.prototype.getValue=function(t){var e=this.dict.getValue(t);return Bi.isUndefined(e)?[]:hr.copy(e)},n.prototype.setValue=function(t,e){if(Bi.isUndefined(t)||Bi.isUndefined(e))return!1;var i=this.dict.getValue(t);return Bi.isUndefined(i)?(this.dict.setValue(t,[e]),!0):!this.allowDuplicate&&hr.contains(i,e,this.equalsF)?!1:(i.push(e),!0)},n.prototype.remove=function(t,e){if(Bi.isUndefined(e)){var i=this.dict.remove(t);return!Bi.isUndefined(i)}var s=this.dict.getValue(t);return!Bi.isUndefined(s)&&hr.remove(s,e,this.equalsF)?(s.length===0&&this.dict.remove(t),!0):!1},n.prototype.keys=function(){return this.dict.keys()},n.prototype.values=function(){for(var t=this.dict.values(),e=[],i=0,s=t;i-1&&this.insertIdIntoRoot(e,i);for(var s in this.nodes)if(this.nodes.hasOwnProperty(s)){var r=this.findNodeId(s,t);r>-1&&this.insertIdIntoNode(s,e,r)}},n.prototype.insertIdAfterId=function(t,e){var i=this.findRootId(t);i>-1&&this.insertIdIntoRoot(e,i+1);for(var s in this.nodes)if(this.nodes.hasOwnProperty(s)){var r=this.findNodeId(s,t);r>-1&&this.insertIdIntoNode(s,e,r+1)}},n.prototype.insertIdIntoId=function(t,e){this.nodeInsertAtEnd(t,e),this.nodes[e]=[]},n.prototype.insertIdIntoRoot=function(t,e){if(e===void 0)this.rootInsertAtEnd(t);else if(e<0){var i=this.rootIds.length;this.rootIds.splice(e+i+1,0,t)}else this.rootIds.splice(e,0,t);this.nodes[t]=this.nodes[t]||[]},n.prototype.insertIdIntoNode=function(t,e,i){if(this.nodes[t]=this.nodes[t]||[],this.nodes[e]=this.nodes[e]||[],i===void 0)this.nodeInsertAtEnd(t,e);else if(i<0){var s=this.nodes[t].length;this.nodes[t].splice(i+s+1,0,e)}else this.nodes[t].splice(i,0,e)},n.prototype.moveId=function(t,e,i){var s=t,r=this.findRootId(s);this.nodes[e];for(var o in this.nodes)if(this.nodes.hasOwnProperty(o)){this.findNodeId(o,e);break}var a=e,l=this.findRootId(a);this.nodes[e];for(var o in this.nodes)if(this.nodes.hasOwnProperty(o)){this.findNodeId(o,e);break}if(r>-1)if(l>-1)switch(this.rootDelete(r),l>r&&l--,i){case de.BEFORE:this.insertIdIntoRoot(s,l);break;case de.AFTER:this.insertIdIntoRoot(s,l+1);break;case de.INSIDE_AT_START:this.nodeInsertAtStart(a,s);break;case de.INSIDE_AT_END:this.nodeInsertAtEnd(a,s);break}else{this.rootDelete(r);for(var o in this.nodes)if(this.nodes.hasOwnProperty(o)){var h=this.findNodeId(o,a);if(h>-1){switch(i){case de.BEFORE:this.insertIdIntoNode(o,s,h);break;case de.AFTER:this.insertIdIntoNode(o,s,h+1);break;case de.INSIDE_AT_START:this.nodeInsertAtStart(a,s);break;case de.INSIDE_AT_END:this.nodeInsertAtEnd(a,s);break}break}}}else if(l>-1){for(var o in this.nodes)if(this.nodes.hasOwnProperty(o)){var h=this.findNodeId(o,s);if(h>-1){this.nodeDeleteAtIndex(o,h);break}}switch(i){case de.BEFORE:this.insertIdIntoRoot(s,l);break;case de.AFTER:this.insertIdIntoRoot(s,l+1);break;case de.INSIDE_AT_START:this.nodeInsertAtStart(a,s);break;case de.INSIDE_AT_END:this.nodeInsertAtEnd(a,s);break}}else{for(var o in this.nodes)if(this.nodes.hasOwnProperty(o)){var h=this.findNodeId(o,s);if(h>-1){this.nodeDeleteAtIndex(o,h);break}}for(var o in this.nodes)if(this.nodes.hasOwnProperty(o)){var h=this.findNodeId(o,a);if(h>-1){switch(i){case de.BEFORE:this.insertIdIntoNode(o,s,h);break;case de.AFTER:this.insertIdIntoNode(o,s,h+1);break;case de.INSIDE_AT_START:this.nodeInsertAtStart(a,s);break;case de.INSIDE_AT_END:this.nodeInsertAtEnd(a,s);break}break}}}},n.prototype.swapArrayElements=function(t,e,i){var s=t[e];return t[e]=t[i],t[i]=s,t},n.prototype.rootDeleteId=function(t){var e=this.findRootId(t);e>-1&&this.rootDelete(e)},n.prototype.nodeAndSubNodesDelete=function(t){for(var e=[],i=0;i(n[n.pppppp=0]="pppppp",n[n.ppppp=1]="ppppp",n[n.pppp=2]="pppp",n[n.ppp=3]="ppp",n[n.pp=4]="pp",n[n.p=5]="p",n[n.mp=6]="mp",n[n.mf=7]="mf",n[n.f=8]="f",n[n.ff=9]="ff",n[n.fff=10]="fff",n[n.ffff=11]="ffff",n[n.fffff=12]="fffff",n[n.ffffff=13]="ffffff",n[n.sf=14]="sf",n[n.sff=15]="sff",n[n.sfp=16]="sfp",n[n.sfpp=17]="sfpp",n[n.fp=18]="fp",n[n.rf=19]="rf",n[n.rfz=20]="rfz",n[n.sfz=21]="sfz",n[n.sffz=22]="sffz",n[n.fz=23]="fz",n[n.other=24]="other",n))(ie||{});Ai.staticConstructor();class Pi{constructor(t,e){t instanceof ei?this.continuousDynamicExpression=t:t instanceof Ai&&(this.instantaneousDynamicExpression=t),this.staffNumber=e}static Compare(t,e){return t.parMultiExpression().AbsoluteTimestamp.CompareTo(e.parMultiExpression().AbsoluteTimestamp)}parMultiExpression(){if(this.continuousDynamicExpression)return this.continuousDynamicExpression.StartMultiExpression;if(this.instantaneousDynamicExpression)return this.instantaneousDynamicExpression.ParentMultiExpression}}class ro{constructor(t){this.printObject=!0,this.parent=t}get Parent(){return this.parent}set Parent(t){this.parent=t}get PrintObject(){return this.printObject}set PrintObject(t){this.printObject=t}}class Ae extends ro{constructor(t,e){super(void 0),this.rhythm=t,this.numerator=t.Numerator,this.denominator=t.Denominator,this.symbolEnum=e}get Rhythm(){return this.rhythm}set Rhythm(t){this.rhythm=t}get SymbolEnum(){return this.symbolEnum}set SymbolEnum(t){this.symbolEnum=t}clone(){return new Ae(this.rhythm.clone(),this.symbolEnum)}OperatorEquals(t){const e=this;return e===t?!0:!e||!t?!1:e.numerator===t.numerator&&e.denominator===t.denominator}OperatorNotEqual(t){return this!==t}ToString(){return"Rhythm: "+this.rhythm.toString()}}var ii=(n=>(n[n.NONE=0]="NONE",n[n.COMMON=1]="COMMON",n[n.CUT=2]="CUT",n))(ii||{});class Ss{constructor(t,e,i){this.currentMeasureIndex=0,this.currentPartIndex=0,this.currentVoiceEntryIndex=-1,this.currentDynamicEntryIndex=0,this.currentTempoEntryIndex=0,this.currentDynamicChangingExpressions=[],this.repetitionIterationCountDictKeys=[],this.repetitionIterationCountDictValues=[],this.currentRepetition=void 0,this.endReached=!1,this.frontReached=!1,this.currentTimeStamp=new W(0,1),this.currentEnrolledMeasureTimestamp=new W(0,1),this.currentRelativeInMeasureTimestamp=new W(0,1),this.currentVerticalContainerInMeasureTimestamp=new W(0,1),this.jumpResponsibleRepetition=void 0,this.activeDynamicExpressions=[];try{this.frontReached=!0,this.musicSheet=t,this.currentBpm=t.userStartTempoInBPM,this.currentVoiceEntries=void 0,this.frontReached=!1;for(const s of this.musicSheet.Repetitions)this.setRepetitionIterationCount(s,1);for(let s=0;s=this.JumpResponsibleRepetition.StartIndex&&s.EndIndex<=this.JumpResponsibleRepetition.EndIndex&&this.resetRepetitionIterationCount(s)}}handleRepetitionsAtMeasureEnd(){for(let t=0,e=this.currentMeasure.LastRepetitionInstructions.length;t-1&&this.getRepetitionIterationCount(s)=this.JumpResponsibleRepetition.StartIndex&&s.EndIndex<=this.JumpResponsibleRepetition.EndIndex&&this.resetRepetitionIterationCount(s),this.repetitionIterationCountDictKeys.contains(s))){const r=s.getForwardJumpTargetForIteration(this.getRepetitionIterationCount(s));if(r>=0){this.currentMeasureIndex=r,this.currentMeasure=this.musicSheet.SourceMeasures[this.currentMeasureIndex],this.currentVoiceEntryIndex=-1,this.jumpResponsibleRepetition=s,this.forwardJumpOccurred=!0;return}r===-2&&(this.endReached=!0)}}}this.currentMeasureIndex++,this.JumpResponsibleRepetition!==void 0&&this.currentMeasureIndex>this.JumpResponsibleRepetition.EndIndex&&(this.jumpResponsibleRepetition=void 0)}doBackJump(t){this.currentMeasureIndex=t.getBackwardJumpTarget(),this.currentMeasure=this.musicSheet.SourceMeasures[this.currentMeasureIndex],this.currentVoiceEntryIndex=-1,this.incrementRepetitionIterationCount(t),this.jumpResponsibleRepetition=t,this.backJumpOccurred=!0}activateCurrentRhythmInstructions(){if(this.currentMeasure!==void 0&&this.currentMeasure.FirstInstructionsStaffEntries.length>0&&this.currentMeasure.FirstInstructionsStaffEntries[0]!==void 0){const t=this.currentMeasure.FirstInstructionsStaffEntries[0].Instructions;for(let e=0,i=t.length;e0&&(this.currentDynamicEntryIndex>=t.length||t[this.currentDynamicEntryIndex].parMultiExpression().AbsoluteTimestamp.gte(this.CurrentSourceTimestamp));)this.currentDynamicEntryIndex--;for(;this.currentDynamicEntryIndex0&&(this.currentTempoEntryIndex>=e.length||e[this.currentTempoEntryIndex].AbsoluteTimestamp.gte(this.CurrentSourceTimestamp));)this.currentTempoEntryIndex--;for(;this.currentTempoEntryIndex=0&&this.currentVoiceEntryIndex=0&&this.currentMeasureIndex0){if(!t)return!0;for(let i=0,s=e.length;ie&&(this.openSheetMusicDisplay.Sheet.SelectionStart=this.openSheetMusicDisplay.Sheet.SourceMeasures[e].AbsoluteTimestamp),this.openSheetMusicDisplay.Sheet&&this.openSheetMusicDisplay.Sheet.SourceMeasures.length>i){const r=this.openSheetMusicDisplay.Sheet.SourceMeasures[i];this.openSheetMusicDisplay.Sheet.SelectionEnd=W.plus(r.AbsoluteTimestamp,r.Duration)}this.iterator=this.manager.getIterator()}getStaffEntryFromVoiceEntry(t){const e=t.ParentSourceStaffEntry.VerticalContainerParent.ParentMeasure.measureListIndex,i=t.ParentSourceStaffEntry.ParentStaff.idInMusicSheet;return this.graphic.findGraphicalStaffEntryFromMeasureList(i,e,t.ParentSourceStaffEntry)}updateWithTimestamp(t){const e=this.manager.absoluteEnrolledToSheetTimestamp(t),i=this.graphic.calculateXPositionFromTimestamp(e),s=i[0],r=i[1];this.updateCurrentPageFromSystem(r);const o=i[2];if(!o)return;const a=Math.max(o.parentMeasure.MeasureNumber,1);let l;for(const f of this.graphic.MeasureList[a-1])if(f){l=f;break}const h=this.graphic.calculateCursorPoints(s,r),c=h[0].y,u=h[1].y-c;if(!!l){if(this.updateWidthAndStyle(l.PositionAndShape,s,c,u),this.openSheetMusicDisplay.FollowCursor){const f=this.cursorElement.getBoundingClientRect().top;this.cursorElement.scrollIntoView({behavior:f<1e3?"smooth":"auto",block:"center"})}this.cursorElement.style.display=""}}update(){if(this.hidden||this.hidden===void 0||this.hidden===null)return;this.updateCurrentPage();const t=this.Iterator,e=t.CurrentVisibleVoiceEntries();if(t.EndReached||!t.CurrentVoiceEntries||e.length===0)return;let i=0,s=0,r=0,o;if(t.CurrentMeasure.isReducedToMultiRest){const c=this.graphic.findGraphicalMeasure(t.CurrentMeasureIndex,0),u=c.parentSourceMeasure.multipleRestMeasures,d=t.CurrentMeasure.multipleRestMeasureNumber/(u+1),p=c.PositionAndShape.Size.width-c.beginInstructionsWidth;i=c.PositionAndShape.AbsolutePosition.x+c.beginInstructionsWidth+d*p,o=c.ParentMusicSystem}else{const u=e.map(f=>this.getStaffEntryFromVoiceEntry(f)).sort((f,d)=>{var p,g,m,S;return((g=(p=f==null?void 0:f.PositionAndShape)==null?void 0:p.AbsolutePosition)==null?void 0:g.x)<=((S=(m=d==null?void 0:d.PositionAndShape)==null?void 0:m.AbsolutePosition)==null?void 0:S.x)?-1:1})[0];u&&(i=u.PositionAndShape.AbsolutePosition.x,o=u.parentMeasure.ParentMusicSystem)}if(!o)return;s=o.PositionAndShape.AbsolutePosition.y+o.StaffLines[0].PositionAndShape.RelativePosition.y;const a=o.StaffLines[o.StaffLines.length-1];r=o.PositionAndShape.AbsolutePosition.y+a.PositionAndShape.RelativePosition.y+a.StaffHeight-s;const h=this.graphic.findGraphicalMeasure(t.CurrentMeasureIndex,0).PositionAndShape;if(this.updateWidthAndStyle(h,i,s,r),this.openSheetMusicDisplay.FollowCursor&&this.cursorOptions.follow)if(this.openSheetMusicDisplay.EngravingRules.RenderSingleHorizontalStaffline)this.cursorElement.scrollIntoView({behavior:"smooth",inline:"center"});else{const c=this.cursorElement.getBoundingClientRect().top;this.cursorElement.scrollIntoView({behavior:c<1e3?"smooth":"auto",block:"center"})}this.cursorElement.style.display=""}updateWidthAndStyle(t,e,i,s){const r=this.cursorElement;let o=0,a=s;switch(this.cursorOptions.type){case 1:r.style.top=i*10*this.openSheetMusicDisplay.zoom+"px",r.style.left=(e-1.5)*10*this.openSheetMusicDisplay.zoom+"px",a=s*10*this.openSheetMusicDisplay.zoom,r.height=a,r.style.height=a+"px",o=5*this.openSheetMusicDisplay.zoom;break;case 2:r.style.top=(i-2.5)*10*this.openSheetMusicDisplay.zoom+"px",r.style.left=e*10*this.openSheetMusicDisplay.zoom+"px",a=1.5*10*this.openSheetMusicDisplay.zoom,r.height=a,r.style.height=a+"px",o=5*this.openSheetMusicDisplay.zoom;break;case 3:r.style.top=t.AbsolutePosition.y*10*this.openSheetMusicDisplay.zoom+"px",r.style.left=t.AbsolutePosition.x*10*this.openSheetMusicDisplay.zoom+"px",a=s*10*this.openSheetMusicDisplay.zoom,r.height=a,r.style.height=a+"px",o=t.Size.width*10*this.openSheetMusicDisplay.zoom;break;case 4:r.style.top=t.AbsolutePosition.y*10*this.openSheetMusicDisplay.zoom+"px",r.style.left=t.AbsolutePosition.x*10*this.openSheetMusicDisplay.zoom+"px",a=s*10*this.openSheetMusicDisplay.zoom,r.height=a,r.style.height=a+"px",o=(e-t.AbsolutePosition.x)*10*this.openSheetMusicDisplay.zoom;break;default:r.style.top=i*10*this.openSheetMusicDisplay.zoom+"px",r.style.left=(e-1.5)*10*this.openSheetMusicDisplay.zoom+"px",a=s*10*this.openSheetMusicDisplay.zoom,r.height=a,r.style.height=a+"px",o=3*10*this.openSheetMusicDisplay.zoom;break}o!==r.width&&(r.width=o,this.updateStyle(o,this.cursorOptions))}hide(){this.cursorElement.style.display="none",this.hidden=!0}next(){this.Iterator.moveToNextVisibleVoiceEntry(!1),this.update()}reset(){this.resetIterator();const t=this.manager.getIterator(this.graphic.ParentMusicSheet.SelectionStart);this.updateWithTimestamp(t.CurrentEnrolledTimestamp)}updateStyle(t,e=void 0){e!==void 0&&(this.cursorOptions=e);const i=document.createElement("canvas");i.width=this.cursorElement.width,i.height=1;const s=i.getContext("2d");s.globalAlpha=this.cursorOptions.alpha;const r=s.createLinearGradient(0,0,this.cursorElement.width,0);switch(this.cursorOptions.type){case 1:case 2:case 3:case 4:r.addColorStop(1,this.cursorOptions.color);break;default:r.addColorStop(0,"white"),r.addColorStop(.2,this.cursorOptions.color),r.addColorStop(.8,this.cursorOptions.color),r.addColorStop(1,"white");break}s.fillStyle=r,s.fillRect(0,0,t,1),this.cursorElement.src=i.toDataURL("image/png")}get Iterator(){return this.iterator}get Hidden(){return this.hidden}VoicesUnderCursor(t){return this.Iterator.CurrentVisibleVoiceEntries(t)}NotesUnderCursor(t){const e=this.VoicesUnderCursor(t),i=[];return e.forEach(s=>{i.push.apply(i,s.Notes)}),i}GNotesUnderCursor(t){const e=this.VoicesUnderCursor(t),i=[];return e.forEach(s=>{i.push(...s.Notes.map(r=>this.rules.GNote(r)))}),i}updateCurrentPage(){const t=this.Iterator.currentTimeStamp;for(const e of this.graphic.MusicPages)if(e.MusicSystems.last().GetSystemsLastTimeStamp().gt(t)){const s=e.PageNumber;return s!==this.currentPageNumber&&(this.container.removeChild(this.cursorElement),this.container=document.getElementById(this.rules.DYContainerId+s),this.container.appendChild(this.cursorElement)),this.currentPageNumber=s}return 1}updateCurrentPageFromSystem(t){if(t!=null&&t.Parent){const e=t.Parent.PageNumber;return e!==this.currentPageNumber&&(this.container.removeChild(this.cursorElement),this.container=document.getElementById(this.rules.DYContainerId+e),this.container.appendChild(this.cursorElement)),this.currentPageNumber=e}return 1}}class O{constructor(t=0,e=0){this.x=0,this.y=0,this.x=t,this.y=e}static get Empty(){return new O}static pointsAreEqual(t,e){return t.x===e.x&&t.y===e.y}ToString(){return"["+this.x+", "+this.y+"]"}}class $e{constructor(t=0,e=0){this.width=t,this.height=e}}class Qe{constructor(t,e,i,s){this.x=0,this.y=0,this.width=0,this.height=0,this.x=t,this.y=e,this.width=i,this.height=s}static createFromLocationAndSize(t,e){return new Qe(t.x,t.y,e.width,e.height)}get Location(){return new O(this.x,this.y)}get Size(){return new $e(this.width,this.height)}}class qh{isInstanceOfClass(t){let e=this.constructor.prototype;for(;e;){if(t===e.constructor.name)return!0;e=e.__proto__}return!1}}class Pe extends qh{get PositionAndShape(){return this.boundingBox}set PositionAndShape(t){this.boundingBox=t}}class wa extends Pe{constructor(t){super(),this.parentStaffLine=t;const e=t.PositionAndShape;this.boundingBox=new le(this,e),this.boundingBox.BorderRight=6,this.boundingBox.BorderBottom=4.5,this.boundingBox.BorderLeft=-1.5,this.boundingBox.BorderTop=-1.5}}class Tn extends Pe{}class le{constructor(t=void 0,e=void 0,i=!1){this.isSymbol=!1,this.relativePositionHasBeenSet=!1,this.xBordersHaveBeenSet=!1,this.yBordersHaveBeenSet=!1,this.absolutePosition=new O,this.relativePosition=new O,this.size=new $e,this.marginSize=new $e,this.upperLeftCorner=new O,this.upperLeftMarginCorner=new O,this.borderLeft=0,this.borderRight=0,this.borderTop=0,this.borderBottom=0,this.borderMarginLeft=0,this.borderMarginRight=0,this.borderMarginTop=0,this.borderMarginBottom=0,this.childElements=[],this.parent=e,this.dataObject=t,this.isSymbol=i,this.xBordersHaveBeenSet=!1,this.yBordersHaveBeenSet=!1,e&&(this.Parent=e)}get RelativePositionHasBeenSet(){return this.relativePositionHasBeenSet}get XBordersHaveBeenSet(){return this.xBordersHaveBeenSet}set XBordersHaveBeenSet(t){this.xBordersHaveBeenSet=t}get YBordersHaveBeenSet(){return this.yBordersHaveBeenSet}set YBordersHaveBeenSet(t){this.yBordersHaveBeenSet=t}get AbsolutePosition(){return this.absolutePosition}set AbsolutePosition(t){this.absolutePosition=t}get RelativePosition(){return this.relativePosition}set RelativePosition(t){this.relativePosition=t,this.relativePositionHasBeenSet=!0}get Size(){return this.size}set Size(t){this.size=t}get MarginSize(){return this.marginSize}get UpperLeftCorner(){return this.upperLeftCorner}get UpperLeftMarginCorner(){return this.upperLeftMarginCorner}get BorderLeft(){return this.borderLeft}set BorderLeft(t){this.borderLeft=t,this.calculateRectangle()}get BorderRight(){return this.borderRight}set BorderRight(t){this.borderRight=t,this.calculateRectangle()}get BorderTop(){return this.borderTop}set BorderTop(t){this.borderTop=t,this.calculateRectangle()}get BorderBottom(){return this.borderBottom}set BorderBottom(t){this.borderBottom=t,this.calculateRectangle()}get BorderMarginLeft(){return this.borderMarginLeft>this.borderLeft?this.borderLeft:this.borderMarginLeft}set BorderMarginLeft(t){this.borderMarginLeft=t,this.calculateMarginRectangle()}get BorderMarginRight(){return this.borderMarginRightthis.borderTop?this.borderTop:this.borderMarginTop}set BorderMarginTop(t){this.borderMarginTop=t,this.calculateMarginRectangle()}get BorderMarginBottom(){return this.borderMarginBottom-1&&this.parent.ChildElements.splice(o,1)}this.parent=t,((i=(e=this.parent)==null?void 0:e.ChildElements)==null?void 0:i.indexOf(this))>-1?j.error("BoundingBox of "+this.dataObject.constructor.name+" already in children list of "+this.parent.dataObject.constructor.name+"'s BoundingBox"):(r=(s=this.parent)==null?void 0:s.ChildElements)==null||r.push(this)}get DataObject(){return this.dataObject}get Center(){return new O(this.RelativePosition.x+(this.BorderMarginRight+this.BorderMarginLeft),this.RelativePosition.y+(this.BorderMarginBottom+this.BorderMarginTop))}setAbsolutePositionFromParent(){this.parent?(this.absolutePosition.x=this.parent.AbsolutePosition.x+this.relativePosition.x,this.absolutePosition.y=this.parent.AbsolutePosition.y+this.relativePosition.y):this.absolutePosition=this.relativePosition}calculateAbsolutePosition(){this.absolutePosition.x=this.relativePosition.x,this.absolutePosition.y=this.relativePosition.y;let t=this.parent;for(;t;)this.absolutePosition.x+=t.relativePosition.x,this.absolutePosition.y+=t.relativePosition.y,t=t.parent}calculateAbsolutePositionsRecursiveWithoutTopelement(){this.absolutePosition.x=0,this.absolutePosition.y=0;for(let t=0,e=this.ChildElements.length;t.001;break;case ve.Up:case ve.Down:s=this.relativePosition.y,t.calculateMarginPositionAlongDirection(this,e),r=Math.abs(s-this.relativePosition.y)>.001;break;default:throw new Li("direction")}while(r)}collisionDetection(t){const e=Math.min(this.AbsolutePosition.x+this.borderRight,t.absolutePosition.x+t.borderRight)-Math.max(this.AbsolutePosition.x+this.borderLeft,t.absolutePosition.x+t.borderLeft),i=Math.min(this.AbsolutePosition.y+this.borderBottom,t.absolutePosition.y+t.borderBottom)-Math.max(this.AbsolutePosition.y+this.borderTop,t.absolutePosition.y+t.borderTop);return e>0&&i>0}liesInsideBorders(t){const e=this.AbsolutePosition.x+this.borderLeft<=t.absolutePosition.x+t.borderLeft&&t.absolutePosition.x+t.borderLeft<=this.AbsolutePosition.x+this.borderRight,i=this.AbsolutePosition.x+this.borderLeft<=t.absolutePosition.x+t.borderRight&&t.absolutePosition.x+t.borderRight<=this.AbsolutePosition.x+this.borderRight;if(e&&i){const s=this.AbsolutePosition.y+this.borderTop<=t.absolutePosition.y+t.borderTop&&t.absolutePosition.y+t.borderTop<=this.AbsolutePosition.y+this.borderBottom,r=this.AbsolutePosition.y+this.borderTop<=t.absolutePosition.y+t.borderBottom&&t.absolutePosition.y+t.borderBottom<=this.AbsolutePosition.y+this.borderBottom;if(s&&r)return!0}return!1}pointLiesInsideBorders(t){return this.AbsolutePosition.x+this.borderLeft<=t.x&&t.x<=this.AbsolutePosition.x+this.borderRight&&this.AbsolutePosition.y+this.borderTop<=t.y&&t.y<=this.AbsolutePosition.y+this.borderBottom}marginCollisionDetection(t){const e=Math.min(this.AbsolutePosition.x+this.borderMarginRight,t.absolutePosition.x+t.borderMarginRight)-Math.max(this.AbsolutePosition.x+this.borderMarginLeft,t.absolutePosition.x+t.borderMarginLeft),i=Math.min(this.AbsolutePosition.y+this.borderMarginBottom,t.absolutePosition.y+t.borderMarginBottom)-Math.max(this.AbsolutePosition.y+this.borderMarginTop,t.absolutePosition.y+t.borderMarginTop);return e>0&&i>0}liesInsideMargins(t){const e=this.AbsolutePosition.x+this.borderMarginLeft<=t.absolutePosition.x+t.borderMarginLeft&&t.absolutePosition.x+t.borderMarginLeft<=this.AbsolutePosition.x+this.borderMarginRight,i=this.AbsolutePosition.x+this.borderMarginLeft<=t.absolutePosition.x+t.borderMarginRight&&t.absolutePosition.x+t.borderMarginRight<=this.AbsolutePosition.x+this.borderMarginRight;if(e&&i){const s=this.AbsolutePosition.y+this.borderMarginTop<=t.absolutePosition.y+t.borderMarginTop&&t.absolutePosition.y+t.borderMarginTop<=this.AbsolutePosition.y+this.borderMarginBottom,r=this.AbsolutePosition.y+this.borderMarginTop<=t.absolutePosition.y+t.borderMarginBottom&&t.absolutePosition.y+t.borderMarginBottom<=this.AbsolutePosition.y+this.borderMarginBottom;if(s&&r)return!0}return!1}pointLiesInsideMargins(t){return this.AbsolutePosition.x+this.borderMarginLeft<=t.x&&t.x<=this.AbsolutePosition.x+this.borderMarginRight&&this.AbsolutePosition.y+this.borderMarginTop<=t.y&&t.y<=this.AbsolutePosition.y+this.borderMarginBottom}computeNonOverlappingPosition(t,e,i){this.RelativePosition=new O(i.x,i.y),this.setAbsolutePositionFromParent();let s=0,r=!1;do switch(e){case ve.Left:case ve.Right:s=this.relativePosition.x,t.calculatePositionAlongDirection(this,e),r=Math.abs(s-this.relativePosition.x)>1e-4;break;case ve.Up:case ve.Down:s=this.relativePosition.y,t.calculatePositionAlongDirection(this,e),r=Math.abs(s-this.relativePosition.y)>1e-4;break;default:throw new Li("direction")}while(r)}getClickedObjectOfType(t){const e=this.dataObject;if(this.pointLiesInsideBorders(t)&&e)return e;for(let i=0,s=this.childElements.length;i(n[n.Left=0]="Left",n[n.Right=1]="Right",n[n.Up=2]="Up",n[n.Down=3]="Down",n))(ve||{});class vr extends Pe{constructor(t){super(),this.musicSystems=[],this.labels=[],this.parent=t,this.boundingBox=new le(this,void 0)}get MusicSystems(){return this.musicSystems}set MusicSystems(t){this.musicSystems=t}get Labels(){return this.labels}set Labels(t){this.labels=t}get Parent(){return this.parent}set Parent(t){this.parent=t}get PageNumber(){return this.pageNumber}set PageNumber(t){this.pageNumber=t}setMusicPageAbsolutePosition(t,e){return new O(0,0)}}var Ea=(n=>(n[n.Down=0]="Down",n[n.Right=1]="Right",n[n.RightDown=2]="RightDown",n))(Ea||{}),vt=(n=>(n[n.LeftTop=0]="LeftTop",n[n.LeftCenter=1]="LeftCenter",n[n.LeftBottom=2]="LeftBottom",n[n.CenterTop=3]="CenterTop",n[n.CenterCenter=4]="CenterCenter",n[n.CenterBottom=5]="CenterBottom",n[n.RightTop=6]="RightTop",n[n.RightCenter=7]="RightCenter",n[n.RightBottom=8]="RightBottom",n))(vt||{});class cr{static IsLeft(t){return t===0||t===1||t===2}static IsCenterAligned(t){return t===3||t===4||t===5}static IsRight(t){return t===6||t===7||t===8}}var ue=(n=>(n[n.Regular=0]="Regular",n[n.Bold=1]="Bold",n[n.Italic=2]="Italic",n[n.BoldItalic=3]="BoldItalic",n[n.Underlined=4]="Underlined",n))(ue||{}),_r=(n=>(n[n.TimesNewRoman=0]="TimesNewRoman",n[n.Kokila=1]="Kokila",n[n.Gonville=2]="Gonville",n))(_r||{});const Jh={0:"Times New Roman",1:"Kokila",2:"Gonville"};var Fs=(n=>(n.SIMPLE="",n.HAMMERON="H",n.PULLOFF="P",n.SLIDE="S",n.TAPPING="T",n))(Fs||{});const dn={"-2":[4,12,23],"-7":[13],"-9":[6]};var ut=(n=>(n[n.C=0]="C",n[n.D=2]="D",n[n.E=4]="E",n[n.F=5]="F",n[n.G=7]="G",n[n.A=9]="A",n[n.B=11]="B",n))(ut||{}),yt=(n=>(n[n.SHARP=0]="SHARP",n[n.FLAT=1]="FLAT",n[n.NONE=2]="NONE",n[n.NATURAL=3]="NATURAL",n[n.DOUBLESHARP=4]="DOUBLESHARP",n[n.DOUBLEFLAT=5]="DOUBLEFLAT",n[n.TRIPLESHARP=6]="TRIPLESHARP",n[n.TRIPLEFLAT=7]="TRIPLEFLAT",n[n.QUARTERTONESHARP=8]="QUARTERTONESHARP",n[n.QUARTERTONEFLAT=9]="QUARTERTONEFLAT",n[n.SLASHFLAT=10]="SLASHFLAT",n[n.THREEQUARTERSSHARP=11]="THREEQUARTERSSHARP",n[n.THREEQUARTERSFLAT=12]="THREEQUARTERSFLAT",n[n.SLASHQUARTERSHARP=13]="SLASHQUARTERSHARP",n[n.SLASHSHARP=14]="SLASHSHARP",n[n.DOUBLESLASHFLAT=15]="DOUBLESLASHFLAT",n[n.SORI=16]="SORI",n[n.KORON=17]="KORON",n))(yt||{});const At=class{constructor(n,t,e,i=void 0){this.accidental=2,this.fundamentalNote=n,this.octave=t,this.accidental=e,this.accidentalXml=i,this.halfTone=n+(t+At.octXmlDiff)*12+At.HalfTonesFromAccidental(e),this.frequency=At.calcFrequency(this),this.nextFrequency=At.calcFrequency(this,"next"),this.prevFrequency=At.calcFrequency(this,"prev")}static getNoteEnumString(n){switch(n){case 0:return"C";case 2:return"D";case 4:return"E";case 5:return"F";case 7:return"G";case 9:return"A";case 11:return"B";default:return""}}static lineShiftFromNoteEnum(n,t){if(t===0)return[n,0];const e=At.pitchEnumValues,i=e.indexOf(n);let s=0,r=(i+t)%e.length;return i+t>e.length-1&&(s=1),r<0&&(r=e.length+r,s=-1),[e[r],s]}static CalculateTransposedHalfTone(n,t){const e=n.fundamentalNote+n.AccidentalHalfTones+t;return At.WrapAroundCheck(e,12)}static WrapAroundCheck(n,t){let e=0;for(;n<0;)n+=t,e--;for(;n>=t;)n-=t,e++;return{overflow:e,halftone:n}}static calcFrequency(n,t){let e=0,i;if(n instanceof At){const a=n;e=a.octave-1,i=a.fundamentalNote-9+a.AccidentalHalfTones}else typeof n=="number"&&(i=n-57);const s=window.DYSubjectId;let r=0;window.DYEnvironment==="COLEXIU"&&(dn["12"]=[120]);for(const a in dn)if(Object.prototype.hasOwnProperty.call(dn,a)&&dn[a].includes(s)){r=parseFloat(a);break}let o=i+r;return t==="next"&&o++,t==="prev"&&o--,442*Math.pow(2,e)*Math.pow(2,o/12)}static calcFractionalKey(n){return Math.log(n/440)/Math.LN10*At.halftoneFactor+57}static fromFrequency(n){const t=At.calcFractionalKey(n)+.5,e=Math.floor(t/12)-At.octXmlDiff,i=Math.floor(t)%12;let s=i,r=2;return this.pitchEnumValues.indexOf(s)===-1&&(s=i-1,r=0),new At(s,e,r)}static fromHalftone(n){const t=Math.floor(n/12)-At.octXmlDiff,e=n%12;let i=e,s=2;return this.pitchEnumValues.indexOf(i)===-1&&(i=e-1,s=0),new At(i,t,s)}static ceiling(n){n=n%12;let t=n;return this.pitchEnumValues.indexOf(t)===-1&&(t=n+1),t}static floor(n){n=n%12;let t=n;return this.pitchEnumValues.indexOf(t)===-1&&(t=n-1),t}static HalfTonesFromAccidental(n){switch(n){case 2:return 0;case 0:return 1;case 1:return-1;case 3:return 0;case 4:return 2;case 5:return-2;case 6:return 3;case 7:return-3;case 8:return .5;case 9:return-.5;case 10:return-.51;case 11:return 1.5;case 12:return-1.5;case 13:return .0013;case 14:return .0014;case 15:return-.0015;case 16:return .0016;case 17:return .0017;default:throw new Error("Unhandled AccidentalEnum value")}}static AccidentalFromHalfTones(n){switch(n){case 0:return 2;case 1:return 0;case-1:return 1;case 2:return 4;case-2:return 5;case 3:return 6;case-3:return 7;case .5:return 8;case-.5:return 9;case 1.5:return 11;case-1.5:return 12;default:return n>0&&n<1?8:n<0&&n>-1?9:8}}static accidentalVexflow(n){let t;switch(n){case 3:t="n";break;case 1:t="b";break;case 0:t="#";break;case 4:t="##";break;case 6:t="###";break;case 5:t="bb";break;case 7:t="bbs";break;case 8:t="+";break;case 9:t="d";break;case 10:t="bs";break;case 11:t="++";break;case 12:t="db";break;case 13:t="+-";break;case 14:t="++-";break;case 15:t="bss";break;case 16:t="o";break;case 17:t="k";break}return t}get AccidentalHalfTones(){return At.HalfTonesFromAccidental(this.accidental)}get Octave(){return this.octave}get FundamentalNote(){return this.fundamentalNote}get Accidental(){return this.accidental}get AccidentalXml(){return this.accidentalXml}get Frequency(){return this.frequency}static get OctaveXmlDifference(){return At.octXmlDiff}getHalfTone(){return this.halfTone}getTransposedPitch(n){if(n>12)throw new Error("rewrite this method to handle bigger octave changes or don't use is with bigger octave changes!");return n>0?this.getHigherPitchByTransposeFactor(n):n<0?this.getLowerPitchByTransposeFactor(-n):this}DoEnharmonicChange(){switch(this.accidental){case 1:case 5:this.fundamentalNote=this.getPreviousFundamentalNote(this.fundamentalNote),this.accidental=At.AccidentalFromHalfTones(this.halfTone-(this.fundamentalNote+(this.octave+At.octXmlDiff)*12));break;case 0:case 4:this.fundamentalNote=this.getNextFundamentalNote(this.fundamentalNote),this.accidental=At.AccidentalFromHalfTones(this.halfTone-(this.fundamentalNote+(this.octave+At.octXmlDiff)*12));break;default:return}}ToString(){let n=At.accidentalVexflow(this.accidental);return n||(n=""),"Key: "+At.getNoteEnumString(this.fundamentalNote)+n+", Note: "+this.fundamentalNote+", octave: "+this.octave.toString()}OperatorEquals(n){const t=this;return!t||!n?!1:t.FundamentalNote===n.FundamentalNote&&t.Octave===n.Octave&&t.Accidental===n.Accidental}OperatorNotEqual(n){return this!==n}OperatorFundamentalGreaterThan(n){const t=this;return t.Octave===n.Octave?t.FundamentalNote>n.FundamentalNote:t.Octave>n.Octave}OperatorFundamentalLessThan(n){const t=this;return t.Octave===n.Octave?t.FundamentalNoteAt.pitchEnumValues.length-1?(i=At.pitchEnumValues[t+n-At.pitchEnumValues.length],e++):i=At.pitchEnumValues[t+n],new At(i,e,2)}getLowerPitchByTransposeFactor(n){const t=At.pitchEnumValues.indexOf(this.fundamentalNote);let e=this.octave,i;return t-n<0?(i=At.pitchEnumValues[At.pitchEnumValues.length+t-n],e--):i=At.pitchEnumValues[t-n],new At(i,e,2)}getNextFundamentalNote(n){let t=At.pitchEnumValues.indexOf(n);return t=(t+1)%At.pitchEnumValues.length,At.pitchEnumValues[t]}getPreviousFundamentalNote(n){const t=At.pitchEnumValues.indexOf(n);return t>0?At.pitchEnumValues[t-1]:At.pitchEnumValues[At.pitchEnumValues.length-1]}};let Kt=At;Kt.pitchEnumValues=[0,2,4,5,7,9,11];Kt.halftoneFactor=12/(Math.LN2/Math.LN10);Kt.octXmlDiff=3;class pn{constructor(t,e){this.staffEntries=[],this.absoluteTimestamp=e,this.staffEntries=new Array(t)}get Index(){return this.index}set Index(t){this.index=t}get AbsoluteTimestamp(){return this.absoluteTimestamp}get StaffEntries(){return this.staffEntries}set StaffEntries(t){this.staffEntries=t}static compareByTimestamp(t,e){const i=t.absoluteTimestamp.RealValue,s=e.absoluteTimestamp.RealValue;return is?1:0}getFirstNonNullStaffEntry(){for(let t=0,e=this.staffEntries.length;t(n[n.BaseWritingColor=0]="BaseWritingColor",n[n.FollowingCursor=1]="FollowingCursor",n[n.AlternativeFollowingCursor=2]="AlternativeFollowingCursor",n[n.PlaybackCursor=3]="PlaybackCursor",n[n.Highlighted=4]="Highlighted",n[n.ErrorUnderlay=5]="ErrorUnderlay",n[n.Selected=6]="Selected",n[n.SelectionSymbol=7]="SelectionSymbol",n[n.DebugColor1=8]="DebugColor1",n[n.DebugColor2=9]="DebugColor2",n[n.DebugColor3=10]="DebugColor3",n[n.SplitScreenDivision=11]="SplitScreenDivision",n[n.GreyTransparentOverlay=12]="GreyTransparentOverlay",n[n.MarkedArea1=13]="MarkedArea1",n[n.MarkedArea2=14]="MarkedArea2",n[n.MarkedArea3=15]="MarkedArea3",n[n.MarkedArea4=16]="MarkedArea4",n[n.MarkedArea5=17]="MarkedArea5",n[n.MarkedArea6=18]="MarkedArea6",n[n.MarkedArea7=19]="MarkedArea7",n[n.MarkedArea8=20]="MarkedArea8",n[n.MarkedArea9=21]="MarkedArea9",n[n.MarkedArea10=22]="MarkedArea10",n[n.Comment1=23]="Comment1",n[n.Comment2=24]="Comment2",n[n.Comment3=25]="Comment3",n[n.Comment4=26]="Comment4",n[n.Comment5=27]="Comment5",n[n.Comment6=28]="Comment6",n[n.Comment7=29]="Comment7",n[n.Comment8=30]="Comment8",n[n.Comment9=31]="Comment9",n[n.Comment10=32]="Comment10",n))(fs||{});const zt=new Ye;zt.setValue(0,"Thistle");zt.setValue(1,"Aqua");zt.setValue(2,"Azure");zt.setValue(3,"Bisque");zt.setValue(4,"CadetBlue");zt.setValue(5,"DarkBlue");zt.setValue(6,"DarkGoldenRod");zt.setValue(7,"BlanchedAlmond");zt.setValue(8,"Chartreuse");zt.setValue(9,"DarkGreen");zt.setValue(10,"DarkOrange");zt.setValue(11,"FireBrick");zt.setValue(12,"DarkSalmon");zt.setValue(13,"DarkSeaGreen");zt.setValue(14,"DarkOrchid");zt.setValue(15,"Aquamarine");zt.setValue(16,"DarkKhaki");zt.setValue(17,"ForestGreen");zt.setValue(18,"AliceBlue");zt.setValue(19,"DeepPink");zt.setValue(20,"Coral");zt.setValue(21,"DarkOliveGreen");zt.setValue(22,"Chocolate");zt.setValue(23,"DodgerBlue");zt.setValue(24,"Blue");zt.setValue(25,"Beige");zt.setValue(26,"Crimson");zt.setValue(27,"Fuchsia");zt.setValue(28,"Brown");zt.setValue(29,"BlanchedAlmond");zt.setValue(30,"CornflowerBlue");zt.setValue(31,"Cornsilk");zt.setValue(32,"DarkGrey");var pe=(n=>(n[n.Background=0]="Background",n[n.Highlight=1]="Highlight",n[n.MeasureError=2]="MeasureError",n[n.SelectionSymbol=3]="SelectionSymbol",n[n.Cursor=4]="Cursor",n[n.PSI_Debug=5]="PSI_Debug",n[n.Notes=6]="Notes",n[n.Comment=7]="Comment",n[n.Debug_above=8]="Debug_above",n))(pe||{}),Ma=(n=>(n[n.Normal=0]="Normal",n[n.Selected=1]="Selected",n[n.Follow_Confirmed=2]="Follow_Confirmed",n[n.QFeedback_NotFound=3]="QFeedback_NotFound",n[n.QFeedback_OK=4]="QFeedback_OK",n[n.QFeedback_Perfect=5]="QFeedback_Perfect",n[n.Debug1=6]="Debug1",n[n.Debug2=7]="Debug2",n[n.Debug3=8]="Debug3",n))(Ma||{}),wr=(n=>(n.C="#d82c6b",n.D="#F89D15",n.E="#FFE21A",n.F="#4dbd5c",n.G="#009D96",n.A="#43469d",n.B="#76429c",n.Rest="#000000",n))(wr||{});class ci{constructor(t,e,i=0,s=fs.BaseWritingColor,r=void 0){this.start=t,this.end=e,this.width=i,this.styleId=s,this.colorHex=r}get Start(){return this.start}set Start(t){this.start=t}get End(){return this.end}set End(t){this.end=t}get Width(){return this.width}set Width(t){this.width=t}}class Wt extends ro{constructor(t=Pt.G,e=0,i=2){super(void 0),this.clefType=Pt.G,this.line=2,this.octaveOffset=0,this.line=i,this.clefType=t,this.octaveOffset=e,this.calcParameters()}static getDefaultClefFromMidiInstrument(t){switch(t){case st.Acoustic_Grand_Piano:return new Wt(Pt.F,0,4);case st.Electric_Bass_finger:return new Wt(Pt.F,0,4);case st.Electric_Bass_pick:return new Wt(Pt.F,0,4);case st.Fretless_Bass:return new Wt(Pt.F,0,4);case st.Slap_Bass_1:return new Wt(Pt.F,0,4);case st.Slap_Bass_2:return new Wt(Pt.F,0,4);case st.Synth_Bass_1:return new Wt(Pt.F,0,4);case st.Synth_Bass_2:return new Wt(Pt.F,0,4);case st.Contrabass:return new Wt(Pt.F,0,4);default:return new Wt(Pt.G,0,2)}}static getAllPossibleClefs(){const t=[];for(let e=0;e<=2;e++){const i=new Wt(Pt.G,e,2);t.push(i)}for(let e=-2;e<=0;e++){const i=new Wt(Pt.F,e,4);t.push(i)}return t}static isSupportedClef(t){switch(t){case Pt.G:case Pt.F:case Pt.C:case Pt.percussion:case Pt.TAB:return!0;default:return!1}}get ClefType(){return this.clefType}set ClefType(t){this.clefType=t}get Line(){return this.line}set Line(t){this.line=t}get OctaveOffset(){return this.octaveOffset}set OctaveOffset(t){this.octaveOffset=t}get ClefPitch(){return this.clefPitch}set ClefPitch(t){this.clefPitch=t}get ReferenceCyPosition(){return this.referenceCyPosition}set ReferenceCyPosition(t){this.referenceCyPosition=t}Equals(t){return this===t?!0:!this||!t?!1:this.clefPitch===t.clefPitch&&this.Line===t.Line}NotEqual(t){return!this.Equals(t)}ToString(){return"ClefType: "+this.clefType}calcParameters(){switch(this.clefType){case Pt.G:this.clefPitch=new Kt(ut.G,1+this.octaveOffset,yt.NONE),this.referenceCyPosition=5-this.line+2;break;case Pt.F:this.clefPitch=new Kt(ut.F,0+this.octaveOffset,yt.NONE),this.referenceCyPosition=5-this.line+1.5;break;case Pt.C:this.clefPitch=new Kt(ut.C,1+this.octaveOffset,yt.NONE),this.referenceCyPosition=5-this.line;break;case Pt.percussion:this.clefPitch=new Kt(ut.C,2,yt.NONE),this.referenceCyPosition=2;break;case Pt.TAB:this.clefPitch=new Kt(ut.G,0,yt.NONE),this.referenceCyPosition=0;break;default:throw new Li("clefType")}}}var Pt=(n=>(n[n.G=0]="G",n[n.F=1]="F",n[n.C=2]="C",n[n.percussion=3]="percussion",n[n.TAB=4]="TAB",n))(Pt||{}),st=(n=>(n[n.None=-1]="None",n[n.Acoustic_Grand_Piano=0]="Acoustic_Grand_Piano",n[n.Bright_Acoustic_Piano=1]="Bright_Acoustic_Piano",n[n.Electric_Grand_Piano=2]="Electric_Grand_Piano",n[n.Honky_tonk_Piano=3]="Honky_tonk_Piano",n[n.Electric_Piano_1=4]="Electric_Piano_1",n[n.Electric_Piano_2=5]="Electric_Piano_2",n[n.Harpsichord=6]="Harpsichord",n[n.Clavinet=7]="Clavinet",n[n.Celesta=8]="Celesta",n[n.Glockenspiel=9]="Glockenspiel",n[n.Music_Box=10]="Music_Box",n[n.Vibraphone=11]="Vibraphone",n[n.Marimba=12]="Marimba",n[n.Xylophone=13]="Xylophone",n[n.Tubular_Bells=14]="Tubular_Bells",n[n.Dulcimer=15]="Dulcimer",n[n.Drawbar_Organ=16]="Drawbar_Organ",n[n.Percussive_Organ=17]="Percussive_Organ",n[n.Rock_Organ=18]="Rock_Organ",n[n.Church_Organ=19]="Church_Organ",n[n.Reed_Organ=20]="Reed_Organ",n[n.Accordion=21]="Accordion",n[n.Harmonica=22]="Harmonica",n[n.Tango_Accordion=23]="Tango_Accordion",n[n.Acoustic_Guitar_nylon=24]="Acoustic_Guitar_nylon",n[n.Acoustic_Guitar_steel=25]="Acoustic_Guitar_steel",n[n.Electric_Guitar_jazz=26]="Electric_Guitar_jazz",n[n.Electric_Guitar_clean=27]="Electric_Guitar_clean",n[n.Electric_Guitar_muted=28]="Electric_Guitar_muted",n[n.Overdriven_Guitar=29]="Overdriven_Guitar",n[n.Distortion_Guitar=30]="Distortion_Guitar",n[n.Guitar_harmonics=31]="Guitar_harmonics",n[n.Acoustic_Bass=32]="Acoustic_Bass",n[n.Electric_Bass_finger=33]="Electric_Bass_finger",n[n.Electric_Bass_pick=34]="Electric_Bass_pick",n[n.Fretless_Bass=35]="Fretless_Bass",n[n.Slap_Bass_1=36]="Slap_Bass_1",n[n.Slap_Bass_2=37]="Slap_Bass_2",n[n.Synth_Bass_1=38]="Synth_Bass_1",n[n.Synth_Bass_2=39]="Synth_Bass_2",n[n.Violin=40]="Violin",n[n.Viola=41]="Viola",n[n.Cello=42]="Cello",n[n.Contrabass=43]="Contrabass",n[n.Tremolo_Strings=44]="Tremolo_Strings",n[n.Pizzicato_Strings=45]="Pizzicato_Strings",n[n.Orchestral_Harp=46]="Orchestral_Harp",n[n.Timpani=47]="Timpani",n[n.String_Ensemble_1=48]="String_Ensemble_1",n[n.String_Ensemble_2=49]="String_Ensemble_2",n[n.Synth_Strings_1=50]="Synth_Strings_1",n[n.Synth_Strings_2=51]="Synth_Strings_2",n[n.Choir_Aahs=52]="Choir_Aahs",n[n.Voice_Oohs=53]="Voice_Oohs",n[n.Synth_Voice=54]="Synth_Voice",n[n.Orchestra_Hit=55]="Orchestra_Hit",n[n.Trumpet=56]="Trumpet",n[n.Trombone=57]="Trombone",n[n.Tuba=58]="Tuba",n[n.Muted_Trumpet=59]="Muted_Trumpet",n[n.French_Horn=60]="French_Horn",n[n.Brass_Section=61]="Brass_Section",n[n.Synth_Brass_1=62]="Synth_Brass_1",n[n.Synth_Brass_2=63]="Synth_Brass_2",n[n.Soprano_Sax=64]="Soprano_Sax",n[n.Alto_Sax=65]="Alto_Sax",n[n.Tenor_Sax=66]="Tenor_Sax",n[n.Baritone_Sax=67]="Baritone_Sax",n[n.Oboe=68]="Oboe",n[n.English_Horn=69]="English_Horn",n[n.Bassoon=70]="Bassoon",n[n.Clarinet=71]="Clarinet",n[n.Piccolo=72]="Piccolo",n[n.Flute=73]="Flute",n[n.Recorder=74]="Recorder",n[n.Pan_Flute=75]="Pan_Flute",n[n.Blown_Bottle=76]="Blown_Bottle",n[n.Shakuhachi=77]="Shakuhachi",n[n.Whistle=78]="Whistle",n[n.Ocarina=79]="Ocarina",n[n.Lead_1_square=80]="Lead_1_square",n[n.Lead_2_sawtooth=81]="Lead_2_sawtooth",n[n.Lead_3_calliope=82]="Lead_3_calliope",n[n.Lead_4_chiff=83]="Lead_4_chiff",n[n.Lead_5_charang=84]="Lead_5_charang",n[n.Lead_6_voice=85]="Lead_6_voice",n[n.Lead_7_fifths=86]="Lead_7_fifths",n[n.Lead_8_bass_lead=87]="Lead_8_bass_lead",n[n.Pad_1_new_age=88]="Pad_1_new_age",n[n.Pad_2_warm=89]="Pad_2_warm",n[n.Pad_3_polysynth=90]="Pad_3_polysynth",n[n.Pad_4_choir=91]="Pad_4_choir",n[n.Pad_5_bowed=92]="Pad_5_bowed",n[n.Pad_6_metallic=93]="Pad_6_metallic",n[n.Pad_7_halo=94]="Pad_7_halo",n[n.Pad_8_sweep=95]="Pad_8_sweep",n[n.FX_1_rain=96]="FX_1_rain",n[n.FX_2_soundtrack=97]="FX_2_soundtrack",n[n.FX_3_crystal=98]="FX_3_crystal",n[n.FX_4_atmosphere=99]="FX_4_atmosphere",n[n.FX_5_brightness=100]="FX_5_brightness",n[n.FX_6_goblins=101]="FX_6_goblins",n[n.FX_7_echoes=102]="FX_7_echoes",n[n.FX_8_scifi=103]="FX_8_scifi",n[n.Sitar=104]="Sitar",n[n.Banjo=105]="Banjo",n[n.Shamisen=106]="Shamisen",n[n.Koto=107]="Koto",n[n.Kalimba=108]="Kalimba",n[n.Bag_pipe=109]="Bag_pipe",n[n.Fiddle=110]="Fiddle",n[n.Shanai=111]="Shanai",n[n.Tinkle_Bell=112]="Tinkle_Bell",n[n.Agogo=113]="Agogo",n[n.Steel_Drums=114]="Steel_Drums",n[n.Woodblock=115]="Woodblock",n[n.Taiko_Drum=116]="Taiko_Drum",n[n.Melodic_Tom=117]="Melodic_Tom",n[n.Synth_Drum=118]="Synth_Drum",n[n.Reverse_Cymbal=119]="Reverse_Cymbal",n[n.Guitar_Fret_Noise=120]="Guitar_Fret_Noise",n[n.Breath_Noise=121]="Breath_Noise",n[n.Seashore=122]="Seashore",n[n.Bird_Tweet=123]="Bird_Tweet",n[n.Telephone_Ring=124]="Telephone_Ring",n[n.Helicopter=125]="Helicopter",n[n.Applause=126]="Applause",n[n.Gunshot=127]="Gunshot",n[n.euphonium=128]="euphonium",n[n.AltoClarinetInEb=200]="AltoClarinetInEb",n[n.TrumpetInBb=201]="TrumpetInBb",n[n.BaritoneSaxophone=202]="BaritoneSaxophone",n[n.TenorSaxophone=203]="TenorSaxophone",n[n.ClarinetInEb=204]="ClarinetInEb",n[n.Euphonium=205]="Euphonium",n[n.Alto_Clarinet=206]="Alto_Clarinet",n[n.Bass_Clarinet=207]="Bass_Clarinet",n[n.Bass_Trombone=208]="Bass_Trombone",n[n.clarinet_in_bb=209]="clarinet_in_bb",n[n.clarinet_in_eb=210]="clarinet_in_eb",n[n.Percussion=135]="Percussion",n))(st||{});const Os=class extends ro{constructor(n=void 0,t=0,e=bi.major){super(n),this.isTransposedBy=0,this.Key=t,this.keyTypeOriginal=t,this.mode=e,this.alteratedNotes=this.calcAlteratedNotes()}static copy(n){const t=new Os(n.parent,n.Key,n.Mode);return t.keyTypeOriginal=n.keyTypeOriginal,t}static getAllPossibleMajorKeyInstructions(){const n=[];for(let t=-7;t<7;t++){const e=new Os(void 0,t,bi.major);n.push(e)}return n}get Key(){return this.keyType}set Key(n){this.keyType=n,this.alteratedNotes=this.calcAlteratedNotes()}get Mode(){return this.mode}set Mode(n){this.mode=n}get AlteratedNotes(){return this.alteratedNotes}calcAlteratedNotes(){const n=[];if(this.keyType>0)for(let t=0;t=0}getAlterationForPitch(n){return this.keyType>0&&this.alteratedNotes.indexOf(n.FundamentalNote)<=this.keyType?yt.SHARP:this.keyType<0&&this.alteratedNotes.indexOf(n.FundamentalNote)<=Math.abs(this.keyType)?yt.FLAT:yt.NONE}ToString(){return"Key: "+this.keyType+this.mode}OperatorEquals(n){const t=this;return t===n?!0:!t||!n?!1:t.Key===n.Key&&t.Mode===n.Mode}OperatorNotEqual(n){return!this.OperatorEquals(n)}};let xe=Os;xe.sharpPositionList=[ut.F,ut.C,ut.G,ut.D,ut.A,ut.E,ut.B];xe.flatPositionList=[ut.B,ut.E,ut.A,ut.D,ut.G,ut.C,ut.F];var bi=(n=>(n[n.major=0]="major",n[n.minor=1]="minor",n[n.none=2]="none",n[n.dorian=3]="dorian",n[n.phrygian=4]="phrygian",n[n.lydian=5]="lydian",n[n.mixolydian=6]="mixolydian",n[n.aeolian=7]="aeolian",n[n.ionian=8]="ionian",n[n.locrian=9]="locrian",n))(bi||{});Array.prototype.last||Object.defineProperty(Array.prototype,"last",{enumerable:!1,value:function(){return this[this.length-1]}});Array.prototype.clear||Object.defineProperty(Array.prototype,"clear",{enumerable:!1,value:function(){this.length=0}});Array.prototype.contains||Object.defineProperty(Array.prototype,"contains",{enumerable:!1,value:function(n){return this.indexOf(n)!==-1}});class Ti{static contains2(t,e){for(let i=0;i{var i,s,r,o;return((s=(i=e.sourceNote.Pitch)==null?void 0:i.getHalfTone())!=null?s:0)-((o=(r=t.sourceNote.Pitch)==null?void 0:r.getHalfTone())!=null?o:0)}),this.notes}sortForVexflow(){return this.notes.sort((t,e)=>{var i,s,r;return((s=(i=t.sourceNote.Pitch)==null?void 0:i.getHalfTone())!=null?s:0)-((r=e.sourceNote.Pitch.getHalfTone())!=null?r:0)}),this.notes}color(){}}class La{constructor(t,e){this.musicPages=[],this.measureList=[],this.verticalGraphicalStaffEntryContainers=[],this.cursors=[],this.leadSheet=!1,this.musicSheet=t,this.numberOfStaves=this.musicSheet.Staves.length,this.calculator=e,this.calculator.initialize(this)}get ParentMusicSheet(){return this.musicSheet}get GetCalculator(){return this.calculator}get JianpuKeySignature(){return this.jianpuKeySignature}set JianpuKeySignature(t){this.jianpuKeySignature=t}get MusicPages(){return this.musicPages}set MusicPages(t){this.musicPages=t}get MeasureList(){return this.measureList}set MeasureList(t){this.measureList=t}get VerticalGraphicalStaffEntryContainers(){return this.verticalGraphicalStaffEntryContainers}set VerticalGraphicalStaffEntryContainers(t){this.verticalGraphicalStaffEntryContainers=t}get Title(){return this.title}set Title(t){this.title=t}get Subtitle(){return this.subtitle}set Subtitle(t){this.subtitle=t}get Composer(){return this.composer}set Composer(t){this.composer=t}get Lyricist(){return this.lyricist}set Lyricist(t){this.lyricist=t}get Cursors(){return this.cursors}get SelectionStartSymbol(){return this.selectionStartSymbol}get SelectionEndSymbol(){return this.selectionEndSymbol}get MinAllowedSystemWidth(){return this.minAllowedSystemWidth}set MinAllowedSystemWidth(t){this.minAllowedSystemWidth=t}get NumberOfStaves(){return this.numberOfStaves}get LeadSheet(){return this.leadSheet}set LeadSheet(t){this.leadSheet=t}static transformRelativeToAbsolutePosition(t){for(let e=0;e=0;i--){const s=this.measureList[i][e];if(s)return s}}findGraphicalStaffEntryFromMeasureList(t,e,i){for(let s=e;s0)return o.staffEntries[0]}}getFirstVisibleMeasuresListFromIndices(t,e){const i=[],s=this.measureList[0].length;for(let r=t;r<=e;r++)for(let o=0;o=0;e--){if(this.verticalGraphicalStaffEntryContainers[e].AbsoluteTimestamp.lt(t)){const i=new pn(this.numberOfStaves,t);return this.verticalGraphicalStaffEntryContainers.splice(e+1,0,i),i}if(this.verticalGraphicalStaffEntryContainers[e].AbsoluteTimestamp.Equals(t))return this.verticalGraphicalStaffEntryContainers[e]}}GetVerticalContainerFromTimestamp(t,e=0){const i=Ti.binarySearch(this.verticalGraphicalStaffEntryContainers,new pn(0,t),pn.compareByTimestamp,e);if(i>=0)return this.verticalGraphicalStaffEntryContainers[i]}GetInterpolatedIndexInVerticalContainers(t){const e=this.verticalGraphicalStaffEntryContainers;let i=0,s=e.length-1,r,o;if(t.lte(e[e.length-1].AbsoluteTimestamp)){for(;s-i>1;){const c=Math.floor((s+i)/2);if(e[i].AbsoluteTimestamp.Equals(t)){s=i;break}else if(e[s].AbsoluteTimestamp.Equals(t)){i=s;break}else{if(e[c].AbsoluteTimestamp.Equals(t))return this.verticalGraphicalStaffEntryContainers.indexOf(e[c]);t.lt(e[c].AbsoluteTimestamp)?s=c:i=c}}if(i===s)return this.verticalGraphicalStaffEntryContainers.indexOf(e[i]);r=e[i].AbsoluteTimestamp,o=e[s].AbsoluteTimestamp}else r=e[e.length-1].AbsoluteTimestamp,o=W.plus(this.getLongestStaffEntryDuration(e.length-1),r),s=e.length;const a=o.RealValue-r.RealValue,l=o.RealValue-t.RealValue,h=s-l/a;return Math.min(h,this.verticalGraphicalStaffEntryContainers.length)}getVisibleStavesIndicesFromSourceMeasure(t){const e=[],i=[];for(let s=0,r=t.length;s{var i;return((i=e.parentStaffEntry)==null?void 0:i.relInMeasureTimestamp)!==void 0})}GetNearestNote(t,e){const i=this.GetNearestVoiceEntry(t);if(!i)return;let s,r=Number.MAX_SAFE_INTEGER;for(const o of i.notes){const a=o.PositionAndShape.AbsolutePosition.y,l=Math.abs(o.PositionAndShape.AbsolutePosition.x-t.x),h=Math.abs(a-t.y);l+ho.PositionAndShape.RelativePosition.x&&(i=o):i=o)}}catch(s){j.info("GraphicalMusicSheet.getStaffEntry",s)}return i}GetPreviousVisibleContainerIndex(t){for(let e=t-1;e>=0;e--){const i=this.verticalGraphicalStaffEntryContainers[e].StaffEntries;for(let s=0,r=i.length;s=0;r--)if(i=this.getStaffEntry(r),i)if(e){if(i.sourceStaffEntry.ParentStaff.ParentInstrument.Visible)return i}else return i}findClosestRightStaffEntry(t,e){let i;const s=Math.max(0,Math.ceil(t));for(let r=s;r{};M.L=(n,t)=>{if(!t)return;const e=Array.prototype.slice.call(t).join(" ");window.console.log(n+": "+e)};M.MakeException=n=>class extends Error{constructor(e,i){super(e),this.name=n,this.message=e,this.data=i}};class Zh{constructor(t,e){this.code=t,this.message=e}toString(){return"[RuntimeError] "+this.code+":"+this.message}}M.RuntimeError=Zh;M.RERR=M.RuntimeError;M.Merge=(n,t)=>{for(const e in t)n[e]=t[e];return n};M.Min=Math.min;M.Max=Math.max;M.forEach=(n,t)=>{for(let e=0;en%t>=t/2?parseInt(n/t,10)*t+t:parseInt(n/t,10)*t;M.MidLine=(n,t)=>{let e=t+(n-t)/2;return e%2>0&&(e=M.RoundN(e*10,5)/10),e};M.SortAndUnique=(n,t,e)=>{if(n.length>1){const i=[];let s;n.sort(t);for(let r=0;r{let e=n.length;for(;e--;)if(n[e]===t)return!0;return!1};M.getCanvasContext=n=>{if(!n)throw new M.RERR("BadArgument","Invalid canvas selector: "+n);const t=document.getElementById(n);if(!(t&&t.getContext))throw new M.RERR("UnsupportedBrowserError","This browser does not support HTML5 Canvas");return t.getContext("2d")};M.drawDot=(n,t,e,i="#55")=>{n.save(),n.setFillStyle(i),n.beginPath(),n.arc(t,e,3,0,Math.PI*2,!0),n.closePath(),n.fill(),n.restore()};M.BM=(n,t)=>{const e=new Date().getTime();t();const i=new Date().getTime()-e;M.L(n+i+"ms")};M.StackTrace=()=>new Error().stack;M.W=(...n)=>{const t=n.join(" ");window.console.log("Warning: ",t,M.StackTrace())};M.Prefix=n=>M.Prefix.prefix+n;M.Prefix.prefix="vf-";class Rt{static GCD(t,e){if(typeof t!="number"||typeof e!="number")throw new M.RERR("BadArgument",`Invalid numbers: ${t}, ${e}`);let i;for(;e!==0;)i=e,e=t%e,t=i;return t}static LCM(t,e){return t*e/Rt.GCD(t,e)}static LCMM(t){if(t.length===0)return 0;if(t.length===1)return t[0];if(t.length===2)return Rt.LCM(t[0],t[1]);{const e=t[0];return t.shift(),Rt.LCM(e,Rt.LCMM(t))}}constructor(t,e){this.set(t,e)}set(t,e){return this.numerator=t===void 0?1:t,this.denominator=e===void 0?1:e,this}value(){return this.numerator/this.denominator}simplify(){let t=this.numerator,e=this.denominator;const i=Rt.GCD(t,e);return t/=i,e/=i,e<0&&(e=-e,t=-t),this.set(t,e)}add(t,e){let i,s;t instanceof Rt?(i=t.numerator,s=t.denominator):(t!==void 0?i=t:i=0,e!==void 0?s=e:s=1);const r=Rt.LCM(this.denominator,s),o=r/this.denominator,a=r/s,l=this.numerator*o+i*a;return this.set(l,r)}subtract(t,e){let i,s;t instanceof Rt?(i=t.numerator,s=t.denominator):(t!==void 0?i=t:i=0,e!==void 0?s=e:s=1);const r=Rt.LCM(this.denominator,s),o=r/this.denominator,a=r/s,l=this.numerator*o-i*a;return this.set(l,r)}multiply(t,e){let i,s;return t instanceof Rt?(i=t.numerator,s=t.denominator):(t!==void 0?i=t:i=1,e!==void 0?s=e:s=1),this.set(this.numerator*i,this.denominator*s)}divide(t,e){let i,s;return t instanceof Rt?(i=t.numerator,s=t.denominator):(t!==void 0?i=t:i=1,e!==void 0?s=e:s=1),this.set(this.numerator*s,this.denominator*i)}equals(t){const e=Rt.__compareA.copy(t).simplify(),i=Rt.__compareB.copy(this).simplify();return e.numerator===i.numerator&&e.denominator===i.denominator}greaterThan(t){const e=Rt.__compareB.copy(this);return e.subtract(t),e.numerator>0}greaterThanEquals(t){const e=Rt.__compareB.copy(this);return e.subtract(t),e.numerator>=0}lessThan(t){return!this.greaterThanEquals(t)}lessThanEquals(t){return!this.greaterThan(t)}clone(){return new Rt(this.numerator,this.denominator)}copy(t){return typeof t=="number"?this.set(t||0,1):this.set(t.numerator,t.denominator)}quotient(){return Math.floor(this.numerator/this.denominator)}fraction(){return this.numerator%this.denominator}abs(){return this.denominator=Math.abs(this.denominator),this.numerator=Math.abs(this.numerator),this}toString(){return this.numerator+"/"+this.denominator}toSimplifiedString(){return Rt.__tmp.copy(this).simplify().toString()}toMixedString(){let t="";const e=this.quotient(),i=Rt.__tmp.copy(this);return e<0?i.abs().fraction():i.fraction(),e!==0?(t+=e,i.numerator!==0&&(t+=" "+i.toSimplifiedString())):i.numerator===0?t="0":t=i.toSimplifiedString(),t}parse(t){const e=t.split("/"),i=parseInt(e[0],10),s=e[1]?parseInt(e[1],10):1;return this.set(i,s)}}Rt.__compareA=new Rt;Rt.__compareB=new Rt;Rt.__tmp=new Rt;const Qh=M.MakeException("RegistryError");function Oo(n,t,e,i,s){n[t][e]||(n[t][e]={}),n[t][e][i]=s}class gi{static get INDEXES(){return["type"]}constructor(){this.clear()}static enableDefaultRegistry(t){gi.defaultRegistry=t}static getDefaultRegistry(){return gi.defaultRegistry}static disableDefaultRegistry(){gi.defaultRegistry=null}clear(){return this.index={id:{},type:{},class:{}},this}updateIndex({id:t,name:e,value:i,oldValue:s}){const r=this.getElementById(t);s!==null&&this.index[e][s]&&delete this.index[e][s][t],i!==null&&Oo(this.index,e,i,r.getAttribute("id"),r)}register(t,e){if(e=e||t.getAttribute("id"),!e)throw new Qh("Can't add element without `id` attribute to registry",t);return t.setAttribute("id",e),Oo(this.index,"id",e,e,t),gi.INDEXES.forEach(i=>{this.updateIndex({id:e,name:i,value:t.getAttribute(i),oldValue:null})}),t.onRegister(this),this}getElementById(t){return this.index.id[t]?this.index.id[t][t]:null}getElementsByAttribute(t,e){const i=this.index[t];return i&&i[e]?Object.keys(i[e]).map(s=>i[e][s]):[]}getElementsByType(t){return this.getElementsByAttribute("type",t)}getElementsByClass(t){return this.getElementsByAttribute("class",t)}onUpdate({id:t,name:e,value:i,oldValue:s}){function r(o,a){return o.filter(l=>l===a).length>0}return r(gi.INDEXES.concat(["id","class"]),e)?(this.updateIndex({id:t,name:e,value:i,oldValue:s}),this):this}}gi.defaultRegistry=null;class he{static newID(){return"auto"+he.ID++}constructor({type:t}={}){this.attrs={id:he.newID(),el:null,type:t||"Base",classes:{}},this.boundingBox=null,this.context=null,this.rendered=!1,gi.getDefaultRegistry()&&gi.getDefaultRegistry().register(this)}setStyle(t){return this.style=t,this}getStyle(){return this.style}applyStyle(t=this.context,e=this.getStyle()){return e?(t.save(),e.shadowColor&&t.setShadowColor(e.shadowColor),e.shadowBlur&&t.setShadowBlur(e.shadowBlur),e.fillStyle&&t.setFillStyle(e.fillStyle),e.strokeStyle&&t.setStrokeStyle(e.strokeStyle),e.lineWidth&&t.setLineWidth(e.lineWidth),this):this}restoreStyle(t=this.context,e=this.getStyle()){return e?(t.restore(),this):this}drawWithStyle(){this.checkContext(),this.applyStyle(),this.draw(),this.restoreStyle()}hasClass(t){return this.attrs.classes[t]===!0}addClass(t){return this.attrs.classes[t]=!0,this.registry&&this.registry.onUpdate({id:this.getAttribute("id"),name:"class",value:t,oldValue:null}),this}removeClass(t){return delete this.attrs.classes[t],this.registry&&this.registry.onUpdate({id:this.getAttribute("id"),name:"class",value:null,oldValue:t}),this}onRegister(t){return this.registry=t,this}isRendered(){return this.rendered}setRendered(t=!0){return this.rendered=t,this}getAttributes(){return this.attrs}getAttribute(t){return this.attrs[t]}setAttribute(t,e){const i=this.attrs.id,s=this.attrs[t];return this.attrs[t]=e,this.registry&&this.registry.onUpdate({id:i,name:t,value:e,oldValue:s}),this}getContext(){return this.context}setContext(t){return this.context=t,this}getBoundingBox(){return this.boundingBox}checkContext(){if(!this.context)throw new M.RERR("NoContext","No rendering context attached to instance");return this.context}}he.ID=1e3;class $h{constructor(t,e,i,s){this.x1=Number.NaN,this.y1=Number.NaN,this.x2=Number.NaN,this.y2=Number.NaN,this.addPoint(t,e),this.addPoint(i,s)}width(){return this.x2-this.x1}height(){return this.y2-this.y1}addPoint(t,e){t!=null&&((isNaN(this.x1)||isNaN(this.x2))&&(this.x1=t,this.x2=t),tthis.x2&&(this.x2=t)),e!=null&&((isNaN(this.y1)||isNaN(this.y2))&&(this.y1=e,this.y2=e),ethis.y2&&(this.y2=e))}addX(t){this.addPoint(t,null)}addY(t){this.addPoint(null,t)}addQuadraticCurve(t,e,i,s,r,o){const a=t+.6666666666666666*(i-t),l=e+2/3*(s-e),h=a+1/3*(r-t),c=l+1/3*(o-e);this.addBezierCurve(t,e,a,l,h,c,r,o)}addBezierCurve(t,e,i,s,r,o,a,l){const h=[t,e],c=[i,s],u=[r,o],f=[a,l];let d;this.addPoint(h[0],h[1]),this.addPoint(f[0],f[1]);const p=(g,m)=>Math.pow(1-g,3)*h[m]+3*Math.pow(1-g,2)*g*c[m]+3*(1-g)*Math.pow(g,2)*u[m]+Math.pow(g,3)*f[m];for(d=0;d<=1;d++){const g=6*h[d]-12*c[d]+6*u[d],m=-3*h[d]+9*c[d]-9*u[d]+3*f[d],S=3*c[d]-3*h[d];if(m===0){if(g===0)continue;const w=-S/g;0{if(!n)throw new M.RERR("BadArgument","Invalid clef: "+n);const t=V.clefProperties.values[n];if(!t)throw new M.RERR("BadArgument","Invalid clef: "+n);return t};V.clefProperties.values={treble:{line_shift:0},bass:{line_shift:6},tenor:{line_shift:4},alto:{line_shift:3},soprano:{line_shift:1},percussion:{line_shift:0},"mezzo-soprano":{line_shift:2},"baritone-c":{line_shift:5},"baritone-f":{line_shift:5},subbass:{line_shift:7},french:{line_shift:-1}};V.keyProperties=(n,t,e)=>{t===void 0&&(t="treble");const i={octave_shift:0};typeof e=="object"&&M.Merge(i,e);const s=n.split("/");if(s.length<2)throw new M.RERR("BadArguments",`Key must have note + octave and an optional glyph: ${n}`);const r=s[0].toUpperCase(),o=V.keyProperties.note_values[r];if(!o)throw new M.RERR("BadArguments","Invalid key name: "+r);o.octave&&(s[1]=o.octave);let a=parseInt(s[1],10);a+=-1*i.octave_shift;let h=(a*7-4*7+o.index)/2;h+=V.clefProperties(t).line_shift;let c=0;h<=0&&h*2%2===0&&(c=1),h>=6&&h*2%2===0&&(c=-1);const u=typeof o.int_val!="undefined"?a*12+o.int_val:null,f=o.code,d=o.shift_right;let p={};if(s.length>2&&s[2]){const g=s[2].toUpperCase();p=V.keyProperties.customNoteHeads[g]||{}}return be({key:r,octave:a,line:h,int_value:u,accidental:o.accidental,code:f,stroke:c,shift_right:d,displaced:!1},p)};V.keyProperties.note_values={C:{index:0,int_val:0,accidental:null},CN:{index:0,int_val:0,accidental:"n"},"C#":{index:0,int_val:1,accidental:"#"},"C##":{index:0,int_val:2,accidental:"##"},CB:{index:0,int_val:-1,accidental:"b"},CBB:{index:0,int_val:-2,accidental:"bb"},D:{index:1,int_val:2,accidental:null},DN:{index:1,int_val:2,accidental:"n"},"D#":{index:1,int_val:3,accidental:"#"},"D##":{index:1,int_val:4,accidental:"##"},DB:{index:1,int_val:1,accidental:"b"},DBB:{index:1,int_val:0,accidental:"bb"},E:{index:2,int_val:4,accidental:null},EN:{index:2,int_val:4,accidental:"n"},"E#":{index:2,int_val:5,accidental:"#"},"E##":{index:2,int_val:6,accidental:"##"},EB:{index:2,int_val:3,accidental:"b"},EBB:{index:2,int_val:2,accidental:"bb"},F:{index:3,int_val:5,accidental:null},FN:{index:3,int_val:5,accidental:"n"},"F#":{index:3,int_val:6,accidental:"#"},"F##":{index:3,int_val:7,accidental:"##"},FB:{index:3,int_val:4,accidental:"b"},FBB:{index:3,int_val:3,accidental:"bb"},G:{index:4,int_val:7,accidental:null},GN:{index:4,int_val:7,accidental:"n"},"G#":{index:4,int_val:8,accidental:"#"},"G##":{index:4,int_val:9,accidental:"##"},GB:{index:4,int_val:6,accidental:"b"},GBB:{index:4,int_val:5,accidental:"bb"},A:{index:5,int_val:9,accidental:null},AN:{index:5,int_val:9,accidental:"n"},"A#":{index:5,int_val:10,accidental:"#"},"A##":{index:5,int_val:11,accidental:"##"},AB:{index:5,int_val:8,accidental:"b"},ABB:{index:5,int_val:7,accidental:"bb"},B:{index:6,int_val:11,accidental:null},BN:{index:6,int_val:11,accidental:"n"},"B#":{index:6,int_val:12,accidental:"#"},"B##":{index:6,int_val:13,accidental:"##"},BB:{index:6,int_val:10,accidental:"b"},BBB:{index:6,int_val:9,accidental:"bb"},R:{index:6,int_val:9,rest:!0},X:{index:6,accidental:"",octave:4,code:"v3e",shift_right:5.5}};V.keyProperties.customNoteHeads={D0:{code:"v27",shift_right:0,stem_up_x_offset:0,stem_down_x_offset:0,stem_up_y_offset:-1,stem_down_y_offset:0},D1:{code:"v2d",shift_right:-.5},D2:{code:"v22",shift_right:-.5},D3:{code:"v70",shift_right:-.5},T0:{code:"v49",shift_right:-2,stem_up_y_offset:-4,stem_down_y_offset:4},T1:{code:"v93",shift_right:.5,stem_up_y_offset:-4,stem_down_y_offset:4},T2:{code:"v40",shift_right:.5,stem_up_y_offset:-4,stem_down_y_offset:4},T3:{code:"v7d",shift_right:.5,stem_up_y_offset:-4,stem_down_y_offset:4},X0:{code:"v92",stem_up_x_offset:-2,stem_down_x_offset:0,stem_up_y_offset:4,stem_down_y_offset:4},X1:{code:"v95",shift_right:-.5,stem_up_y_offset:4,stem_down_y_offset:4},X2:{code:"v3e",shift_right:.5,stem_up_y_offset:4,stem_down_y_offset:4},X3:{code:"v3b",shift_right:0,stem_up_x_offset:-1.2,stem_down_x_offset:0,stem_up_y_offset:-1,stem_down_y_offset:2},S1:{code:"vd3",shift_right:0},S2:{code:"vd2",shift_right:0},R1:{code:"vd5",shift_right:0},R2:{code:"vd4",shift_right:0}};V.integerToNote=n=>{if(typeof n=="undefined")throw new M.RERR("BadArguments","Undefined integer for integerToNote");if(n<-2)throw new M.RERR("BadArguments",`integerToNote requires integer > -2: ${n}`);const t=V.integerToNote.table[n];if(!t)throw new M.RERR("BadArguments",`Unknown note value for integer: ${n}`);return t};V.integerToNote.table={0:"C",1:"C#",2:"D",3:"D#",4:"E",5:"F",6:"F#",7:"G",8:"G#",9:"A",10:"A#",11:"B"};V.tabToGlyph=(n,t=1)=>{let e=null,i=0,s=0;if(n.toString().toUpperCase()==="X"){const r=new xt("v7f",V.DEFAULT_TABLATURE_FONT_SCALE).getMetrics();e="v7f",i=r.width,s=-r.height/2}else i=V.textWidth(n.toString());return{text:n,code:e,getWidth:()=>i*t,shift_y:s}};V.textWidth=n=>7*n.toString().length;V.articulationCodes=n=>V.articulationCodes.articulations[n];V.articulationCodes.articulations={"a.":{code:"v23",between_lines:!0},av:{code:"v28",between_lines:!0},"a>":{code:"v42",between_lines:!0},"a-":{code:"v25",between_lines:!0},"a^":{code:"va",between_lines:!1},"a+":{code:"v8b",between_lines:!1},ao:{code:"v94",between_lines:!1},ah:{code:"vb9",between_lines:!1},"a@a":{code:"v43",between_lines:!1},"a@u":{code:"v5b",between_lines:!1},"a|":{code:"v75",between_lines:!1},am:{code:"v97",between_lines:!1},"a,":{code:"vb3",between_lines:!1}};V.accidentalCodes=n=>V.accidentalCodes.accidentals[n];V.accidentalCodes.accidentals={"#":{code:"v18",parenRightPaddingAdjustment:-1},"##":{code:"v7f",parenRightPaddingAdjustment:-1},b:{code:"v44",parenRightPaddingAdjustment:-2},bb:{code:"v26",parenRightPaddingAdjustment:-2},n:{code:"v4e",parenRightPaddingAdjustment:-1},"{":{code:"v9c",parenRightPaddingAdjustment:-1},"}":{code:"v84",parenRightPaddingAdjustment:-1},db:{code:"v9e",parenRightPaddingAdjustment:-1},d:{code:"vab",parenRightPaddingAdjustment:0},bbs:{code:"v90",parenRightPaddingAdjustment:-1},"++":{code:"v51",parenRightPaddingAdjustment:-1},"+":{code:"v78",parenRightPaddingAdjustment:-1},"+-":{code:"v8d",parenRightPaddingAdjustment:-1},"++-":{code:"v7a",parenRightPaddingAdjustment:-1},bs:{code:"vb7",parenRightPaddingAdjustment:-1},bss:{code:"v39",parenRightPaddingAdjustment:-1},o:{code:"vd0",parenRightPaddingAdjustment:-1},k:{code:"vd1",parenRightPaddingAdjustment:-1},ashs:{code:"vd6",parenRightPaddingAdjustment:-1},afhf:{code:"vd7",parenRightPaddingAdjustment:-1}};V.accidentalColumnsTable={1:{a:[1],b:[1]},2:{a:[1,2]},3:{a:[1,3,2],b:[1,2,1],second_on_bottom:[1,2,3]},4:{a:[1,3,4,2],b:[1,2,3,1],spaced_out_tetrachord:[1,2,1,2]},5:{a:[1,3,5,4,2],b:[1,2,4,3,1],spaced_out_pentachord:[1,2,3,2,1],very_spaced_out_pentachord:[1,2,1,2,1]},6:{a:[1,3,5,6,4,2],b:[1,2,4,5,3,1],spaced_out_hexachord:[1,3,2,1,3,2],very_spaced_out_hexachord:[1,2,1,2,1,2]}};V.ornamentCodes=n=>V.ornamentCodes.ornaments[n];V.ornamentCodes.ornaments={mordent:{code:"v1e"},mordent_inverted:{code:"v45"},turn:{code:"v72"},turn_inverted:{code:"v33"},tr:{code:"v1f"},upprall:{code:"v60"},downprall:{code:"vb4"},prallup:{code:"v6d"},pralldown:{code:"v2c"},upmordent:{code:"v29"},downmordent:{code:"v68"},lineprall:{code:"v20"},prallprall:{code:"v86"}};V.keySignature=n=>{const t=V.keySignature.keySpecs[n];if(!t)throw new M.RERR("BadKeySignature",`Bad key signature spec: '${n}'`);if(!t.acc)return[];const e=V.keySignature.accidentalList(t.acc),i=[];for(let s=0;s({b:[2,.5,2.5,1,3,1.5,3.5],"#":[0,1.5,-.5,1,2.5,.5,2]})[n];V.parseNoteDurationString=n=>{if(typeof n!="string")return null;const e=/(\d*\/?\d+|[a-z])(d*)([nrhms]|$)/.exec(n);if(!e)return null;const i=e[1],s=e[2].length;let r=e[3];return r.length===0&&(r="n"),{duration:i,dots:s,type:r}};V.parseNoteStruct=n=>{const t=n.duration,e=V.parseNoteDurationString(t);if(!e)return null;let i=V.durationToTicks(e.duration);if(i==null)return null;let s=n.type;const r=[];if(s){if(!V.getGlyphProps.validTypes[s])return null}else s=e.type||"n",n.keys!==void 0&&n.keys.forEach((l,h)=>{const c=l.split("/");c&&c.length===3&&(r[h]=c[2])});const o=n.dots?n.dots:e.dots;if(typeof o!="number")return null;let a=i;for(let l=0;l{const t=V.durationAliases[n];if(t!==void 0&&(n=t),V.durationToTicks.durations[n]===void 0)throw new M.RERR("BadArguments",`The provided duration is not valid: ${n}`);return n};V.durationToFraction=n=>new Rt().parse(V.sanitizeDuration(n));V.durationToNumber=n=>V.durationToFraction(n).value();V.durationToTicks=n=>{n=V.sanitizeDuration(n);const t=V.durationToTicks.durations[n];return t===void 0?null:t};V.durationToTicks.durations={"1/2":V.RESOLUTION*2,"1":V.RESOLUTION/1,"2":V.RESOLUTION/2,"4":V.RESOLUTION/4,"8":V.RESOLUTION/8,"16":V.RESOLUTION/16,"32":V.RESOLUTION/32,"64":V.RESOLUTION/64,"128":V.RESOLUTION/128,"256":V.RESOLUTION/256};V.durationAliases={w:"1",h:"2",q:"4",b:"256"};V.getGlyphProps=(n,t)=>{n=V.sanitizeDuration(n);const e=V.getGlyphProps.duration_codes[n];if(e===void 0)return null;t||(t="n");let i=e.type[t];if(i===void 0){const s=V.keyProperties.customNoteHeads[t.toUpperCase()];if(s===void 0)return null;i=be({code_head:s.code},s)}return be(be({},e.common),i)};V.getGlyphProps.validTypes={n:{name:"note"},r:{name:"rest"},h:{name:"harmonic"},m:{name:"muted"},s:{name:"slash"}};V.getGlyphProps.duration_codes={"1/2":{common:{getWidth(n=V.DEFAULT_NOTATION_FONT_SCALE){return new xt(this.code_head||"v53",n).getMetrics().width},stem:!1,stem_offset:0,flag:!1,stem_up_extension:-V.STEM_HEIGHT,stem_down_extension:-V.STEM_HEIGHT,tabnote_stem_up_extension:-V.STEM_HEIGHT,tabnote_stem_down_extension:-V.STEM_HEIGHT,dot_shiftY:0,line_above:0,line_below:0},type:{n:{code_head:"v53"},h:{code_head:"v59"},m:{code_head:"vf",stem_offset:0},r:{code_head:"v31",rest:!0,position:"B/5",dot_shiftY:.5},s:{getWidth:()=>V.SLASH_NOTEHEAD_WIDTH,position:"B/4"}}},"1":{common:{getWidth(n=V.DEFAULT_NOTATION_FONT_SCALE){return new xt(this.code_head||"v1d",n).getMetrics().width},stem:!1,stem_offset:0,flag:!1,stem_up_extension:-V.STEM_HEIGHT,stem_down_extension:-V.STEM_HEIGHT,tabnote_stem_up_extension:-V.STEM_HEIGHT,tabnote_stem_down_extension:-V.STEM_HEIGHT,dot_shiftY:0,line_above:0,line_below:0},type:{n:{code_head:"v1d"},h:{code_head:"v46"},m:{code_head:"v92",stem_offset:-3},r:{code_head:"v5c",rest:!0,position:"D/5",dot_shiftY:.5},s:{getWidth:()=>V.SLASH_NOTEHEAD_WIDTH,position:"B/4"}}},"2":{common:{getWidth(n=V.DEFAULT_NOTATION_FONT_SCALE){return new xt(this.code_head||"v81",n).getMetrics().width},stem:!0,stem_offset:0,flag:!1,stem_up_extension:0,stem_down_extension:0,tabnote_stem_up_extension:0,tabnote_stem_down_extension:0,dot_shiftY:0,line_above:0,line_below:0},type:{n:{code_head:"v81"},h:{code_head:"v2d"},m:{code_head:"v95",stem_offset:-3},r:{code_head:"vc",stem:!1,rest:!0,position:"B/4",dot_shiftY:-.5},s:{getWidth:()=>V.SLASH_NOTEHEAD_WIDTH,position:"B/4"}}},"4":{common:{getWidth(n=V.DEFAULT_NOTATION_FONT_SCALE){return new xt(this.code_head||"vb",n).getMetrics().width},stem:!0,stem_offset:0,flag:!1,stem_up_extension:0,stem_down_extension:0,tabnote_stem_up_extension:0,tabnote_stem_down_extension:0,dot_shiftY:0,line_above:0,line_below:0},type:{n:{code_head:"vb"},h:{code_head:"v22"},m:{code_head:"v3e",stem_offset:-3},r:{code_head:"v7c",stem:!1,rest:!0,position:"B/4",dot_shiftY:-.5,line_above:1.5,line_below:1.5},s:{getWidth:()=>V.SLASH_NOTEHEAD_WIDTH,position:"B/4"}}},"8":{common:{getWidth(n=V.DEFAULT_NOTATION_FONT_SCALE){return new xt(this.code_head||"vb",n).getMetrics().width},stem:!0,stem_offset:0,flag:!0,beam_count:1,code_flag_upstem:"v54",code_flag_downstem:"v9a",stem_up_extension:0,stem_down_extension:0,tabnote_stem_up_extension:0,tabnote_stem_down_extension:0,dot_shiftY:0,line_above:0,line_below:0},type:{n:{code_head:"vb"},h:{code_head:"v22"},m:{code_head:"v3e"},r:{code_head:"va5",stem:!1,flag:!1,rest:!0,position:"B/4",dot_shiftY:-.5,line_above:1,line_below:1},s:{getWidth:()=>V.SLASH_NOTEHEAD_WIDTH,position:"B/4"}}},"16":{common:{beam_count:2,getWidth(n=V.DEFAULT_NOTATION_FONT_SCALE){return new xt(this.code_head||"vb",n).getMetrics().width},stem:!0,stem_offset:0,flag:!0,code_flag_upstem:"v3f",code_flag_downstem:"v8f",stem_up_extension:0,stem_down_extension:0,tabnote_stem_up_extension:0,tabnote_stem_down_extension:0,dot_shiftY:0,line_above:0,line_below:0},type:{n:{code_head:"vb"},h:{code_head:"v22"},m:{code_head:"v3e"},r:{code_head:"v3c",stem:!1,flag:!1,rest:!0,position:"B/4",dot_shiftY:-.5,line_above:1,line_below:2},s:{getWidth:()=>V.SLASH_NOTEHEAD_WIDTH,position:"B/4"}}},"32":{common:{beam_count:3,getWidth(n=V.DEFAULT_NOTATION_FONT_SCALE){return new xt(this.code_head||"vb",n).getMetrics().width},stem:!0,stem_offset:0,flag:!0,code_flag_upstem:"v47",code_flag_downstem:"v2a",stem_up_extension:9,stem_down_extension:9,tabnote_stem_up_extension:8,tabnote_stem_down_extension:5,dot_shiftY:0,line_above:0,line_below:0},type:{n:{code_head:"vb"},h:{code_head:"v22"},m:{code_head:"v3e"},r:{code_head:"v55",stem:!1,flag:!1,rest:!0,position:"B/4",dot_shiftY:-1.5,line_above:2,line_below:2},s:{getWidth:()=>V.SLASH_NOTEHEAD_WIDTH,position:"B/4"}}},"64":{common:{beam_count:4,getWidth(n=V.DEFAULT_NOTATION_FONT_SCALE){return new xt(this.code_head||"vb",n).getMetrics().width},stem:!0,stem_offset:0,flag:!0,code_flag_upstem:"va9",code_flag_downstem:"v58",stem_up_extension:13,stem_down_extension:13,tabnote_stem_up_extension:12,tabnote_stem_down_extension:9,dot_shiftY:0,line_above:0,line_below:0},type:{n:{code_head:"vb"},h:{code_head:"v22"},m:{code_head:"v3e"},r:{code_head:"v38",stem:!1,flag:!1,rest:!0,position:"B/4",dot_shiftY:-1.5,line_above:2,line_below:3},s:{getWidth:()=>V.SLASH_NOTEHEAD_WIDTH,position:"B/4"}}},"128":{common:{beam_count:5,getWidth(n=V.DEFAULT_NOTATION_FONT_SCALE){return new xt(this.code_head||"vb",n).getMetrics().width},stem:!0,stem_offset:0,flag:!0,code_flag_upstem:"v9b",code_flag_downstem:"v30",stem_up_extension:22,stem_down_extension:22,tabnote_stem_up_extension:21,tabnote_stem_down_extension:18,dot_shiftY:0,line_above:0,line_below:0},type:{n:{code_head:"vb"},h:{code_head:"v22"},m:{code_head:"v3e"},r:{code_head:"vaa",stem:!1,flag:!1,rest:!0,position:"B/4",dot_shiftY:1.5,line_above:3,line_below:3},s:{getWidth:()=>V.SLASH_NOTEHEAD_WIDTH,position:"B/4"}}}};V.smufl={};V.smufl.to_code_points={bracketTop:"v1b",bracketBottom:"v10",barlineTick:"v6f",segno:"v8c",coda:"v4d",gClef:"v83",cClef:"vad",fClef:"v79",unpitchedPercussionClef1:"v59","6stringTabClef":"v2f",timeSig0:"v0",timeSig1:"v1",timeSig2:"v2",timeSig3:"v3",timeSig4:"v4",timeSig5:"v5",timeSig6:"v6",timeSig7:"v7",timeSig8:"v8",timeSig9:"v9",timeSigCommon:"v41",timeSigCutCommon:"vb6",noteheadDoubleWhole:"v53",noteheadWhole:"v1d",noteheadHalf:"v81",noteheadBlack:"vb",noteheadXWhole:"v92",noteheadXHalf:"v95",noteheadXBlack:"v3e",noteheadCircleX:"v3b",noteheadTriangleUpWhole:"v49",noteheadTriangleUpHalf:"v93",noteheadTriangleUpBlack:"v40",noteheadDiamondWhole:"v46",noteheadDiamondHalf:"v2d",noteheadDiamondBlack:"v22",augmentationDot:"v23",tremolo1:"v74",flag8thUp:"v54",flag8thDown:"v9a",flag16thUp:"v3f",flag16thDown:"v8f",flag32ndUp:"v47",flag32ndDown:"v2a",flag64thUp:"va9",flag64thDown:"v58",flag128thUp:"v9b",flag128thDown:"v30",accidentalFlat:"v44",accidentalNatural:"v4e",accidentalSharp:"v18",accidentalDoubleSharp:"v7f",accidentalDoubleFlat:"v26",accidentalParensLeft:"v9c",accidentalParensRight:"v84",accidentalQuarterToneFlatStein:"vab",accidentalThreeQuarterTonesFlatZimmermann:"v9e",accidentalQuarterToneSharpStein:"v78",accidentalThreeQuarterTonesSharpStein:"v51",accidentalBuyukMucennebFlat:"v39",accidentalBakiyeFlat:"vb7",accidentalKomaSharp:"v51",accidentalKucukMucennebSharp:"v8d",accidentalKoron:"vd1",accidentalSori:"vd0",articAccentAbove:"v42",articAccentBelow:"v42",articTenutoAbove:"v25",articTenutoBelow:"v25",articStaccatoAbove:"v23",articStaccatoBelow:"v23",articStaccatissimoAbove:"v28",articMarcatoAbove:"va",fermataAbove:"v43",fermataBelow:"v5b",breathMarkComma:"v6c",breathMarkUpbow:"v8a",caesura:"v34",caesuraCurved:"v4b",restMaxima:"v59",restDoubleWhole:"v31",restWhole:"v5c",restHalf:"vc",restQuarter:"v7c",rest8th:"va5",rest16th:"v3c",rest32nd:"v55",rest64th:"v38",rest128th:"vaa",dynamicPiano:"vbf",dynamicMezzo:"v62",dynamicForte:"vba",dynamicRinforzando:"vba",dynamicSforzando:"v4a",dynamicZ:"v80",ornamentTrill:"v1f",ornamentTurn:"v72",ornamentTurnSlash:"v33",ornamentMordent:"v45",ornamentMordentInverted:"v1e",ornamentTremblement:"v86",ornamentPrecompAppoggTrill:"v20",ornamentPrecompSlideTrillDAnglebert:"v60",ornamentPrecompSlideTrillBach:"v29",ornamentPrecompTrillSuffixDandrieu:"v6d",ornamentPrecompDoubleCadenceUpperPrefix:"vb4",ornamentPrecompDoubleCadenceUpperPrefixTurn:"v68",ornamentPrecompTrillLowerSuffix:"v2c",stringsDownBow:"v94",stringsUpBow:"v75",stringsHarmonic:"vb9",pluckedSnapPizzicatoAbove:"v94",pluckedLeftHandPizzicato:"v8b",keyboardPedalPed:"v36",keyboardPedalUp:"v5d",pictChokeCymbal:"vb3",wiggleArpeggiatoUp:"va3",arrowheadBlackUp:"vc3",arrowheadBlackDown:"v52"};V.TIME4_4={num_beats:4,beat_value:4,resolution:V.RESOLUTION};class gs{static get WIDTH(){return 600}static get HEIGHT(){return 400}static get CANVAS_BROWSER_SIZE_LIMIT(){return 32767}static SanitizeCanvasDims(t,e){return Math.max(t,e)>this.CANVAS_BROWSER_SIZE_LIMIT&&(M.W("Canvas dimensions exceed browser limit. Cropping to "+this.CANVAS_BROWSER_SIZE_LIMIT),t>this.CANVAS_BROWSER_SIZE_LIMIT&&(t=this.CANVAS_BROWSER_SIZE_LIMIT),e>this.CANVAS_BROWSER_SIZE_LIMIT&&(e=this.CANVAS_BROWSER_SIZE_LIMIT)),[t,e]}constructor(t){this.vexFlowCanvasContext=t,t.canvas?this.canvas=t.canvas:this.canvas={width:gs.WIDTH,height:gs.HEIGHT}}clear(){this.vexFlowCanvasContext.clearRect(0,0,this.canvas.width,this.canvas.height)}openGroup(){}closeGroup(){}add(){}setFont(t,e,i){return this.vexFlowCanvasContext.font=(i||"")+" "+e+"pt "+t,this}setRawFont(t){return this.vexFlowCanvasContext.font=t,this}setFillStyle(t){return this.vexFlowCanvasContext.fillStyle=t,this}setBackgroundFillStyle(t){return this.background_fillStyle=t,this}setStrokeStyle(t){return this.vexFlowCanvasContext.strokeStyle=t,this}setShadowColor(t){return this.vexFlowCanvasContext.shadowColor=t,this}setShadowBlur(t){return this.vexFlowCanvasContext.shadowBlur=t,this}setLineWidth(t){return this.vexFlowCanvasContext.lineWidth=t,this}setLineCap(t){return this.vexFlowCanvasContext.lineCap=t,this}setLineDash(t){return this.vexFlowCanvasContext.lineDash=t,this}scale(t,e){return this.vexFlowCanvasContext.scale(parseFloat(t),parseFloat(e))}resize(t,e){return[t,e]=this.SanitizeCanvasDims(parseInt(t,10),parseInt(e,10)),this.vexFlowCanvasContext.resize(t,e)}rect(t,e,i,s){return this.vexFlowCanvasContext.rect(t,e,i,s)}fillRect(t,e,i,s){return this.vexFlowCanvasContext.fillRect(t,e,i,s)}clearRect(t,e,i,s){return this.vexFlowCanvasContext.clearRect(t,e,i,s)}beginPath(){return this.vexFlowCanvasContext.beginPath()}moveTo(t,e){return this.vexFlowCanvasContext.moveTo(t,e)}lineTo(t,e){return this.vexFlowCanvasContext.lineTo(t,e)}bezierCurveTo(t,e,i,s,r,o){return this.vexFlowCanvasContext.bezierCurveTo(t,e,i,s,r,o)}quadraticCurveTo(t,e,i,s){return this.vexFlowCanvasContext.quadraticCurveTo(t,e,i,s)}arc(t,e,i,s,r,o){return this.vexFlowCanvasContext.arc(t,e,i,s,r,o)}glow(){return this.vexFlowCanvasContext.glow()}fill(){return this.vexFlowCanvasContext.fill()}stroke(){return this.vexFlowCanvasContext.stroke()}closePath(){return this.vexFlowCanvasContext.closePath()}measureText(t){return this.vexFlowCanvasContext.measureText(t)}fillText(t,e,i){return this.vexFlowCanvasContext.fillText(t,e,i)}save(){return this.vexFlowCanvasContext.save()}restore(){return this.vexFlowCanvasContext.restore()}}class tc{constructor(t){this.element=t,this.paper=Raphael(t),this.path="",this.pen={x:0,y:0},this.lineWidth=1,this.state={scale:{x:1,y:1},font_family:"Arial",font_size:8,font_weight:800},this.attributes={"stroke-width":.3,fill:"black",stroke:"black",font:"10pt Arial"},this.background_attributes={"stroke-width":0,fill:"white",stroke:"white",font:"10pt Arial"},this.shadow_attributes={width:0,color:"black"},this.state_stack=[]}openGroup(){}closeGroup(){}add(){}setFont(t,e,i){return this.state.font_family=t,this.state.font_size=e,this.state.font_weight=i,this.attributes.font=(this.state.font_weight||"")+" "+this.state.font_size*this.state.scale.x+"pt "+this.state.font_family,this}setRawFont(t){return this.attributes.font=t,this}setFillStyle(t){return this.attributes.fill=t,this}setBackgroundFillStyle(t){return this.background_attributes.fill=t,this.background_attributes.stroke=t,this}setStrokeStyle(t){return this.attributes.stroke=t,this}setShadowColor(t){return this.shadow_attributes.color=t,this}setShadowBlur(t){return this.shadow_attributes.width=t,this}setLineWidth(t){this.attributes["stroke-width"]=t,this.lineWidth=t}setLineDash(){return this}setLineCap(){return this}scale(t,e){return this.state.scale={x:t,y:e},this.attributes.transform="S"+t+","+e+",0,0",this.attributes.scale=t+","+e+",0,0",this.attributes.font=this.state.font_size*this.state.scale.x+"pt "+this.state.font_family,this.background_attributes.transform="S"+t+","+e+",0,0",this.background_attributes.font=this.state.font_size*this.state.scale.x+"pt "+this.state.font_family,this}clear(){this.paper.clear()}resize(t,e){return this.element.style.width=t,this.paper.setSize(t,e),this}setViewBox(t){this.paper.canvas.setAttribute("viewBox",t)}rect(t,e,i,s){return s<0&&(e+=s,s=-s),this.paper.rect(t,e,i-.5,s-.5).attr(this.attributes).attr("fill","none").attr("stroke-width",this.lineWidth),this}fillRect(t,e,i,s){return s<0&&(e+=s,s=-s),this.paper.rect(t,e,i-.5,s-.5).attr(this.attributes),this}clearRect(t,e,i,s){return s<0&&(e+=s,s=-s),this.paper.rect(t,e,i-.5,s-.5).attr(this.background_attributes),this}beginPath(){return this.path="",this.pen.x=0,this.pen.y=0,this}moveTo(t,e){return this.path+="M"+t+","+e,this.pen.x=t,this.pen.y=e,this}lineTo(t,e){return this.path+="L"+t+","+e,this.pen.x=t,this.pen.y=e,this}bezierCurveTo(t,e,i,s,r,o){return this.path+="C"+t+","+e+","+i+","+s+","+r+","+o,this.pen.x=r,this.pen.y=o,this}quadraticCurveTo(t,e,i,s){return this.path+="Q"+t+","+e+","+i+","+s,this.pen.x=i,this.pen.y=s,this}arc(t,e,i,s,r,o){function a(h){for(;h<0;)h+=Math.PI*2;for(;h>Math.PI*2;)h-=Math.PI*2;return h}if(s=a(s),r=a(r),s>r){const h=s;s=r,r=h,o=!o}const l=r-s;return l>Math.PI?(this.arcHelper(t,e,i,s,s+l/2,o),this.arcHelper(t,e,i,s+l/2,r,o)):this.arcHelper(t,e,i,s,r,o),this}arcHelper(t,e,i,s,r,o){const a=t+i*Math.cos(s),l=e+i*Math.sin(s),h=t+i*Math.cos(r),c=e+i*Math.sin(r);let u=0,f=0;o?(f=1,r-sMath.PI&&(u=1),this.path+="M"+a+","+l+",A"+i+","+i+",0,"+u+","+f+","+h+","+c+"M"+this.pen.x+","+this.pen.y}glow(){const t=this.paper.set();if(this.shadow_attributes.width>0){const e=this.shadow_attributes,i=e.width/2;for(let s=1;s<=i;s++)t.push(this.paper.path(this.path).attr({stroke:e.color,"stroke-linejoin":"round","stroke-linecap":"round","stroke-width":+(e.width/i*s).toFixed(3),opacity:+((e.opacity||.3)/i).toFixed(3),transform:this.attributes.transform,scale:this.attributes.scale}))}return t}fill(){const t=this.paper.path(this.path).attr(this.attributes).attr("stroke-width",0);return this.glow(t),this}stroke(){const t=this.lineWidth*(this.state.scale.x+this.state.scale.y)/2,e=this.paper.path(this.path).attr(this.attributes).attr("fill","none").attr("stroke-width",t);return this.glow(e),this}closePath(){return this.path+="Z",this}measureText(t){const e=this.paper.text(0,0,t).attr(this.attributes).attr("fill","none").attr("stroke","none"),i=e.getBBox();return e.remove(),{width:i.width,height:i.height}}fillText(t,e,i){return this.paper.text(e+this.measureText(t).width/2,i-this.state.font_size/(2.25*this.state.scale.y),t).attr(this.attributes),this}save(){return this.state_stack.push({state:{font_family:this.state.font_family},attributes:{font:this.attributes.font,fill:this.attributes.fill,stroke:this.attributes.stroke,"stroke-width":this.attributes["stroke-width"]},shadow_attributes:{width:this.shadow_attributes.width,color:this.shadow_attributes.color}}),this}restore(){const t=this.state_stack.pop();return this.state.font_family=t.state.font_family,this.attributes.font=t.attributes.font,this.attributes.fill=t.attributes.fill,this.attributes.stroke=t.attributes.stroke,this.attributes["stroke-width"]=t.attributes["stroke-width"],this.shadow_attributes.width=t.shadow_attributes.width,this.shadow_attributes.color=t.shadow_attributes.color,this}}const Er={path:{x:!0,y:!0,width:!0,height:!0},rect:{},text:{width:!0,height:!0}};{const n={"font-family":!0,"font-weight":!0,"font-style":!0,"font-size":!0};M.Merge(Er.rect,n),M.Merge(Er.path,n)}class ec{constructor(t){this.element=t,this.svgNS="http://www.w3.org/2000/svg";const e=this.create("svg");this.element.appendChild(e),this.svg=e,this.groups=[this.svg],this.parent=this.svg,this.path="",this.pen={x:NaN,y:NaN},this.lineWidth=1,this.state={scale:{x:1,y:1},"font-family":"Arial","font-size":"8pt","font-weight":"normal"},this.attributes={"stroke-width":.3,fill:"black",stroke:"black","stroke-dasharray":"none","font-family":"Arial","font-size":"10pt","font-weight":"normal","font-style":"normal"},this.background_attributes={"stroke-width":0,fill:"white",stroke:"white","stroke-dasharray":"none","font-family":"Arial","font-size":"10pt","font-weight":"normal","font-style":"normal"},this.shadow_attributes={width:0,color:"black"},this.state_stack=[],this.iePolyfill()}create(t){return document.createElementNS(this.svgNS,t)}openGroup(t,e,i){const s=this.create("g");return this.groups.push(s),this.parent.appendChild(s),this.parent=s,t&&s.setAttribute("class",M.Prefix(t)),e&&s.setAttribute("id",M.Prefix(e)),i&&i.pointerBBox&&s.setAttribute("pointer-events","bounding-box"),s}closeGroup(){this.groups.pop(),this.parent=this.groups[this.groups.length-1]}add(t){this.parent.appendChild(t)}iePolyfill(){typeof navigator!="undefined"&&(this.ie=/MSIE 9/i.test(navigator.userAgent)||/MSIE 10/i.test(navigator.userAgent)||/rv:11\.0/i.test(navigator.userAgent)||/Trident/i.test(navigator.userAgent))}setFont(t,e,i){let s=!1,r=!1,o="normal";typeof i=="string"&&(i.indexOf("italic")!==-1&&(i=i.replace(/italic/g,""),r=!0),i.indexOf("bold")!==-1&&(i=i.replace(/bold/g,""),s=!0),i=i.replace(/ /g,"")),i=s?"bold":i,i=typeof i=="undefined"||i===""?"normal":i,o=r?"italic":o;const a={"font-family":t,"font-size":e+"pt","font-weight":i,"font-style":o};return this.fontSize=Number(e),M.Merge(this.attributes,a),M.Merge(this.state,a),this}setRawFont(t){t=t.trim();const e=t.split(" ");return this.attributes["font-family"]=e[1],this.state["font-family"]=e[1],this.attributes["font-size"]=e[0],this.state["font-size"]=e[0],this.fontSize=Number(e[0].match(/\d+/)),this}setFillStyle(t){return this.attributes.fill=t,this}setBackgroundFillStyle(t){return this.background_attributes.fill=t,this.background_attributes.stroke=t,this}setStrokeStyle(t){return this.attributes.stroke=t,this}setShadowColor(t){return this.shadow_attributes.color=t,this}setShadowBlur(t){return this.shadow_attributes.width=t,this}setLineWidth(t){this.attributes["stroke-width"]=t,this.lineWidth=t}setLineDash(t){if(Object.prototype.toString.call(t)==="[object Array]")return t=t.join(", "),this.attributes["stroke-dasharray"]=t,this;throw new M.RERR("ArgumentError","lineDash must be an array of integers.")}setLineCap(t){return this.attributes["stroke-linecap"]=t,this}resize(t,e){this.width=t,this.height=e,this.element.style.width=t;const i={width:t,height:e};return this.applyAttributes(this.svg,i),this.scale(this.state.scale.x,this.state.scale.y),this}scale(t,e){this.state.scale={x:t,y:e};const i=this.width/t,s=this.height/e;return this.setViewBox(0,0,i,s),this}setViewBox(...t){if(t.length===1){const[e]=t;this.svg.setAttribute("viewBox",e)}else{const[e,i,s,r]=t,o=e+" "+i+" "+s+" "+r;this.svg.setAttribute("viewBox",o)}}applyAttributes(t,e){const i=Er[t.nodeName];return Object.keys(e).forEach(s=>{var r;i&&i[s]||!s||!e[s]||s==="d"&&((r=e[s])==null?void 0:r.indexOf("NaN"))>-1||t.setAttributeNS(null,s,e[s])}),t}clear(){for(;this.svg.lastChild;)this.svg.removeChild(this.svg.lastChild);this.scale(this.state.scale.x,this.state.scale.y)}rect(t,e,i,s,r){s<0&&(e+=s,s*=-1);const o=this.create("rect");return typeof r=="undefined"&&(r={fill:"none","stroke-width":this.lineWidth,stroke:"black"}),M.Merge(r,{x:t,y:e,width:i,height:s}),this.applyAttributes(o,r),this.add(o),this}fillRect(t,e,i,s){return s<0&&(e+=s,s*=-1),this.rect(t,e,i,s,this.attributes),this}clearRect(t,e,i,s){return this.rect(t,e,i,s,this.background_attributes),this}beginPath(){return this.path="",this.pen.x=NaN,this.pen.y=NaN,this}moveTo(t,e){return this.path+="M"+t+" "+e,this.pen.x=t,this.pen.y=e,this}lineTo(t,e){return this.path+="L"+t+" "+e,this.pen.x=t,this.pen.y=e,this}bezierCurveTo(t,e,i,s,r,o){return this.path+="C"+t+" "+e+","+i+" "+s+","+r+" "+o,this.pen.x=r,this.pen.y=o,this}quadraticCurveTo(t,e,i,s){return this.path+="Q"+t+" "+e+","+i+" "+s,this.pen.x=i,this.pen.y=s,this}arc(t,e,i,s,r,o){function a(h){for(;h<0;)h+=Math.PI*2;for(;h>Math.PI*2;)h-=Math.PI*2;return h}if(s=a(s),r=a(r),s>r){const h=s;s=r,r=h,o=!o}const l=r-s;return l>Math.PI?(this.arcHelper(t,e,i,s,s+l/2,o),this.arcHelper(t,e,i,s+l/2,r,o)):this.arcHelper(t,e,i,s,r,o),this}arcHelper(t,e,i,s,r,o){const a=t+i*Math.cos(s),l=e+i*Math.sin(s),h=t+i*Math.cos(r),c=e+i*Math.sin(r);let u=0,f=0;o?(f=1,r-sMath.PI&&(u=1),this.path+="M"+a+" "+l+" A"+i+" "+i+" 0 "+u+" "+f+" "+h+" "+c,!isNaN(this.pen.x)&&!isNaN(this.pen.y)&&(this.peth+="M"+this.pen.x+" "+this.pen.y)}closePath(){return this.path+="Z",this}glow(){if(this.shadow_attributes.width>0){const t=this.shadow_attributes,e=t.width/2;for(let i=1;i<=e;i++){const s={stroke:t.color,"stroke-linejoin":"round","stroke-linecap":"round","stroke-width":+(t.width*.4/e*i).toFixed(3),opacity:+((t.opacity||.3)/e).toFixed(3)},r=this.create("path");s.d=this.path,this.applyAttributes(r,s),this.add(r)}}return this}fill(t){this.glow();const e=this.create("path");let i=t;return typeof t=="undefined"?(t={},M.Merge(t,this.attributes),t.stroke="none",i=t):(i=t,M.Merge(i,this.attributes),t.class&&(i.class=t.class),t.id&&(i.id=t.id)),t.d=this.path,this.applyAttributes(e,t),this.add(e),this}stroke(t=void 0){this.glow();const e=this.create("path"),i={};return M.Merge(i,this.attributes),t&&M.Merge(i,t),i.fill="none",i["stroke-width"]=this.lineWidth,i.d=this.path,this.applyAttributes(e,i),this.add(e),this}measureText(t){const e=this.create("text");if(typeof e.getBBox!="function")return{x:0,y:0,width:0,height:0};e.textContent=t,this.applyAttributes(e,this.attributes),this.svg.appendChild(e);let i=e.getBBox();return this.ie&&t!==""&&this.attributes["font-style"]==="italic"&&(i=this.ieMeasureTextFix(i,t)),this.svg.removeChild(e),i}ieMeasureTextFix(t){const e=Number(this.fontSize),i=1.196,s=1.9598,r=i*e+s,o=t.width-r,a=t.height-1.5;return{x:t.x,y:t.y,width:o,height:a}}fillText(t,e,i){if(!t||t.length<=0)return;const s={};M.Merge(s,this.attributes),s.stroke="none",s.x=e,s.y=i;const r=this.create("text");r.textContent=t,this.applyAttributes(r,s),this.add(r)}save(){return this.state_stack.push({state:{"font-family":this.state["font-family"],"font-weight":this.state["font-weight"],"font-style":this.state["font-style"],"font-size":this.state["font-size"],scale:this.state.scale},attributes:{"font-family":this.attributes["font-family"],"font-weight":this.attributes["font-weight"],"font-style":this.attributes["font-style"],"font-size":this.attributes["font-size"],fill:this.attributes.fill,stroke:this.attributes.stroke,"stroke-width":this.attributes["stroke-width"],"stroke-dasharray":this.attributes["stroke-dasharray"]},shadow_attributes:{width:this.shadow_attributes.width,color:this.shadow_attributes.color},lineWidth:this.lineWidth}),this}restore(){const t=this.state_stack.pop();return this.state["font-family"]=t.state["font-family"],this.state["font-weight"]=t.state["font-weight"],this.state["font-style"]=t.state["font-style"],this.state["font-size"]=t.state["font-size"],this.state.scale=t.state.scale,this.attributes["font-family"]=t.attributes["font-family"],this.attributes["font-weight"]=t.attributes["font-weight"],this.attributes["font-style"]=t.attributes["font-style"],this.attributes["font-size"]=t.attributes["font-size"],this.attributes.fill=t.attributes.fill,this.attributes.stroke=t.attributes.stroke,this.attributes["stroke-width"]=t.attributes["stroke-width"],this.attributes["stroke-dasharray"]=t.attributes["stroke-dasharray"],this.shadow_attributes.width=t.shadow_attributes.width,this.shadow_attributes.color=t.shadow_attributes.color,this.lineWidth=t.lineWidth,this}}let Go=null;class Zt{static get Backends(){return{CANVAS:1,RAPHAEL:2,SVG:3,VML:4}}static get LineEndType(){return{NONE:1,UP:2,DOWN:3}}static get USE_CANVAS_PROXY(){return!1}static get lastContext(){return Go}static set lastContext(t){Go=t}static buildContext(t,e,i,s,r){const o=new Zt(t,e);i&&s&&o.resize(i,s),r||(r="#FFF");const a=o.getContext();return a.setBackgroundFillStyle(r),Zt.lastContext=a,a}static getCanvasContext(t,e,i,s){return Zt.buildContext(t,Zt.Backends.CANVAS,e,i,s)}static getRaphaelContext(t,e,i,s){return Zt.buildContext(t,Zt.Backends.RAPHAEL,e,i,s)}static getSVGContext(t,e,i,s){return Zt.buildContext(t,Zt.Backends.SVG,e,i,s)}static bolsterCanvasContext(t){if(Zt.USE_CANVAS_PROXY)return new gs(t);const e=["clear","setFont","setRawFont","setFillStyle","setBackgroundFillStyle","setStrokeStyle","setShadowColor","setShadowBlur","setLineWidth","setLineCap","setLineDash","openGroup","closeGroup","getGroup"];return t.vexFlowCanvasContext=t,e.forEach(i=>{t[i]=t[i]||gs.prototype[i]}),t}static drawDashedLine(t,e,i,s,r,o){t.beginPath();const a=s-e,l=r-i,h=Math.atan2(l,a);let c=e,u=i;t.moveTo(e,i);let f=0,d=!0;for(;!((a<0?c<=s:c>=s)&&(l<0?u<=r:u>=r));){const p=o[f++%o.length],g=c+Math.cos(h)*p;c=a<0?Math.max(s,g):Math.min(s,g);const m=u+Math.sin(h)*p;u=l<0?Math.max(r,m):Math.min(r,m),d?t.lineTo(c,u):t.moveTo(c,u),d=!d}t.closePath(),t.stroke()}constructor(t,e){if(this.elementId=t,!this.elementId)throw new M.RERR("BadArgument","Invalid id for renderer.");if(this.element=document.getElementById(t),this.element||(this.element=t),this.ctx=null,this.paper=null,this.backend=e,this.backend===Zt.Backends.CANVAS){if(!this.element.getContext)throw new M.RERR("BadElement",`Can't get canvas context from element: ${t}`);this.ctx=Zt.bolsterCanvasContext(this.element.getContext("2d"))}else if(this.backend===Zt.Backends.RAPHAEL)this.ctx=new tc(this.element);else if(this.backend===Zt.Backends.SVG)this.ctx=new ec(this.element);else throw new M.RERR("InvalidBackend",`No support for backend: ${this.backend}`)}resize(t,e){if(this.backend===Zt.Backends.CANVAS){if(!this.element.getContext)throw new M.RERR("BadElement",`Can't get canvas context from element: ${this.elementId}`);[t,e]=gs.SanitizeCanvasDims(t,e);const i=window.devicePixelRatio||1;this.element.width=t*i,this.element.height=e*i,this.element.style.width=t+"px",this.element.style.height=e+"px",this.ctx=Zt.bolsterCanvasContext(this.element.getContext("2d")),this.ctx.scale(i,i)}else this.ctx.resize(t,e);return this}getContext(){return this.ctx}}function ic(...n){ft.DEBUG&&M.L("Vex.Flow.Stem",n)}class ft extends he{static get CATEGORY(){return"stem"}static get UP(){return 1}static get DOWN(){return-1}static get WIDTH(){return V.STEM_WIDTH}static get HEIGHT(){return V.STEM_HEIGHT}constructor(t={}){super(),this.setAttribute("type","Stem"),this.x_begin=t.x_begin||0,this.x_end=t.x_end||0,this.y_top=t.y_top||0,this.y_bottom=t.y_bottom||0,this.stem_extension=t.stem_extension||0,this.stem_direction=t.stem_direction||0,this.hide=t.hide||!1,this.isStemlet=t.isStemlet||!1,this.stemletHeight=t.stemletHeight||0,this.resetHeight=0,this.renderHeightAdjustment=0,this.setOptions(t)}setResetHeight(t){this.resetHeight=t}setOptions(t){this.stem_up_y_offset=t.stem_up_y_offset||0,this.stem_down_y_offset=t.stem_down_y_offset||0}setNoteHeadXBounds(t,e){return this.x_begin=t,this.x_end=e,this}setDirection(t){this.stem_direction=t}setExtension(t){this.stem_extension=t}getExtension(){return this.stem_extension}setYBounds(t,e){this.y_top=t,this.y_bottom=e}getCategory(){return ft.CATEGORY}getHeight(){const t=this.stem_direction===ft.UP?this.stem_up_y_offset:this.stem_down_y_offset;return(this.y_bottom-this.y_top)*this.stem_direction+(ft.HEIGHT-t+this.stem_extension)*this.stem_direction}getBoundingBox(){throw new M.RERR("NotImplemented","getBoundingBox() not implemented.")}getExtents(){const t=this.stem_direction===ft.UP,e=[this.y_top,this.y_bottom],i=ft.HEIGHT+this.stem_extension,s=(t?Math.min:Math.max)(...e),r=(t?Math.max:Math.min)(...e);return{topY:s+i*-this.stem_direction+this.resetHeight*-this.stem_direction,baseY:r}}setVisibility(t){return this.hide=!t,this}setStemlet(t,e){return this.isStemlet=t,this.stemletHeight=e,this}draw(){if(this.setRendered(),this.hide)return;const t=this.checkContext();let e,i;const s=this.stem_direction;s===ft.DOWN?(e=this.x_begin,i=this.y_top+this.stem_down_y_offset):(e=this.x_end,i=this.y_bottom-this.stem_up_y_offset);const r=this.getHeight();ic("Rendering stem - ","Top Y: ",this.y_top,"Bottom Y: ",this.y_bottom);const o=this.isStemlet?r-this.stemletHeight*this.stem_direction:0;if(t.save(),this.applyStyle(t),t.beginPath(),t.setLineWidth(ft.WIDTH),t.moveTo(e,i-o),t.lineTo(e,i-r-this.renderHeightAdjustment*s-this.resetHeight*s),t.svg){const a={class:M.Prefix("stem")};this.id&&(a.id=this.id),t.stroke(a)}else t.stroke();this.restoreStyle(t),t.restore()}}class He extends he{static get LOCATION_TOP(){return 1}static get LOCATION_BOTTOM(){return-1}static get NESTING_OFFSET(){return 15}constructor(t,e){if(super(),this.setAttribute("type","Tuplet"),!t||!t.length)throw new M.RuntimeError("BadArguments","No notes provided for tuplet.");this.options=M.Merge({},e),this.notes=t,this.num_notes="num_notes"in this.options?this.options.num_notes:t.length,this.options.beats_occupied&&this.beatsOccupiedDeprecationWarning(),this.notes_occupied=this.options.notes_occupied||this.options.beats_occupied||2,"bracketed"in this.options?this.bracketed=this.options.bracketed:this.bracketed=t.some(i=>i.beam===null),this.ratioed="ratioed"in this.options?this.options.ratioed:Math.abs(this.notes_occupied-this.num_notes)>1,this.point=28,this.y_pos=16,this.x_pos=100,this.width=200,this.location=this.options.location||He.LOCATION_TOP,si.AlignRestsToNotes(t,!0,!0),this.resolveGlyphs(),this.attach()}attach(){for(let t=0;t=1;)this.numerator_glyphs.unshift(new xt("v"+t%10,this.point)),t=parseInt(t/10,10);for(this.denom_glyphs=[],t=this.notes_occupied;t>=1;)this.denom_glyphs.unshift(new xt("v"+t%10,this.point)),t=parseInt(t/10,10)}getNestedTupletCount(){const t=this.location,e=this.notes[0];let i=r(e,t),s=r(e,t);function r(o,a){return o.tupletStack.filter(l=>l.location===a).length}return this.notes.forEach(o=>{const a=r(o,t);i=a>i?a:i,s=as&&(s=o)}}return s+t+e}draw(){this.checkContext(),this.setRendered();const t=this.notes[0],e=this.notes[this.notes.length-1];this.bracketed?(this.x_pos=t.getTieLeftX()-5,this.width=e.getTieRightX()-this.x_pos+5):(this.x_pos=t.getStemX(),this.width=e.getStemX()-this.x_pos),this.y_pos=this.getYPosition();const i=(l,h)=>l+h.getMetrics().width;let s=this.numerator_glyphs.reduce(i,0);this.ratioed&&(s=this.denom_glyphs.reduce(i,s),s+=this.point*.32);const o=this.x_pos+this.width/2-s/2;if(this.bracketed){const l=this.width/2-s/2-5;l>0&&(this.context.fillRect(this.x_pos,this.y_pos,l,1),this.context.fillRect(this.x_pos+this.width/2+s/2+5,this.y_pos,l,1),this.context.fillRect(this.x_pos,this.y_pos+(this.location===He.LOCATION_BOTTOM),1,this.location*10),this.context.fillRect(this.x_pos+this.width,this.y_pos+(this.location===He.LOCATION_BOTTOM),1,this.location*10))}let a=0;if(this.numerator_glyphs.forEach(l=>{l.render(this.context,o+a,this.y_pos+this.point/3-2),a+=l.getMetrics().width}),this.ratioed){const l=o+a+this.point*.16,h=this.point*.06;this.context.beginPath(),this.context.arc(l,this.y_pos-this.point*.08,h,0,Math.PI*2,!0),this.context.closePath(),this.context.fill(),this.context.beginPath(),this.context.arc(l,this.y_pos+this.point*.12,h,0,Math.PI*2,!0),this.context.closePath(),this.context.fill(),a+=this.point*.32,this.denom_glyphs.forEach(c=>{c.render(this.context,o+a,this.y_pos+this.point/3-2),a+=c.getMetrics().width})}}}function Wo(n){let t=0;return n.forEach(e=>{e.keyProps&&e.keyProps.forEach(i=>{t+=i.line-3})}),t>=0?ft.DOWN:ft.UP}const sc=(n,t)=>{const e=n.getStemExtents().topY,i=n.getStemX(),s=t.getStemExtents().topY,r=t.getStemX();return(s-e)/(r-i)},ur="L",nc="R",Uo="B";class Vi extends he{static getDefaultBeamGroups(t){(!t||t==="c")&&(t="4/4");const i={"1/2":["1/2"],"2/2":["1/2"],"3/2":["1/2"],"4/2":["1/2"],"1/4":["1/4"],"2/4":["1/4"],"3/4":["1/4"],"4/4":["1/4"],"1/8":["1/8"],"2/8":["2/8"],"3/8":["3/8"],"4/8":["2/8"],"1/16":["1/16"],"2/16":["2/16"],"3/16":["3/16"],"4/16":["2/16"]}[t];if(i===void 0){const s=parseInt(t.split("/")[0],10),r=parseInt(t.split("/")[1],10);if(s%3===0)return[new Rt(3,r)];if(r>4)return[new Rt(2,r)];if(r<=4)return[new Rt(1,r)]}else return i.map(s=>new Rt().parse(s));return[new Rt(1,4)]}static applyAndGetBeams(t,e,i){return Vi.generateBeams(t.getTickables(),{groups:i,stem_direction:e})}static generateBeams(t,e){e||(e={}),(!e.groups||!e.groups.length)&&(e.groups=[new Rt(2,8)]);const i=e.groups.map(x=>{if(!x.multiply)throw new M.RuntimeError("InvalidBeamGroups","The beam groups must be an array of Vex.Flow.Fractions");return x.clone().multiply(V.RESOLUTION,1)}),s=t;let r=0,o=[],a=[];function l(x){return x.reduce((w,T)=>T.getTicks().clone().add(w),new Rt(0,1))}function h(){i.length-1>r?r+=1:r=0}function c(){let x=[];s.forEach(w=>{if(x=[],w.shouldIgnoreTicks()){o.push(a),a=x;return}a.push(w);const T=i[r].clone(),E=l(a),C=V.durationToNumber(w.duration)<8;C&&w.tuplet&&(T.numerator*=2),E.greaterThan(T)?(C||x.push(a.pop()),o.push(a),a=x,h()):E.equals(T)&&(o.push(a),a=x,h())}),a.length>0&&o.push(a)}function u(){return o.filter(x=>{if(x.length>1){let w=!0;return x.forEach(T=>{T.getIntrinsicTicks()>=V.durationToTicks("4")&&(w=!1)}),w}return!1})}function f(){const x=[];o.forEach(w=>{let T=[];w.forEach((E,C,P)=>{const I=C===0||C===P.length-1,F=P[C-1],L=!e.beam_rests&&E.isRest(),k=e.beam_rests&&e.beam_middle_only&&E.isRest()&&I;let v=!1;if(e.maintain_stem_directions&&F&&!E.isRest()&&!F.isRest()){const H=F.getStemDirection();v=E.getStemDirection()!==H}const G=parseInt(E.duration,10)<8;L||k||v||G?(T.length>0&&x.push(T),T=v?[E]:[]):T.push(E)}),T.length>0&&x.push(T)}),o=x}function d(){o.forEach(x=>{let w;if(e.maintain_stem_directions){const T=p(x);w=T?T.getStemDirection():ft.UP}else e.stem_direction?w=e.stem_direction:w=Wo(x);g(x,w)})}function p(x){for(let w=0;w{T.setStemDirection(w)})}function m(){const x=[];return o.forEach(w=>{let T=null;w.forEach(E=>{E.tuplet&&T!==E.tuplet&&(T=E.tuplet,x.push(T))})}),x}c(),f(),d();const S=u(),b=m(),y=[];return S.forEach(x=>{const w=new Vi(x);e.show_stemlets&&(w.render_options.show_stemlets=!0),e.secondary_breaks&&(w.render_options.secondary_break_ticks=V.durationToTicks(e.secondary_breaks)),e.flat_beams===!0&&(w.render_options.flat_beams=!0,w.render_options.flat_beam_offset=e.flat_beam_offset),y.push(w)}),b.forEach(x=>{const w=x.notes[0].stem_direction===ft.DOWN?He.LOCATION_BOTTOM:He.LOCATION_TOP;x.setTupletLocation(w);let T=!1;for(let E=0;E=V.durationToTicks("4"))throw new M.RuntimeError("BadArguments","Beams can only be applied to notes shorter than a quarter note.");let i,s;for(this.stem_direction=ft.UP,i=0;ia+l.stem_direction,0)>-1?ft.UP:ft.DOWN),i=0;ii.getGlyph().beam_count).reduce((i,s)=>s>i?s:i)}breakSecondaryAt(t){return this.break_on_indices=t,this}getSlopeY(t,e,i,s){return i+(t-e)*s}calculateSlope(){const{notes:t,stem_direction:e,render_options:{max_slope:i,min_slope:s,slope_iterations:r,slope_cost:o}}=this,a=t[0],l=sc(a,t[t.length-1]),h=(i-s)/r;let c=Number.MAX_VALUE,u=0,f=0;for(let d=s;d<=i;d+=h){let p=0,g=0;for(let y=1;ym)&&(h=m,a=Math.min(...g.getYs()),l=g.getBeamCount())}let c=o/t.length;const u=i*1.5,f=s+l*u,d=a+f*-e;e===ft.DOWN&&cd&&(c=a-f),r+this.render_options.flat_beam_offset_per_beam>0?e===ft.DOWN&&c>r&&!this.render_options.flat_beams?this.render_options.flat_beam_offset=c:e===ft.UP&&c0){let s=this.render_options.flat_beam_offset;this.render_options.flat_beam_offset_per_beam&&(s+=this.render_options.flat_beam_offset_per_beam*this.getBeamCount());let r=this.notes[0].note_heads[0].y;const o=this.stem_direction>0?Math.min:Math.max;for(const a of this.notes)for(const l of a.note_heads)r=o(r,l.y);i=r+s*-this.stem_direction}return i}applyStemExtensions(){const{notes:t,slope:e,y_shift:i,stem_direction:s,beam_count:r,render_options:{show_stemlets:o,stemlet_extension:a,beam_width:l}}=this,h=t[0],c=this.getBeamYToDraw(),u=h.getStemX();for(let f=0;f=8&&(d=this.break_on_indices.indexOf(c)!==-1,this.render_options.secondary_break_ticks&&l>=this.render_options.secondary_break_ticks&&(l=0,d=!0));const p=u.getIntrinsicTicks(){t.getStem()&&(this.context.openGroup("stem",t.getAttribute("id")+"-stem"),t.getStem().setContext(this.context).draw(),this.context.closeGroup())},this)}drawBeamLines(){this.checkContext();const t=["4","8","16","32","64"],e=this.notes[0];let i=this.getBeamYToDraw();const s=e.getStemX(),r=this.render_options.beam_width*this.stem_direction,o={};for(const a of this.notes)o[a.getAttribute("id")]=0;for(let a=0;a{t.getStave()||t.setStave(this.stave)}),this.preFormatted=!0,this)}draw(t=this.context,e=this.stave){this.setRendered();let i=null;for(let s=0;s0&&i){const o=r.getBoundingBox();o&&i.mergeWith(o)}r.setContext(t),r.drawWithStyle()}this.boundingBox=i}}function zo(n,t,e,i,s){if(t!==Bt.type.BOLD_DOUBLE_LEFT&&t!==Bt.type.BOLD_DOUBLE_RIGHT)throw new M.RERR("InvalidConnector","A REPEAT_BEGIN or REPEAT_END type must be provided.");let r=3,o=3.5;const a=2;t===Bt.type.BOLD_DOUBLE_RIGHT&&(r=-5,o=3),n.fillRect(e+r,i,1,s-i),n.fillRect(e-a,i,o,s-i)}class Bt extends he{static get type(){return{SINGLE_RIGHT:0,SINGLE_LEFT:1,SINGLE:1,DOUBLE:2,BRACE:3,BRACKET:4,BOLD_DOUBLE_LEFT:5,BOLD_DOUBLE_RIGHT:6,THIN_DOUBLE:7,NONE:8}}static get typeString(){return{singleRight:Bt.type.SINGLE_RIGHT,singleLeft:Bt.type.SINGLE_LEFT,single:Bt.type.SINGLE,double:Bt.type.DOUBLE,brace:Bt.type.BRACE,bracket:Bt.type.BRACKET,boldDoubleLeft:Bt.type.BOLD_DOUBLE_LEFT,boldDoubleRight:Bt.type.BOLD_DOUBLE_RIGHT,thinDouble:Bt.type.THIN_DOUBLE,none:Bt.type.NONE}}constructor(t,e){super(),this.setAttribute("type","StaveConnector"),this.thickness=V.STAVE_LINE_THICKNESS,this.width=3,this.top_stave=t,this.bottom_stave=e,this.type=Bt.type.DOUBLE,this.font={family:"times",size:16,weight:"normal"},this.x_shift=0,this.texts=[]}setType(t){return t=typeof t=="string"?Bt.typeString[t]:t,t>=Bt.type.SINGLE_RIGHT&&t<=Bt.type.NONE&&(this.type=t),this}setText(t,e){return this.texts.push({content:t,options:M.Merge({shift_x:0,shift_y:0},e)}),this}setFont(t){M.Merge(this.font,t)}setXShift(t){if(typeof t!="number")throw M.RERR("InvalidType","x_shift must be a Number");return this.x_shift=t,this}draw(){const t=this.checkContext();this.setRendered();let e=this.top_stave.getYForLine(0),i=this.bottom_stave.getYForLine(this.bottom_stave.getNumLines()-1)+this.thickness,s=this.width,r=this.top_stave.getX();(this.type===Bt.type.SINGLE_RIGHT||this.type===Bt.type.BOLD_DOUBLE_RIGHT||this.type===Bt.type.THIN_DOUBLE)&&(r=this.top_stave.getX()+this.top_stave.width);let a=i-e;switch(this.type){case Bt.type.SINGLE:s=1;break;case Bt.type.SINGLE_LEFT:s=1;break;case Bt.type.SINGLE_RIGHT:s=1;break;case Bt.type.DOUBLE:r-=this.width+2;break;case Bt.type.BRACE:{s=12;const l=this.top_stave.getX()-2+this.x_shift,h=e,c=l,u=i,f=l-s,d=h+a/2,p=f-.9*s,g=h+.2*a,m=l+1.1*s,S=d-.135*a,b=m,y=d+.135*a,x=p,w=u-.2*a,T=f-s,E=w,C=l+.4*s,P=d+.135*a,I=C,F=d-.135*a,L=T,k=g;t.beginPath(),t.moveTo(l,h),t.bezierCurveTo(p,g,m,S,f,d),t.bezierCurveTo(b,y,x,w,c,u),t.bezierCurveTo(T,E,C,P,f,d),t.bezierCurveTo(I,F,L,k,l,h),t.fill(),t.stroke();break}case Bt.type.BRACKET:e-=4,i+=4,a=i-e,xt.renderGlyph(t,r-5,e-3,40,"v1b",!0),xt.renderGlyph(t,r-5,i+3,40,"v10",!0),r-=this.width+2;break;case Bt.type.BOLD_DOUBLE_LEFT:zo(t,this.type,r+this.x_shift,e,i);break;case Bt.type.BOLD_DOUBLE_RIGHT:zo(t,this.type,r,e,i);break;case Bt.type.THIN_DOUBLE:s=1;break;case Bt.type.NONE:break;default:throw new M.RERR("InvalidType",`The provided StaveConnector.type (${this.type}) is invalid`)}this.type!==Bt.type.BRACE&&this.type!==Bt.type.BOLD_DOUBLE_LEFT&&this.type!==Bt.type.BOLD_DOUBLE_RIGHT&&this.type!==Bt.type.NONE&&t.fillRect(r,e,s,a),this.type===Bt.type.THIN_DOUBLE&&t.fillRect(r-3,e,s,a),t.save(),t.lineWidth=2,t.setFont(this.font.family,this.font.size,this.font.weight);for(let l=0;l0){const m=g.space.deviation,S=m>=0?"+":"";t.setFillStyle("red"),t.fillText(S+Math.round(m),a+e.getXShift(),i-10)}t.restore()}constructor(t){if(super(),this.setAttribute("type","Note"),!t)throw new M.RuntimeError("BadArguments","Note must have valid initialization data to identify duration and type.");const e=V.parseNoteStruct(t);if(!e)throw new M.RuntimeError("BadArguments",`Invalid note initialization object: ${JSON.stringify(t)}`);if(this.duration=e.duration,this.dots=e.dots,this.noteType=e.type,this.customTypes=e.customTypes,this.DYMusicScoreType=t.DYMusicScoreType,t.duration_override?this.setDuration(t.duration_override):this.setIntrinsicTicks(e.ticks),this.modifiers=[],this.glyph=V.getGlyphProps(this.duration,this.noteType),this.customGlyphs=this.customTypes.map(i=>V.getGlyphProps(this.duration,i)),this.positions&&(typeof this.positions!="object"||!this.positions.length))throw new M.RuntimeError("BadArguments","Note keys must be array type.");this.playNote=null,this.tickContext=null,this.modifierContext=null,this.ignore_ticks=!1,this.width=0,this.extraLeftPx=0,this.extraRightPx=0,this.x_shift=0,this.left_modPx=0,this.right_modPx=0,this.voice=null,this.preFormatted=!1,this.ys=[],t.align_center&&this.setCenterAlignment(t.align_center),this.stave=null,this.render_options={annotation_spacing:5,stave_padding:Ie.STAVEPADDING}}getPlayNote(){return this.playNote}setPlayNote(t){return this.playNote=t,this}isRest(){return!1}addStroke(t,e){return e.setNote(this),e.setIndex(t),this.modifiers.push(e),this.setPreFormatted(!1),this}getStave(){return this.stave}setStave(t){return this.stave=t,this.setYs([t.getYForLine(0)]),this.context=this.stave.context,this}getCategory(){return Ie.CATEGORY}setContext(t){return this.context=t,this}getExtraLeftPx(){return this.extraLeftPx}getExtraRightPx(){return this.extraRightPx}setExtraLeftPx(t){return this.extraLeftPx=t,this}setExtraRightPx(t){return this.extraRightPx=t,this}shouldIgnoreTicks(){return this.ignore_ticks}getLineNumber(){return 0}getLineForRest(){return 0}getGlyph(){return this.glyph}getGlyphWidth(){return this.glyph.getWidth?this.glyph.getWidth(this.render_options.glyph_font_scale):15}setYs(t){return this.ys=t,this}getYs(){if(this.ys.length===0)throw new M.RERR("NoYValues","No Y-values calculated for this note.");return this.ys}getYForTopText(t){if(!this.stave)throw new M.RERR("NoStave","No stave attached to this note.");return this.stave.getYForTopText(t)}getBoundingBox(){return null}getVoice(){if(!this.voice)throw new M.RERR("NoVoice","Note has no voice.");return this.voice}setVoice(t){return this.voice=t,this.preFormatted=!1,this}getTickContext(){return this.tickContext}setTickContext(t){return this.tickContext=t,this.preFormatted=!1,this}getDuration(){return this.duration}isDotted(){return this.dots>0}hasStem(){return!1}getDots(){return this.dots}getNoteType(){return this.noteType}setBeam(){return this}setModifierContext(t){return this.modifierContext=t,this}addModifier(t,e=0){return t.setNote(this),t.setIndex(e),this.modifiers.push(t),this.setPreFormatted(!1),this}getModifierStartXY(){if(!this.preFormatted)throw new M.RERR("UnformattedNote","Can't call GetModifierStartXY on an unformatted note");return{x:this.getAbsoluteX(),y:this.ys[0]}}getMetrics(){if(!this.preFormatted)throw new M.RERR("UnformattedNote","Can't call getMetrics on an unformatted note.");let t=0,e=0;this.modifierContext!=null&&(t=this.modifierContext.state.left_shift,e=this.modifierContext.state.right_shift);const i=this.getWidth();return{width:i,noteWidth:i-t-e-this.extraLeftPx-this.extraRightPx,left_shift:this.x_shift,modLeftPx:t,modRightPx:e,extraLeftPx:this.extraLeftPx,extraRightPx:this.extraRightPx}}setWidth(t){this.width=t}getWidth(){if(!this.preFormatted)throw new M.RERR("UnformattedNote","Can't call GetWidth on an unformatted note.");return this.width+(this.modifierContext?this.modifierContext.getWidth():0)}setXShift(t){return this.x_shift=t,this}getXShift(){return this.x_shift}getX(){if(!this.tickContext)throw new M.RERR("NoTickContext","Note needs a TickContext assigned for an X-Value");return this.tickContext.getX()+this.x_shift}getAbsoluteX(){if(!this.tickContext)throw new M.RERR("NoTickContext","Note needs a TickContext assigned for an X-Value");let t=this.tickContext.getX();return this.stave&&(t+=this.stave.getNoteStartX()+this.render_options.stave_padding),this.isCenterAligned()&&(this.DYMusicScoreType==="jianpu"||(t+=this.getCenterXShift())),t}setPreFormatted(t){if(this.preFormatted=t,this.preFormatted){const e=this.tickContext.getExtraPx();this.left_modPx=Math.max(this.left_modPx,e.left),this.right_modPx=Math.max(this.right_modPx,e.right)}}}function rc(...n){Ms.DEBUG&&M.L("Vex.Flow.NoteHead",n)}function oc(n,t,e,i,s,r){const o=V.SLASH_NOTEHEAD_WIDTH;n.save(),n.setLineWidth(V.STEM_WIDTH);let a=!1;if(V.durationToNumber(t)>2&&(a=!0),a||(e-=V.STEM_WIDTH/2*s),n.beginPath(),n.moveTo(e,i+r),n.lineTo(e,i+1),n.lineTo(e+o,i-r),n.lineTo(e+o,i),n.lineTo(e,i+r),n.closePath(),a?n.fill():n.stroke(),V.durationToFraction(t).equals(.5)){const l=[-3,-1,o+1,o+3];for(let h=0;h{const a=o.getTickContext();o.setStave(e.stave),a.setXOffset(r)})}}class Gi extends St{static get CATEGORY(){return"dots"}static format(t,e){const i=e.right_shift,s=1;if(!t||t.length===0)return!1;const r=[],o={};for(let d=0;dp.line-d.line);let a=i,l=0,h=null,c=null,u=null,f=0;for(let d=0;dl?a:l,h=S,c=g}return e.right_shift+=l,!0}constructor(){super(),this.setAttribute("type","Dot"),this.note=null,this.index=null,this.position=St.Position.RIGHT,this.radius=2,this.setWidth(5),this.dot_shiftY=0}getCategory(){return Gi.CATEGORY}setNote(t){this.note=t,this.note.getCategory()==="gracenotes"&&(this.radius*=.5,this.setWidth(3))}setDotShiftY(t){return this.dot_shiftY=t,this}draw(){if(this.checkContext(),this.setRendered(),!this.note||this.index===null)throw new M.RERR("NoAttachedNote","Can't draw dot without a note and index.");const t=this.note.stave.options.spacing_between_lines_px,e=this.note.getModifierStartXY(this.position,this.index,{forceFlagRight:!0});this.note.getCategory()==="tabnotes"&&(e.y=this.note.getStemExtents().baseY+1);const i=e.x+this.x_shift+this.width-this.radius,s=e.y+this.y_shift+this.dot_shiftY*t,r=this.context;r.beginPath(),r.arc(i,s,this.radius,0,Math.PI*2,!1),r.fill()}}function ac(...n){ae.DEBUG&&M.L("Vex.Flow.StaveNote",n)}const lc=n=>ft.WIDTH/(2*-n.getStemDirection()),hc=(n,t)=>t===(n.getStemDirection()===ft.UP?n.keyProps.length-1:0);function Di(n,t,e){const i=(t.isrest?0:1)*e;n.line+=i,n.maxLine+=i,n.minLine+=i,n.note.setKeyLine(0,n.note.getKeyLine(0)+i)}function cc(n,t,e){const i=n.line-M.MidLine(t.minLine,e.maxLine);n.note.setKeyLine(0,n.note.getKeyLine(0)-i),n.line-=i,n.maxLine-=i,n.minLine-=i}class ae extends oo{static get CATEGORY(){return"stavenotes"}static get STEM_UP(){return ft.UP}static get STEM_DOWN(){return ft.DOWN}static get DEFAULT_LEDGER_LINE_OFFSET(){return 3}static renderVibrato(t,e,i,s,r){const{vibrato_width:o,wave_width:a,wave_girth:l,wave_height:h}=s,c=o/a,u=Math.abs(r-i)/c+2;t.beginPath();let f;for(t.moveTo(e,i+l),f=0;f2?i[1]:null;let l=r>2?i[2]:i[1];r===2&&o.stemDirection===-1&&l.stemDirection===1&&(o=i[1],l=i[0]);const h=Math.max(o.voice_shift,l.voice_shift);let c=0,u;if(r===2){const f=o.stemDirection===l.stemDirection?0:.5;if(o.stemDirection===l.stemDirection&&o.minLine<=l.maxLine&&(o.isrest||(u=Math.abs(o.line-(l.maxLine+.5)),u=Math.max(u,o.stemMin),o.minLine=o.line-u,o.note.setStemLength(u*10))),o.minLine<=l.maxLine+f)if(o.isrest)Di(o,l,1);else if(l.isrest)Di(l,o,-1);else{c=h;const d=Math.abs(o.line-l.line);let p=0,g=0;o.note.duration==="h"?p++:o.note.duration==="w"&&g++,l.note.duration==="h"?p++:l.note.duration==="w"&&g++;let m=p===1||g===1||o.note.dots!==l.note.dots;if(s&&(m=m||g===2),d===0&&m){if(l.note.setXShift(c),o.note.dots>0){let S=0;for(const b of o.note.modifiers)if(b instanceof Gi&&(S++,b.setYShift(-10*(l.maxLine-o.line+1)),S===o.note.dots))break}}else d<1&&d>0?l.note.setXShift(c):o.note.voice!==l.note.voice&&o.stemDirection===l.stemDirection&&(o.line>l.line?o.stemDirection===1?l.note.renderFlag=!1:o.note.renderFlag=!1:l.line>o.line?l.stemDirection===1?o.note.renderFlag=!1:l.note.renderFlag=!1:l.stemDirection===1&&(l.stemDirection=-1,l.note.setStemDirection(-1)))}return!0}if(a!==null&&a.minLinee.postFormat()),!0):!1}constructor(t){if(super(t),this.setAttribute("type","StaveNote"),this.keys=t.keys,this.clef=t.clef,this.octave_shift=t.octave_shift,this.beam=null,this.vibrato=null,this.glyph=V.getGlyphProps(this.duration,this.noteType),!this.glyph)throw new M.RuntimeError("BadArguments",`Invalid note initialization data (No glyph found): ${JSON.stringify(t)}`);this.displaced=!1,this.dot_shiftY=0,this.addDotsCount=0,this.keyProps=[],this.use_default_head_x=!1,this.note_heads=[],this.modifiers=[],M.Merge(this.render_options,{glyph_font_scale:t.glyph_font_scale||V.DEFAULT_NOTATION_FONT_SCALE,stroke_px:t.stroke_px||ae.DEFAULT_LEDGER_LINE_OFFSET}),this.calculateKeyProps(),this.buildStem(),t.auto_stem?this.autoStem():this.setStemDirection(t.stem_direction),this.reset(),this.buildFlag()}reset(){super.reset();const t=this.note_heads.map(e=>e.getStyle());this.buildNoteHeads(),this.note_heads.forEach((e,i)=>e.setStyle(t[i])),this.stave&&this.note_heads.forEach(e=>e.setStave(this.stave)),this.calcExtraPx()}setBeam(t){return this.beam=t,this.calcExtraPx(),this}setVibrato(t){this.vibrato=t}getCategory(){return ae.CATEGORY}buildStem(){this.setStem(new ft({hide:!!this.isRest()})),this.stem.id=M.Prefix(`${this.getAttribute("id")}-stem`)}buildNoteHeads(){this.note_heads=[];const t=this.getStemDirection(),e=this.getKeys();let i=null,s=null,r=!1,o,a,l;t===ft.UP?(o=0,a=e.length,l=1):t===ft.DOWN&&(o=e.length-1,a=-1,l=-1);for(let h=o;h!==a;h+=l){const c=this.keyProps[h],u=c.line;i===null?i=u:(s=Math.abs(i-u),s===0||s===.5?r=!r:(r=!1,this.use_default_head_x=!0)),i=u;const f=new Ms({duration:this.duration,note_type:this.noteType,displaced:r,stem_direction:t,custom_glyph_code:c.code,glyph_font_scale:this.render_options.glyph_font_scale,x_shift:c.shift_right,stem_up_x_offset:c.stem_up_x_offset,stem_down_x_offset:c.stem_down_x_offset,line:c.line});this.note_heads[h]=f}}autoStem(){this.minLine=this.keyProps[0].line,this.maxLine=this.keyProps[this.keyProps.length-1].line;const t=3,i=(this.minLine+this.maxLine)/20&&(this.keyProps[e-1].displaced=!0)),t=o,this.keyProps.push(r)}t=-1/0,this.keyProps.forEach(e=>{e.linee.line-i.line)}getBoundingBox(){if(!this.preFormatted)throw new M.RERR("UnformattedNote","Can't call getBoundingBox on an unformatted note.");const{width:t,modLeftPx:e,extraLeftPx:i}=this.getMetrics(),s=this.getAbsoluteX()-e-i;let r=0,o=0;const a=this.getStave().getSpacingBetweenLines()/2,l=a*2;if(this.isRest()){const h=this.ys[0],c=V.durationToFraction(this.duration);c.equals(1)||c.equals(2)?(r=h-a,o=h+a):(r=h-this.glyph.line_above*l,o=h+this.glyph.line_below*l)}else if(this.glyph.stem){const h=this.getStemExtents();h.baseY+=a*this.stem_direction,r=Math.min(h.topY,h.baseY),o=Math.max(h.topY,h.baseY)}else{r=null,o=null;for(let h=0;he&&(e=s):s1}hasStem(){return this.glyph.stem}hasFlag(){return super.hasFlag()&&!this.isRest()&&this.renderFlag}getStemX(){return this.noteType==="r"?this.getCenterGlyphX():super.getStemX()+lc(this)}getYForTopText(t){const e=this.getStemExtents();return Math.min(this.stave.getYForTopText(t),e.topY-this.render_options.annotation_spacing*(t+1))}getYForBottomText(t){const e=this.getStemExtents();return Math.max(this.stave.getYForTopText(t),e.baseY+this.render_options.annotation_spacing*t)}setStave(t){super.setStave(t);const e=this.note_heads.map(i=>(i.setStave(t),i.getY()));if(this.setYs(e),this.stem){const{y_top:i,y_bottom:s}=this.getNoteHeadBounds();this.stem.setYBounds(i,s)}return this}getKeys(){return this.keys}getKeyProps(){return this.keyProps}isDisplaced(){return this.displaced}setNoteDisplaced(t){return this.displaced=t,this}getTieRightX(){let t=this.getAbsoluteX();return t+=this.getGlyphWidth()+this.x_shift+this.extraRightPx,this.modifierContext&&(t+=this.modifierContext.getExtraRightPx()),t}getTieLeftX(){let t=this.getAbsoluteX();return t+=this.x_shift-this.extraLeftPx,t}getLineForRest(){let t=this.keyProps[0].line;if(this.keyProps.length>1){const e=this.keyProps[this.keyProps.length-1].line,i=Math.max(t,e),s=Math.min(t,e);t=M.MidLine(i,s)}return t}getModifierStartXY(t,e,i){if(i=i||{},!this.preFormatted)throw new M.RERR("UnformattedNote","Can't call GetModifierStartXY on an unformatted note");if(this.ys.length===0)throw new M.RERR("NoYValues","No Y-Values calculated for this note.");const{ABOVE:s,BELOW:r,LEFT:o,RIGHT:a}=St.Position;let l=0;return t===o?l=-1*2:t===a?(l=this.getGlyphWidth()+this.x_shift+2,this.stem_direction===ft.UP&&this.hasFlag()&&(i.forceFlagRight||hc(this,e))&&(l+=this.flag.getMetrics().width)):(t===r||t===s)&&(l=this.getGlyphWidth()/2),{x:this.getAbsoluteX()+l,y:this.ys[e]}}setStyle(t){super.setStyle(t),this.note_heads.forEach(e=>e.setStyle(t)),this.stem&&this.stem.setStyle(t)}setStemStyle(t){this.stem&&this.getStem().setStyle(t)}getStemStyle(){return this.stem.getStyle()}setLedgerLineStyle(t){this.ledgerLineStyle=t}getLedgerLineStyle(){return this.ledgerLineStyle}setFlagStyle(t){this.flagStyle=t}getFlagStyle(){return this.flagStyle}setKeyStyle(t,e){return this.note_heads[t].setStyle(e),this}setKeyLine(t,e){return(this.glyph.code_head=="va5"||this.glyph.code_head=="v3c")&&(e=3),this.keyProps[t].line=e,this.reset(),this}getKeyLine(t){return this.keyProps[t].line}addToModifierContext(t){this.setModifierContext(t);for(let e=0;e{const f=u.getLine(),d=u.getY();(t===null||de)&&(e=d),s===null&&u.isDisplaced()&&(s=u.getAbsoluteX()),i===null&&!u.isDisplaced()&&(i=u.getAbsoluteX()),r=f>r?f:r,o=f{let w;x&&y?w=g-i:y?w=p-i:w=d-i;const T=y&&x?o:r;s.beginPath(),s.moveTo(w,b),s.lineTo(w+T,b),s.stroke()},S=be(be({},t.getStyle()||{}),this.getLedgerLineStyle()||{});this.applyStyle(s,S);for(let b=6;b<=a;++b){const y=p!==null&&b<=c,x=d!==null&&b<=h;m(t.getYForNote(b),y,x)}for(let b=0;b>=l;--b){const y=p!==null&&b>=f,x=d!==null&&b>=u;m(t.getYForNote(b),y,x)}this.restoreStyle(s,S)}drawVibrato(){if(this.vibrato){const t=this.context;t.openGroup("vibrato");const e=this.vibrato.getNoteHeadEndX()+2,{y_top:i}=this.vibrato.getNoteHeadBounds();let{y_bottom:s}=this.getNoteHeadBounds(),r=Math.abs(this.getNoteHeadBeginX()-e)-10;this.vibrato.stave.y!==this.stave.y&&(r=30,s=i+10),ae.renderVibrato(this.context,e,i,{harsh:!0,vibrato_width:r,wave_height:6,wave_width:4,wave_girth:2},s),t.closeGroup()}}drawModifiers(){if(!this.context)throw new M.RERR("NoCanvasContext","Can't draw without a canvas context.");const t=this.context;t.openGroup("modifiers");for(let e=0;e6.5||u<-.5)&&(c=c+(u>6.5?(u-6.5)*10:(u+.5)*10))}i.openGroup("flag",null,{pointerBBox:!0}),this.applyStyle(i,this.getFlagStyle()||!1),this.flag.render(i,h,c),this.restoreStyle(i,this.getFlagStyle()||!1),i.closeGroup()}}drawNoteHeads(){this.note_heads.forEach(t=>{this.context.openGroup("notehead",null,{pointerBBox:!0});try{if(this.isRest()&&this.duration==="w"){const e=this.stave.options.line_config.filter(s=>s.visible).length;this.keyProps[0].line===4&&e<5&&t.setY(t.getY()+10),e===1&&t.setLine(3)}}catch{}t.setContext(this.context).draw(),this.context.closeGroup()})}drawStem(t){if(!this.context)throw new M.RERR("NoCanvasContext","Can't draw without a canvas context.");t&&this.setStem(new ft(t)),this.stem.id=M.Prefix(`${this.getAttribute("id")}-stem`),this.stem&&(this.context.openGroup("stem",null,{pointerBBox:!0}),this.stem.setContext(this.context).draw(),this.context.closeGroup())}draw(){if(!this.context)throw new M.RERR("NoCanvasContext","Can't draw without a canvas context.");if(!this.stave)throw new M.RERR("NoStave","Can't draw without a stave.");if(this.ys.length===0)throw new M.RERR("NoYValues","Can't draw note without Y values.");const t=this.stave.getLines();if(t===2||t===3||t===4)for(let s=0;ss.setX(e)),this.stem){let s=this.getStemX();const r=this.keyProps[0].line;(r>6.5||r<-.5)&&(this.beam||(this.stem.renderHeightAdjustment=r>6.5?(r-6.5)*10:Math.abs(r+.5)*10)),this.stem.setNoteHeadXBounds(s,s)}ac("Rendering ",this.isChord()?"chord :":"note :",this.keys),this.drawLedgerLines(),this.applyStyle(),this.setAttribute("el",this.context.openGroup("stavenote",this.getAttribute("id"))),this.context.openGroup("note",null,{pointerBBox:!0}),i&&this.drawStem(),this.drawNoteHeads(),this.drawFlag(),this.context.closeGroup(),this.drawModifiers(),this.context.closeGroup(),this.restoreStyle(),this.setRendered()}}class Qs extends St{static get CATEGORY(){return"frethandfinger"}static format(t,e){const{left_shift:i,right_shift:s}=e,r=1;if(!t||t.length===0)return!1;const o=[];let a=null,l=0,h=0;for(let m=0;mS.line-m.line);let c=0,u=0,f=0,d=0,p=null,g=null;for(let m=0;mf?S:f):y===St.Position.RIGHT&&(x.setXShift(u),S=h+C,d=S>d?S:d),p=w,g=b}return e.left_shift+=f,e.right_shift+=d,!0}constructor(t){super(),this.setAttribute("type","FretHandFinger"),this.note=null,this.index=null,this.finger=t,this.width=7,this.position=St.Position.LEFT,this.x_shift=0,this.y_shift=0,this.x_offset=0,this.y_offset=0,this.font={family:"sans-serif",size:9,weight:"bold"}}getCategory(){return Qs.CATEGORY}setFretHandFinger(t){return this.finger=t,this}setOffsetX(t){return this.x_offset=t,this}setOffsetY(t){return this.y_offset=t,this}draw(){if(this.checkContext(),!this.note||this.index==null)throw new M.RERR("NoAttachedNote","Can't draw string number without a note and index.");this.setRendered();const t=this.context,e=this.note.getModifierStartXY(this.position,this.index);let i=e.x+this.x_shift+this.x_offset,s=e.y+this.y_shift+this.y_offset+5;switch(this.position){case St.Position.ABOVE:i-=4,s-=12;break;case St.Position.BELOW:i-=2,s+=10;break;case St.Position.LEFT:i-=this.width;break;case St.Position.RIGHT:i+=1;break;default:throw new M.RERR("InvalidPostion",`The position ${this.position} does not exist`)}t.save(),t.setFont(this.font.family,this.font.size,this.font.weight),t.fillText(""+this.finger,i,s),t.restore()}}class te{static get NUM_TONES(){return 12}static get roots(){return["c","d","e","f","g","a","b"]}static get root_values(){return[0,2,4,5,7,9,11]}static get root_indices(){return{c:0,d:1,e:2,f:3,g:4,a:5,b:6}}static get canonical_notes(){return["c","c#","d","d#","e","f","f#","g","g#","a","a#","b"]}static get diatonic_intervals(){return["unison","m2","M2","m3","M3","p4","dim5","p5","m6","M6","b7","M7","octave"]}static get diatonic_accidentals(){return{unison:{note:0,accidental:0},m2:{note:1,accidental:-1},M2:{note:1,accidental:0},m3:{note:2,accidental:-1},M3:{note:2,accidental:0},p4:{note:3,accidental:0},dim5:{note:4,accidental:-1},p5:{note:4,accidental:0},m6:{note:5,accidental:-1},M6:{note:5,accidental:0},b7:{note:6,accidental:-1},M7:{note:6,accidental:0},octave:{note:7,accidental:0}}}static get intervals(){return{u:0,unison:0,m2:1,b2:1,min2:1,S:1,H:1,"2":2,M2:2,maj2:2,T:2,W:2,m3:3,b3:3,min3:3,M3:4,"3":4,maj3:4,"4":5,p4:5,"#4":6,b5:6,aug4:6,dim5:6,"5":7,p5:7,"#5":8,b6:8,aug5:8,"6":9,M6:9,maj6:9,b7:10,m7:10,min7:10,dom7:10,M7:11,maj7:11,"8":12,octave:12}}static get scales(){return{major:[2,2,1,2,2,2,1],dorian:[2,1,2,2,2,1,2],mixolydian:[2,2,1,2,2,1,2],minor:[2,1,2,2,1,2,2]}}static get scaleTypes(){return{M:te.scales.major,m:te.scales.minor}}static get accidentals(){return["bb","b","n","#","##"]}static get noteValues(){return{c:{root_index:0,int_val:0},cn:{root_index:0,int_val:0},"c#":{root_index:0,int_val:1},"c##":{root_index:0,int_val:2},cb:{root_index:0,int_val:11},cbb:{root_index:0,int_val:10},d:{root_index:1,int_val:2},dn:{root_index:1,int_val:2},"d#":{root_index:1,int_val:3},"d##":{root_index:1,int_val:4},db:{root_index:1,int_val:1},dbb:{root_index:1,int_val:0},e:{root_index:2,int_val:4},en:{root_index:2,int_val:4},"e#":{root_index:2,int_val:5},"e##":{root_index:2,int_val:6},eb:{root_index:2,int_val:3},ebb:{root_index:2,int_val:2},f:{root_index:3,int_val:5},fn:{root_index:3,int_val:5},"f#":{root_index:3,int_val:6},"f##":{root_index:3,int_val:7},fb:{root_index:3,int_val:4},fbb:{root_index:3,int_val:3},g:{root_index:4,int_val:7},gn:{root_index:4,int_val:7},"g#":{root_index:4,int_val:8},"g##":{root_index:4,int_val:9},gb:{root_index:4,int_val:6},gbb:{root_index:4,int_val:5},a:{root_index:5,int_val:9},an:{root_index:5,int_val:9},"a#":{root_index:5,int_val:10},"a##":{root_index:5,int_val:11},ab:{root_index:5,int_val:8},abb:{root_index:5,int_val:7},b:{root_index:6,int_val:11},bn:{root_index:6,int_val:11},"b#":{root_index:6,int_val:0},"b##":{root_index:6,int_val:1},bb:{root_index:6,int_val:10},bbb:{root_index:6,int_val:9}}}isValidNoteValue(t){return!(t==null||t<0||t>=te.NUM_TONES)}isValidIntervalValue(t){return this.isValidNoteValue(t)}getNoteParts(t){if(!t||t.length<1)throw new M.RERR("BadArguments","Invalid note name: "+t);if(t.length>3)throw new M.RERR("BadArguments","Invalid note name: "+t);const e=t.toLowerCase(),s=/^([cdefgab])(b|bb|n|#|##)?$/.exec(e);if(s!=null){const r=s[1],o=s[2];return{root:r,accidental:o}}else throw new M.RERR("BadArguments","Invalid note name: "+t)}getKeyParts(t){if(!t||t.length<1)throw new M.RERR("BadArguments","Invalid key: "+t);const e=t.toLowerCase(),s=/^([cdefgab])(b|#)?(mel|harm|m|M)?$/.exec(e);if(s!=null){const r=s[1],o=s[2];let a=s[3];return a||(a="M"),{root:r,accidental:o,type:a}}else throw new M.RERR("BadArguments",`Invalid key: ${t}`)}getNoteValue(t){const e=te.noteValues[t];if(e==null)throw new M.RERR("BadArguments",`Invalid note name: ${t}`);return e.int_val}getIntervalValue(t){const e=te.intervals[t];if(e==null)throw new M.RERR("BadArguments",`Invalid interval name: ${t}`);return e}getCanonicalNoteName(t){if(!this.isValidNoteValue(t))throw new M.RERR("BadArguments",`Invalid note value: ${t}`);return te.canonical_notes[t]}getCanonicalIntervalName(t){if(!this.isValidIntervalValue(t))throw new M.RERR("BadArguments",`Invalid interval value: ${t}`);return te.diatonic_intervals[t]}getRelativeNoteValue(t,e,i){if(i==null&&(i=1),i!==1&&i!==-1)throw new M.RERR("BadArguments",`Invalid direction: ${i}`);let s=(t+i*e)%te.NUM_TONES;return s<0&&(s+=te.NUM_TONES),s}getRelativeNoteName(t,e){const i=this.getNoteParts(t),s=this.getNoteValue(i.root);let r=e-s;if(Math.abs(r)>te.NUM_TONES-3){let a=1;r>0&&(a=-1);const l=(e+1+(s+1))%te.NUM_TONES*a;if(Math.abs(l)>2)throw new M.RERR("BadArguments",`Notes not related: ${t}, ${e})`);r=l}if(Math.abs(r)>2)throw new M.RERR("BadArguments",`Notes not related: ${t}, ${e})`);let o=i.root;if(r>0)for(let a=1;a<=r;++a)o+="#";else if(r<0)for(let a=-1;a>=r;--a)o+="b";return o}getScaleTones(t,e){const i=[t];let s=t;for(let r=0;rn.getMetrics().width;class is extends St{static get CATEGORY(){return"accidentals"}static format(t,e){const s=e.left_shift+1,r=3;if(!t||t.length===0)return;const o=[];let a=null,l=0,h;for(let b=0;by.line-b.line);const c=[];let u=0,f=null;for(let b=0;bu?y.shift:u,f=y.line}let d=0;for(let b=0;bc[x+v],E=v=>v.map(T),C=(v,G)=>{const[et,H]=E([v,G]).map(nt=>nt.line);return et-H},P=(...v)=>v.map(E).every(G=>!this.checkCollision(...G)),I=w-x+1;let F=this.checkCollision(c[x],c[w])?"a":"b";switch(I){case 3:F==="a"&&C(1,2)===.5&&C(0,1)!==.5&&(F="second_on_bottom");break;case 4:P([0,2],[1,3])&&(F="spaced_out_tetrachord");break;case 5:F==="b"&&P([1,3])&&(F="spaced_out_pentachord",P([0,2],[2,4])&&(F="very_spaced_out_pentachord"));break;case 6:P([0,3],[1,4],[2,5])&&(F="spaced_out_hexachord"),P([0,2],[2,4],[1,3],[3,5])&&(F="very_spaced_out_hexachord");break}let L,k;if(I>=7){let v=2,G=!0;for(;G===!0;){G=!1;for(let et=0;et+vk?d:k}else for(L=b;L<=w;L++)k=V.accidentalColumnsTable[I][F][L-b],c[L].column=k,d=d>k?d:k;b=w}const p=[],g=[];for(let b=0;b<=d;b++)p[b]=0,g[b]=0;p[0]=u+s,g[0]=u+s,c.forEach(b=>{b.width>p[b.column]&&(p[b.column]=b.width)});for(let b=1;b{let y=0;const x=S+b.numAcc;for(S;S0?(s=e.flatLine||e.dblSharpLine?2.5:3,t.dblSharpLine&&(i-=.5)):(s=t.flatLine||t.dblSharpLine?2.5:3,e.dblSharpLine&&(i-=.5));const r=Math.abs(i){const l=new Rt(0,1);a.getTickables().forEach(c=>{if(c.shouldIgnoreTicks())return;const u=s[l.value()];u?u.push(c):(i.push(l.value()),s[l.value()]=[c]),l.add(c.getTicks())})});const r=new te;e||(e="C");const o=r.createScaleMap(e);i.forEach(a=>{const l=s[a],h=[],c=u=>{u.isRest()||u.shouldIgnoreTicks()||(u.keys.forEach((f,d)=>{const p=r.getNoteParts(f.split("/")[0]),g=p.accidental||"n",m=p.root+g,S=o[p.root]===m,b=h.indexOf(m)>-1;if(!S||S&&b){o[p.root]=m;const y=new is(g);u.addAccidental(d,y),h.push(m)}}),u.getModifiers().forEach(f=>{f.getCategory()==="gracenotegroups"&&f.getGraceNotes().forEach(c)}))};l.forEach(c)})}constructor(t=null){if(super(),this.setAttribute("type","Accidental"),mn("New accidental: ",t),this.note=null,this.index=null,this.type=t,this.position=St.Position.LEFT,this.render_options={font_scale:38,stroke_px:3,parenLeftPadding:2,parenRightPadding:2},this.accidental=V.accidentalCodes(this.type),!this.accidental)throw new M.RERR("ArgumentError",`Unknown accidental type: ${t}`);this.cautionary=!1,this.parenLeft=null,this.parenRight=null,this.reset()}reset(){const t=this.render_options.font_scale;this.glyph=new xt(this.accidental.code,t),this.glyph.setOriginX(1),this.cautionary&&(this.parenLeft=new xt(V.accidentalCodes("{").code,t),this.parenRight=new xt(V.accidentalCodes("}").code,t),this.parenLeft.setOriginX(1),this.parenRight.setOriginX(1))}getCategory(){return is.CATEGORY}getWidth(){const t=this.cautionary?Ns(this.parenLeft)+Ns(this.parenRight)+this.render_options.parenLeftPadding+this.render_options.parenRightPadding:0;return Ns(this.glyph)+t}setNote(t){if(!t)throw new M.RERR("ArgumentError",`Bad note value: ${t}`);this.note=t,this.note.getCategory()==="gracenotes"&&(this.render_options.font_scale=25,this.reset())}setAsCautionary(){return this.cautionary=!0,this.render_options.font_scale=28,this.reset(),this}draw(){const{context:t,type:e,position:i,note:s,index:r,cautionary:o,x_shift:a,y_shift:l,glyph:h,parenLeft:c,parenRight:u,render_options:{parenLeftPadding:f,parenRightPadding:d}}=this;if(this.checkContext(),!(s&&r!=null))throw new M.RERR("NoAttachedNote","Can't draw accidental without a note and index.");const p=s.getModifierStartXY(i,r);let g=p.x+a;const m=p.y+l;mn("Rendering: ",e,g,m),o?(u.render(t,g,m),g-=Ns(u),g-=d,g-=this.accidental.parenRightPaddingAdjustment,h.render(t,g,m),g-=Ns(h),g-=f,c.render(t,g,m)):h.render(t,g,m),this.setRendered()}}class $s extends St{static get CATEGORY(){return"notesubgroup"}static format(t,e){if(!t||t.length===0)return!1;let i=0;for(let s=0;s{e.ignore_ticks=!1}),this.width=0,this.preFormatted=!1,this.formatter=new si,this.voice=new ye({num_beats:4,beat_value:4,resolution:V.RESOLUTION}).setStrict(!1),this.voice.addTickables(this.subNotes),this}getCategory(){return $s.CATEGORY}preFormat(){this.preFormatted||(this.formatter.joinVoices([this.voice]).format([this.voice],0),this.setWidth(this.formatter.getMinTotalWidth()),this.preFormatted=!0)}setNote(t){this.note=t}setWidth(t){this.width=t}getWidth(){return this.width}draw(){this.checkContext();const t=this.getNote();if(!(t&&this.index!==null))throw new M.RuntimeError("NoAttachedNote","Can't draw notes without a parent note and parent note index.");this.setRendered(),this.alignSubNotesWithNote(this.subNotes,t),this.subNotes.forEach(e=>e.setContext(this.context).drawWithStyle())}}class Qn extends he{constructor(t,e){super(),this.setAttribute("type","StaveTie"),this.notes=t,this.context=null,this.text=e,this.direction=null,this.render_options={cp1:8,cp2:12,text_shift_x:0,first_x_shift:0,last_x_shift:0,y_shift:7,tie_spacing:0,font:{family:"Arial",size:15,style:""}},this.font=this.render_options.font,this.setNotes(t)}setFont(t){return this.font=t,this}setDirection(t){return this.direction=t,this}setNotes(t){if(!t.first_note&&!t.last_note)throw new M.RuntimeError("BadArguments","Tie needs to have either first_note or last_note set.");if(t.first_indices||(t.first_indices=[0]),t.last_indices||(t.last_indices=[0]),t.first_indices.length!==t.last_indices.length)throw new M.RuntimeError("BadArguments","Tied notes must have similar index sizes");return this.first_note=t.first_note,this.first_indices=t.first_indices,this.last_note=t.last_note,this.last_indices=t.last_indices,this}isPartial(){return!this.first_note||!this.last_note}renderTie(t){if(t.first_ys.length===0||t.last_ys.length===0)throw new M.RERR("BadArguments","No Y-values to render");const e=this.context;let i=this.render_options.cp1,s=this.render_options.cp2;Math.abs(t.last_x_px-t.first_x_px)<10&&(i=2,s=8);const r=this.render_options.first_x_shift,o=this.render_options.last_x_shift,a=this.render_options.y_shift*t.direction;for(let l=0;lf&&Math.abs(c-f)<10?-6:0;if(this.first_note&&this.first_note.DYMusicScoreType==="jianpu"){if(this.getAttribute("type")==="TabTie")continue;c1){const e=new Vi(t);e.render_options.beam_width=3,e.render_options.partial_beam_length=4,this.beams.push(e)}return this}setNote(t){this.note=t}setWidth(t){this.width=t}getWidth(){return this.width}getGraceNotes(){return this.grace_notes}draw(){this.checkContext();const t=this.getNote();if(uc("Drawing grace note group for:",t),!(t&&this.index!==null))throw new M.RuntimeError("NoAttachedNote","Can't draw grace note without a parent note and parent note index.");if(this.setRendered(),this.alignSubNotesWithNote(this.getGraceNotes(),t),this.grace_notes.forEach(e=>{e.setContext(this.context).draw()}),this.beams.forEach(e=>{e.setContext(this.context).draw()}),this.show_slur){const e=this.getNote().getCategory()===ae.CATEGORY,i=e?Qn:ys;this.slur=new i({last_note:this.grace_notes[0],first_note:t,first_indices:[0],last_indices:[0]}),this.slur.render_options.cp2=12,this.slur.render_options.y_shift=(e?7:5)+this.render_options.slur_y_shift,this.slur.setContext(this.context).draw()}}}class Te extends St{static get CATEGORY(){return"strokes"}static get Type(){return{BRUSH_DOWN:1,BRUSH_UP:2,ROLL_DOWN:3,ROLL_UP:4,RASQUEDO_DOWN:5,RASQUEDO_UP:6,ARPEGGIO_DIRECTIONLESS:7}}static format(t,e){const i=e.left_shift,s=0;if(!t||t.length===0)return this;const r=t.map(l=>{const h=l.getNote();if(h instanceof ae){const{line:c,displaced:u}=h.getKeyProps()[l.getIndex()],f=u?h.getExtraLeftPx():0;return{line:c,shift:f,stroke:l}}else{const{str:c}=h.getPositions()[l.getIndex()];return{line:c,shift:0,stroke:l}}}),o=i,a=r.reduce((l,{stroke:h,shift:c})=>(h.setXShift(o+c),Math.max(h.getWidth()+s,l)),0);return e.left_shift+=a,!0}constructor(t,e){super(),this.setAttribute("type","Stroke"),this.note=null,this.options=M.Merge({},e),this.all_voices="all_voices"in this.options?this.options.all_voices:!0,this.note_end=null,this.index=null,this.type=t,this.position=St.Position.LEFT,this.render_options={font_scale:38,stroke_px:3,stroke_spacing:10},this.font={family:"serif",size:10,weight:"bold italic"},this.setXShift(0),this.setWidth(10)}getCategory(){return Te.CATEGORY}getPosition(){return this.position}addEndNote(t){return this.note_end=t,this}draw(){if(this.checkContext(),this.setRendered(),!(this.note&&this.index!=null))throw new M.RERR("NoAttachedNote","Can't draw stroke without a note and index.");const t=this.note.getModifierStartXY(this.position,this.index);let e=this.note.getYs(),i=t.y,s=t.y;const r=t.x-5,o=this.note.stave.options.spacing_between_lines_px,a=this.getModifierContext().getModifiers(this.note.getCategory());for(let d=0;dw.line-x.line);let g=0,m=0,S=0,b=null,y=null;for(c=0;cm?x:m):d===St.Position.RIGHT&&(u.setXShift(g),x+=E,S=x>S?x:S),b=w,y=f}return e.left_shift+=m,e.right_shift+=S,!0}constructor(t){super(),this.setAttribute("type","StringNumber"),this.note=null,this.last_note=null,this.index=null,this.string_number=t,this.setWidth(20),this.position=St.Position.ABOVE,this.x_shift=0,this.y_shift=0,this.x_offset=0,this.y_offset=0,this.dashed=!0,this.leg=Zt.LineEndType.NONE,this.radius=8,this.font={family:"sans-serif",size:10,weight:"bold"}}getCategory(){return tn.CATEGORY}getNote(){return this.note}setNote(t){return this.note=t,this}getIndex(){return this.index}setIndex(t){return this.index=t,this}setLineEndType(t){return t>=Zt.LineEndType.NONE&&t<=Zt.LineEndType.DOWN&&(this.leg=t),this}setStringNumber(t){return this.string_number=t,this}setOffsetX(t){return this.x_offset=t,this}setOffsetY(t){return this.y_offset=t,this}setLastNote(t){return this.last_note=t,this}setDashed(t){return this.dashed=t,this}draw(){const t=this.checkContext();if(!(this.note&&this.index!=null))throw new M.RERR("NoAttachedNote","Can't draw string number without a note and index.");this.setRendered();const e=this.note.stave.options.spacing_between_lines_px,i=this.note.getModifierStartXY(this.position,this.index);let s=i.x+this.x_shift+this.x_offset,r=i.y+this.y_shift+this.y_offset;switch(this.position){case St.Position.ABOVE:case St.Position.BELOW:{const a=this.note.getStemExtents();let l=a.topY,h=a.baseY+2;this.note.stem_direction===ae.STEM_DOWN&&(l=a.baseY,h=a.topY-2),this.position===St.Position.ABOVE?r=this.note.hasStem()?l-e*1.75:i.y-e*1.75:r=this.note.hasStem()?h+e*1.5:i.y+e*1.75,r+=this.y_shift+this.y_offset;break}case St.Position.LEFT:s-=this.radius/2+5;break;case St.Position.RIGHT:s+=this.radius/2+6;break;default:throw new M.RERR("InvalidPosition",`The position ${this.position} is invalid`)}t.save(),t.beginPath(),t.arc(s,r,this.radius,0,Math.PI*2,!1),t.lineWidth=1.5,t.stroke(),t.setFont(this.font.family,this.font.size,this.font.weight);const o=s-t.measureText(this.string_number).width/2;if(t.fillText(""+this.string_number,o,r+4.5),this.last_note!=null){const a=this.last_note.getStemX()-this.note.getX()+5;t.strokeStyle="#000000",t.lineCap="round",t.lineWidth=.6,this.dashed?Zt.drawDashedLine(t,s+10,r,s+a,r,[3,3]):Zt.drawDashedLine(t,s+10,r,s+a,r,[3,0]);let l,h;switch(this.leg){case Zt.LineEndType.UP:l=-10,h=this.dashed?[3,3]:[3,0],Zt.drawDashedLine(t,s+a,r,s+a,r+l,h);break;case Zt.LineEndType.DOWN:l=10,h=this.dashed?[3,3]:[3,0],Zt.drawDashedLine(t,s+a,r,s+a,r+l,h);break}}t.restore()}}function fc(...n){Ri.DEBUG&&M.L("Vex.Flow.Articulation",n)}const{ABOVE:Qi,BELOW:Vs}=St.Position,Ca=(n,t)=>n(t/.5)*.5,ao=(n,t)=>t===Qi?n<=5:n>=1,Ra=(n,t)=>ao(n,t)?t===Qi?Math.ceil:Math.floor:Math.round,dc=(n,t,e,i)=>{const s=Ca(Ra(t,e),t),r=n&&ao(s,e),o=s%1===0;return r&&o?s+.5*-i:s},lo=n=>{const t=n.getCategory();return t==="stavenotes"||t==="gracenotes"},Na=n=>{const t=n.getCategory();return t==="tabnotes"||t==="numberednotes"},pc=(n,t)=>{const e=n.getStave(),i=n.getStemDirection(),{topY:s,baseY:r}=n.getStemExtents();if(lo(n))return n.hasStem()?i===ft.UP?s:r:Math.min(...n.getYs());if(Na(n))return n.hasStem()&&i===ft.UP?s:e.getYForTopText(t);throw new M.RERR("UnknownCategory","Only can get the top and bottom ys of stavenotes and tabnotes")},mc=(n,t)=>{const e=n.getStave(),i=n.getStemDirection(),{topY:s,baseY:r}=n.getStemExtents();if(lo(n))return n.hasStem()?i===ft.UP?r:s:Math.max(...n.getYs());if(Na(n))return n.hasStem()?i===ft.UP?e.getYForBottomText(t):s:e.getYForBottomText(t);throw new M.RERR("UnknownCategory","Only can get the top and bottom ys of stavenotes and tabnotes")},gc=(n,t)=>{const e=t===Qi&&n.getStemDirection()===ft.UP||t===Vs&&n.getStemDirection()===ft.DOWN;return lo(n)?n.hasStem()&&e?.5:1:n.hasStem()&&e?1:0};class Ri extends St{static get CATEGORY(){return"articulations"}static get INITIAL_OFFSET(){return-.5}static format(t,e){if(!t||t.length===0)return!1;const i=l=>l.getPosition()===Qi,s=l=>l.getPosition()===Vs,r=.5,o=(l,h,c)=>Ca(Ra(h,c),l.glyph.getMetrics().height/10+r);t.filter(i).forEach(l=>{l.setTextLine(e.top_text_line),e.top_text_line+=o(l,e.top_text_line,Qi)}),t.filter(s).forEach(l=>{l.setTextLine(e.text_line),e.text_line+=o(l,e.text_line,Vs)});const a=t.map(l=>l.getWidth()).reduce((l,h)=>Math.max(h,l));return e.left_shift+=a/2,e.right_shift+=a/2,!0}static easyScoreHook({articulations:t},e,i){if(!t)return;const s={staccato:"a.",tenuto:"a-"};t.split(",").map(r=>r.trim().split(".")).map(([r,o])=>{const a={type:s[r]};return o&&(a.position=St.PositionString[o]),i.getFactory().Articulation(a)}).map(r=>e.addModifier(0,r))}constructor(t){if(super(),this.setAttribute("type","Articulation"),this.note=null,this.index=null,this.type=t,this.position=Vs,this.render_options={font_scale:38},this.articulation=V.articulationCodes(this.type),!this.articulation)throw new M.RERR("ArgumentError",`Articulation not found: ${this.type}`);this.glyph=new xt(this.articulation.code,this.render_options.font_scale),this.setWidth(this.glyph.getMetrics().width)}getCategory(){return Ri.CATEGORY}draw(){const{note:t,index:e,position:i,glyph:s,articulation:{between_lines:r},text_line:o,context:a}=this;if(this.checkContext(),!t||e==null)throw new M.RERR("NoAttachedNote","Can't draw Articulation without a note and index.");this.setRendered();const l=t.getStave(),h=l.getSpacingBetweenLines(),c=t.getCategory()==="tabnotes",{x:u}=t.getModifierStartXY(i,e),f=!r||c,d=gc(t,i);let p={[Qi]:()=>{s.setOrigin(.5,1);const g=pc(t,o)-(o+d)*h+(this.y_shift||0);return f?Math.min(l.getYForTopText(Ri.INITIAL_OFFSET),g):g},[Vs]:()=>{s.setOrigin(.5,0);const g=mc(t,o)+(o+d)*h;return f?Math.max(l.getYForBottomText(Ri.INITIAL_OFFSET),g):g}}[i]();if(!c){const g=i===Qi?-1:1,m=c?t.positions[e].str:t.getKeyProps()[e].line,b=(t.getYs()[e]-p)/h+m,y=dc(r,b,i,g);ao(y,i)&&s.setOrigin(.5,.5),p+=Math.abs(y-b)*h*g}fc(`Rendering articulation at (x: ${u}, y: ${p})`),s.render(a,u,p)}}class xs extends Ta{static getNextContext(t){const e=t.tContexts,i=e.indexOf(t);return e[i+1]}constructor(){super(),this.setAttribute("type","TickContext"),this.currentTick=new Rt(0,1),this.maxTicks=new Rt(0,1),this.minTicks=null,this.padding=3,this.x=0,this.xBase=0,this.xOffset=0,this.tickables=[],this.notePx=0,this.extraLeftPx=0,this.extraRightPx=0,this.tContexts=[]}getX(){return this.x}setX(t){return this.x=t,this.xBase=t,this.xOffset=0,this}getXBase(){return this.xBase}setXBase(t){this.xBase=t,this.x=t+this.xOffset}getXOffset(){return this.xOffset}setXOffset(t){this.xOffset=t,this.x=this.xBase+t}getWidth(){return this.width+this.padding*2}setPadding(t){return this.padding=t,this}getMaxTicks(){return this.maxTicks}getMinTicks(){return this.minTicks}getTickables(){return this.tickables}getCenterAlignedTickables(){return this.tickables.filter(t=>t.isCenterAligned())}getMetrics(){const{width:t,notePx:e,extraLeftPx:i,extraRightPx:s}=this;return{width:t,notePx:e,extraLeftPx:i,extraRightPx:s}}getCurrentTick(){return this.currentTick}setCurrentTick(t){this.currentTick=t,this.preFormatted=!1}getExtraPx(){let t=0,e=0,i=0,s=0;for(let r=0;r0&&s--;for(let l=0;l{Ho("Preformatting ModifierContext: ",t.CATEGORY),t.format(this.getModifiers(t.CATEGORY),this.state,this)}),this.width=this.state.left_shift+this.state.right_shift,this.preFormatted=!0)}postFormat(){this.postFormatted||this.POSTFORMAT.forEach(t=>{Ho("Postformatting ModifierContext: ",t.CATEGORY),t.postFormat(this.getModifiers(t.CATEGORY),this)})}}function yc(...n){si.DEBUG&&M.L("Vex.Flow.Formatter",n)}function Aa(n,t){var i,s;const e=n[t+1];return e&&((i=e==null?void 0:e.keys)==null?void 0:i.includes("b/4"))||((s=e==null?void 0:e.keys)==null?void 0:s.includes("r/4"))?Aa(n,t+1):e}function Xo(n,t,e,i,s=0){let r=t;for(e+=1;e4.5||r<1.5)){const a=n[e].stem;if(a)if(a.stem_direction>0){const l=r<1.5?Math.abs(r-1.5)*s:0;a.setResetHeight(l)}else{const l=r>4.5?Math.abs(r-4.5)*s:0;a.setResetHeight(l)}}return r}function Yo(n,t,e){if(!n||!n.length)throw new M.RERR("BadArgument","No voices to format");const i=n[0].getTotalTicks(),s=n.reduce((l,h)=>{if(!h.getTotalTicks().equals(i))throw new M.RERR("TickMismatch","Voices should have same total note duration in ticks.");if(h.getMode()===ye.Mode.STRICT&&!h.isComplete())throw new M.RERR("IncompleteVoice","Voice does not have enough notes.");return Math.max(l,Rt.LCM(l,h.getResolutionMultiplier()))},1),r={},o=[],a=[];return n.forEach(l=>{const h=new Rt(0,s);l.getTickables().forEach(c=>{const u=h.numerator;if(!r[u]){const f=new t;a.push(f),r[u]=f}e(c,r[u]),o.push(u),h.add(c.getTicks())})}),{map:r,array:a,list:M.SortAndUnique(o,(l,h)=>l-h,(l,h)=>l===h),resolutionMultiplier:s}}class si{static SimpleFormat(t,e=0,{paddingBetween:i=10}={}){t.reduce((s,r)=>{r.addToModifierContext(new Ys);const o=new xs().addTickable(r).preFormat(),a=o.getExtraPx();return o.setX(s+a.left),s+o.getWidth()+a.right+i},e)}static plotDebugging(t,e,i,s,r){const o=i+Ie.STAVEPADDING,a=e.contextGaps;function l(h,c,u){t.beginPath(),t.setStrokeStyle(u),t.setFillStyle(u),t.setLineWidth(1),t.fillRect(h,s,c-h,r-s)}t.save(),t.setFont("Arial",8,""),a.gaps.forEach(h=>{l(o+h.x1,o+h.x2,"#aaa"),t.fillText(Math.round(h.x2-h.x1),o+h.x1,r+12)}),t.fillText(Math.round(a.total)+"px",o-20,r+12),t.setFillStyle("red"),t.fillText("Loss: "+e.lossHistory.map(h=>Math.round(h)),o-20,r+22),t.restore()}static FormatAndDraw(t,e,i,s){const r={auto_beam:!1,align_rests:!1};typeof s=="object"?M.Merge(r,s):typeof s=="boolean"&&(r.auto_beam=s);const o=new ye(V.TIME4_4).setMode(ye.Mode.SOFT).addTickables(i),a=r.auto_beam?Vi.applyAndGetBeams(o):[];return new si().joinVoices([o],{align_rests:r.align_rests}).formatToStave([o],e,{align_rests:r.align_rests,stave:e}),o.setStave(e).draw(t,e),a.forEach(l=>l.setContext(t).draw()),o.getBoundingBox()}static FormatAndDrawTab(t,e,i,s,r,o,a){const l={auto_beam:o,align_rests:!1};typeof a=="object"?M.Merge(l,a):typeof a=="boolean"&&(l.auto_beam=a);const h=new ye(V.TIME4_4).setMode(ye.Mode.SOFT).addTickables(r),c=new ye(V.TIME4_4).setMode(ye.Mode.SOFT).addTickables(s),u=l.auto_beam?Vi.applyAndGetBeams(h):[];new si().joinVoices([h],{align_rests:l.align_rests}).joinVoices([c]).formatToStave([h,c],i,{align_rests:l.align_rests}),h.draw(t,i),c.draw(t,e),u.forEach(f=>f.setContext(t).draw()),new Bt(i,e).setContext(t).draw()}static AlignRestsToNotes(t,e,i){return t.forEach((s,r)=>{if(s instanceof ae&&s.isRest()){if(s.tuplet&&!i)return;if(s.getGlyph().position.toUpperCase(),s.glyph.code_head==="va5"||s.glyph.code_head==="v3c"){const o=s.glyph.code_head==="va5"?10:20,a=t[r-1],l=Aa(t,r);let h=!1;if(a&&l&&a.beam&&l.beam&&(h=a.beam.notes.includes(l)),e||s.beam!=null||h){const c=s.getKeyProps()[0];if(r===0)c.line=Xo(t,c.line,r,!1,o),s.setKeyLine(0,c.line);else if(r>0&&rsi.AlignRestsToNotes(i.getTickables(),e))}preCalculateMinTotalWidth(t){if(this.hasMinTotalWidth)return this.minTotalWidth;if(!this.tickContexts){if(!t)throw new M.RERR("BadArgument","'voices' required to run preCalculateMinTotalWidth");this.createTickContexts(t)}const{list:e,map:i}=this.tickContexts;return this.minTotalWidth=e.map(s=>{const r=i[s];return r.preFormat(),r.getWidth()}).reduce((s,r)=>s+r,0),this.hasMinTotalWidth=!0,this.minTotalWidth}getMinTotalWidth(){if(!this.hasMinTotalWidth)throw new M.RERR("NoMinTotalWidth","Call 'preCalculateMinTotalWidth' or 'preFormat' before calling 'getMinTotalWidth'");return this.minTotalWidth}createModifierContexts(t){const e=Yo(t,Ys,(i,s)=>i.addToModifierContext(s));return this.modiferContexts=e,e}createTickContexts(t){const e=Yo(t,xs,(i,s)=>s.addTickable(i));return e.array.forEach(i=>{i.tContexts=e.array}),this.totalTicks=t[0].getTicksUsed().clone(),this.tickContexts=e,e}preFormat(t=0,e,i,s){const r=this.tickContexts,{list:o,map:a,resolutionMultiplier:l}=r;i&&s&&i.forEach(g=>g.setStave(s).preFormat());let h=0,c=0;const u=t/2;if(this.minTotalWidth=0,o.forEach(g=>{const m=a[g];e&&m.setContext(e),m.preFormat();const S=m.getWidth();this.minTotalWidth+=S;const b=m.getMetrics();h=h+c+b.extraLeftPx,m.setX(h),c=S-b.extraLeftPx}),this.minTotalWidth=h+c,this.hasMinTotalWidth=!0,t<=0)return;const d=(t-this.minTotalWidth)/(this.totalTicks.value()*l);let p=0;o.forEach((g,m)=>{const S=o[m-1]||0,b=a[g];p+=(g-S)*d,b.setX(b.getX()+p),b.getCenterAlignedTickables().forEach(x=>{x.center_x_shift=u-b.getX()})}),o.length!==1&&(this.justifyWidth=t,this.lossHistory=[],this.evaluate())}evaluate(){const t=this.justifyWidth;this.contextGaps={total:0,gaps:[]},this.tickContexts.list.forEach((r,o)=>{if(o===0)return;const a=this.tickContexts.list[o-1],l=this.tickContexts.map[a],h=this.tickContexts.map[r],c=l.getMetrics(),u=l.getX()+c.width,f=h.getX(),d=f-u;this.contextGaps.total+=d,this.contextGaps.gaps.push({x1:u,x2:f}),h.getFormatterMetrics().freedom.left=d,l.getFormatterMetrics().freedom.right=d});const e=this.durationStats={};function i(r,o){const a=e[r];a===void 0?e[r]={mean:o,count:1}:(a.count+=1,a.mean=(a.mean+o)/2)}this.voices.forEach(r=>{r.getTickables().forEach((o,a,l)=>{const h=o.getTicks().clone().simplify().toString(),c=o.getMetrics(),u=o.getFormatterMetrics(),f=o.getX()+c.noteWidth+c.modRightPx+c.extraRightPx;let d=0;if(a{r.getTickables().forEach(o=>{const a=o.getTicks().clone().simplify().toString(),l=o.getFormatterMetrics();l.iterations+=1,l.space.deviation=l.space.used-e[a].mean,l.duration=a,l.space.mean=e[a].mean,s+=Math.pow(e[a].mean,2)})}),this.totalCost=Math.sqrt(s),this.lossHistory.push(this.totalCost),this}tune(){const t=s=>s.reduce((r,o)=>r+o);function e(s,r,o,a){s.setX(s.getX()+a),s.getFormatterMetrics().freedom.left+=a,s.getFormatterMetrics().freedom.right-=a,r&&(r.getFormatterMetrics().freedom.right+=a),o&&(o.getFormatterMetrics().freedom.left-=a)}let i=0;return this.tickContexts.list.forEach((s,r,o)=>{const a=this.tickContexts.map[s],l=r>0?this.tickContexts.map[o[r-1]]:null,h=rf.getFormatterMetrics().space.deviation));c>0?i=-Math.min(a.getFormatterMetrics().freedom.right,Math.abs(c)):c<0&&(h?i=Math.min(h.getFormatterMetrics().freedom.right,Math.abs(c)):i=0);const u=Math.min(5,Math.abs(i));i=i>0?u:-u}),this.evaluate()}postFormat(){const t=e=>e.list.forEach(i=>e.map[i].postFormat());return t(this.modiferContexts),t(this.tickContexts),this}joinVoices(t){return this.createModifierContexts(t),this.hasMinTotalWidth=!1,this}format(t,e,i){const s={align_rests:!1,context:null,stave:null};return M.Merge(s,i),this.voices=t,this.alignRests(t,s.align_rests),this.createTickContexts(t),this.preFormat(e,s.context,t,s.stave),s.stave&&this.postFormat(),this}formatToStave(t,e,i){const s=e.getNoteEndX()-e.getNoteStartX()-10;yc("Formatting voices to width: ",s);const r={context:e.getContext()};return M.Merge(r,i),this.format(t,s,r)}}class Vt extends he{static get Position(){return{LEFT:1,RIGHT:2,ABOVE:3,BELOW:4,BEGIN:5,END:6}}constructor(){super(),this.setAttribute("type","StaveModifier"),this.padding=10,this.position=Vt.Position.ABOVE,this.layoutMetrics=null}getPosition(){return this.position}setPosition(t){return this.position=t,this}getStave(){return this.stave}setStave(t){return this.stave=t,this}getWidth(){return this.width}setWidth(t){return this.width=t,this}getX(){return this.x}setX(t){return this.x=t,this}getCategory(){return""}makeSpacer(t){return{getContext(){return!0},setStave(){},renderToStave(){},getMetrics(){return{width:t}}}}placeGlyphOnLine(t,e,i){t.setYShift(e.getYForLine(i)-e.getYForGlyphs())}getPadding(t){return t!==void 0&&t<2?0:this.padding}setPadding(t){return this.padding=t,this}setLayoutMetrics(t){return this.layoutMetrics=t,this}getLayoutMetrics(){return this.layoutMetrics}}class Xt extends Vt{static get CATEGORY(){return"barlines"}static get type(){return{SINGLE:1,DOUBLE:2,END:3,REPEAT_BEGIN:4,REPEAT_END:5,REPEAT_BOTH:6,NONE:7}}static get typeString(){return{single:Xt.type.SINGLE,double:Xt.type.DOUBLE,end:Xt.type.END,repeatBegin:Xt.type.REPEAT_BEGIN,repeatEnd:Xt.type.REPEAT_END,repeatBoth:Xt.type.REPEAT_BOTH,none:Xt.type.NONE}}constructor(t){super(),this.setAttribute("type","Barline"),this.thickness=V.STAVE_LINE_THICKNESS;const e=Xt.type;this.widths={},this.widths[e.SINGLE]=5,this.widths[e.DOUBLE]=5,this.widths[e.END]=5,this.widths[e.REPEAT_BEGIN]=5,this.widths[e.REPEAT_END]=5,this.widths[e.REPEAT_BOTH]=5,this.widths[e.NONE]=5,this.paddings={},this.paddings[e.SINGLE]=0,this.paddings[e.DOUBLE]=0,this.paddings[e.END]=0,this.paddings[e.REPEAT_BEGIN]=15,this.paddings[e.REPEAT_END]=15,this.paddings[e.REPEAT_BOTH]=15,this.paddings[e.NONE]=0,this.layoutMetricsMap={},this.layoutMetricsMap[e.SINGLE]={xMin:0,xMax:1,paddingLeft:5,paddingRight:5},this.layoutMetricsMap[e.DOUBLE]={xMin:-3,xMax:1,paddingLeft:5,paddingRight:5},this.layoutMetricsMap[e.END]={xMin:-5,xMax:1,paddingLeft:5,paddingRight:5},this.layoutMetricsMap[e.REPEAT_END]={xMin:-10,xMax:1,paddingLeft:5,paddingRight:5},this.layoutMetricsMap[e.REPEAT_BEGIN]={xMin:-2,xMax:10,paddingLeft:5,paddingRight:5},this.layoutMetricsMap[e.REPEAT_BOTH]={xMin:-10,xMax:10,paddingLeft:5,paddingRight:5},this.layoutMetricsMap[e.NONE]={xMin:0,xMax:0,paddingLeft:5,paddingRight:5},this.setPosition(Vt.Position.BEGIN),this.setType(t)}getCategory(){return Xt.CATEGORY}getType(){return this.type}setType(t){return this.type=typeof t=="string"?Xt.typeString[t]:t,this.setWidth(this.widths[this.type]),this.setPadding(this.paddings[this.type]),this.setLayoutMetrics(this.layoutMetricsMap[this.type]),this}draw(t){switch(t.checkContext(),this.setRendered(),this.type){case Xt.type.SINGLE:this.drawVerticalBar(t,this.x,!1);break;case Xt.type.DOUBLE:this.drawVerticalBar(t,this.x,!0);break;case Xt.type.END:this.drawVerticalEndBar(t,this.x);break;case Xt.type.REPEAT_BEGIN:this.drawRepeatBar(t,this.x,!0),t.getX()!==this.x&&this.drawVerticalBar(t,t.getX());break;case Xt.type.REPEAT_END:this.drawRepeatBar(t,this.x,!1);break;case Xt.type.REPEAT_BOTH:this.drawRepeatBar(t,this.x,!1),this.drawRepeatBar(t,this.x,!0);break}}drawVerticalBar(t,e,i){t.checkContext();const s=t.getTopLineTopY(),r=t.getBottomLineBottomY();i&&t.context.fillRect(e-3,s,1,r-s),t.context.fillRect(e,s,1,r-s)}drawVerticalEndBar(t,e){t.checkContext();const i=t.getTopLineTopY(),s=t.getBottomLineBottomY();t.context.fillRect(e-5,i,1,s-i),t.context.fillRect(e-2,i,3,s-i)}drawRepeatBar(t,e,i){t.checkContext();const s=t.getTopLineTopY(),r=t.getBottomLineBottomY();let o=3;i||(o=-5),t.context.fillRect(e+o,s,1,r-s),t.context.fillRect(e-2,s,3,r-s);const a=2;i?o+=4:o-=4;const l=e+o+a/2;let h=(t.getNumLines()-1)*t.getSpacingBetweenLines();h=h/2-t.getSpacingBetweenLines()/2;let c=s+h+a/2;t.context.beginPath(),t.context.arc(l,c,a,0,Math.PI*2,!1),t.context.fill(),c+=t.getSpacingBetweenLines(),t.context.beginPath(),t.context.arc(l,c,a,0,Math.PI*2,!1),t.context.fill()}}class _e extends Vt{static get CATEGORY(){return"repetitions"}static get type(){return{NONE:1,CODA_LEFT:2,CODA_RIGHT:3,SEGNO_LEFT:4,SEGNO_RIGHT:5,DC:6,DC_AL_CODA:7,DC_AL_FINE:8,DS:9,DS_AL_CODA:10,DS_AL_FINE:11,FINE:12,TO_CODA:13}}constructor(t,e,i){super(),this.setAttribute("type","Repetition"),this.symbol_type=t,this.x=e,this.x_shift=0,this.y_shift=i,this.font={family:"times",size:12,weight:"bold italic"}}getCategory(){return _e.CATEGORY}setShiftX(t){return this.x_shift=t,this}setShiftY(t){return this.y_shift=t,this}setX(t){return this.x=t,this}draw(t,e){switch(this.setRendered(),this.symbol_type){case _e.type.CODA_RIGHT:this.drawCodaFixed(t,e+t.width);break;case _e.type.CODA_LEFT:this.drawSymbolText(t,e,"Coda",!1);break;case _e.type.SEGNO_LEFT:this.drawSignoFixed(t,e);break;case _e.type.SEGNO_RIGHT:this.drawSignoFixed(t,e+t.width);break;case _e.type.DC:this.drawSymbolText(t,e,"D.C.",!1);break;case _e.type.DC_AL_CODA:this.drawSymbolText(t,e,"D.C. al Coda",!0);break;case _e.type.DC_AL_FINE:this.drawSymbolText(t,e,"D.C. al Fine",!1);break;case _e.type.DS:this.drawSymbolText(t,e,"D.S.",!1);break;case _e.type.DS_AL_CODA:this.drawSymbolText(t,e,"D.S. al Coda",!0);break;case _e.type.DS_AL_FINE:this.drawSymbolText(t,e,"D.S. al Fine",!1);break;case _e.type.FINE:this.drawSymbolText(t,e,"Fine",!1);break;case _e.type.TO_CODA:this.drawSymbolText(t,e,"To Coda",!0);break}return this}drawCodaFixed(t,e){const i=t.getYForTopText(t.options.num_lines)+this.y_shift;return xt.renderGlyph(t.context,this.x+e+this.x_shift,i+25,40,"v4d",!0),this}drawSignoFixed(t,e){const i=t.getYForTopText(t.options.num_lines)+this.y_shift;return xt.renderGlyph(t.context,this.x+e+this.x_shift,i+25,30,"v8c",!0),this}drawSymbolText(t,e,i,s){const r=t.checkContext();r.save(),r.setFont(this.font.family,this.font.size,this.font.weight);let o=0+this.x_shift,a=e+this.x_shift;this.symbol_type===_e.type.CODA_LEFT?(o=this.x+t.options.vertical_bar_width,a=o+r.measureText(i).width+12):(this.x_shift=-(o+r.measureText(i).width+12+t.options.vertical_bar_width+12),o=this.x+this.x_shift+t.options.vertical_bar_width,a=o+r.measureText(i).width+12);const l=t.getYForTopText(t.options.num_lines)+this.y_shift+25;return s&&xt.renderGlyph(r,a,l,40,"v4d",!0),r.fillText(i,o,l+5),r.restore(),this}}class ho extends Vt{static get CATEGORY(){return"stavesection"}constructor(t,e,i){super(),this.setAttribute("type","StaveSection"),this.setWidth(16),this.section=t,this.x=e,this.shift_x=0,this.shift_y=i,this.font={family:"sans-serif",size:12,weight:"bold"}}getCategory(){return ho.CATEGORY}setStaveSection(t){return this.section=t,this}setShiftX(t){return this.shift_x=t,this}setShiftY(t){return this.shift_y=t,this}draw(t,e){const i=t.checkContext();this.setRendered(),i.save(),i.lineWidth=2,i.setFont(this.font.family,this.font.size,this.font.weight);const s=i.measureText(""+this.section),r=s.width,o=s.height;let a=r+6;a<18&&(a=18);const l=o,h=t.getYForTopText(3)+this.shift_y;let c=this.x+e;return i.beginPath(),i.lineWidth=2,i.rect(c,h+o/4,a,l),i.stroke(),c+=(a-r)/2,i.fillText(""+this.section,c,h+16),i.restore(),this}}class $n extends Vt{static get CATEGORY(){return"stavetempo"}constructor(t,e,i){super(),this.setAttribute("type","StaveTempo"),this.tempo=t,this.position=St.Position.ABOVE,this.x=e,this.shift_x=10,this.shift_y=i,this.font={family:"times",size:14,weight:"bold"},this.render_options={glyph_font_scale:30}}getCategory(){return $n.CATEGORY}setTempo(t){return this.tempo=t,this}setShiftX(t){return this.shift_x=t,this}setShiftY(t){return this.shift_y=t,this}draw(t,e){const i=t.checkContext();this.setRendered();const s=this.render_options,r=s.glyph_font_scale/38,o=this.tempo.name,a=this.tempo.duration,l=this.tempo.dots,h=this.tempo.bpm,c=this.font;let u=this.x+this.shift_x+e;const f=t.getYForTopText(1)+this.shift_y;if(i.save(),i.openGroup("stavetempo",null,{}),o&&(i.setFont(c.family,c.size,c.weight),i.fillText(o,u,f),u+=i.measureText(o).width),a&&h){i.setFont(c.family,c.size,"normal"),o&&(u+=i.measureText(" ").width,i.fillText("(",u,f),u+=i.measureText("(").width);const d=V.getGlyphProps(a);if(u+=3*r,xt.renderGlyph(i,u,f,s.glyph_font_scale,d.code_head),u+=d.getWidth()*r,d.stem){let p=30;d.beam_count&&(p+=3*(d.beam_count-1)),p*=r;const g=f-p;i.fillRect(u-r,g,r,p),d.flag&&(xt.renderGlyph(i,u,g,s.glyph_font_scale,d.code_flag_upstem),l||(u+=6*r))}for(let p=0;p=t.line?l.above:l.below)}this.placeGlyphOnLine(s,this.stave,t.line),this.glyphs.push(s);const o=this.xPositions[this.xPositions.length-1],a=s.getMetrics().width+r;this.xPositions.push(o+a),this.width+=a}cancelKey(t){return this.formatted=!1,this.cancelKeySpec=t,this}convertToCancelAccList(t){const e=V.keySignature(t),i=this.accList.length>0&&e.length>0&&e[0].type!==this.accList[0].type,s=i?e.length:e.length-this.accList.length;if(s<1)return;const r=[];for(let o=0;o0?t[0].type:null;let i;if(this.cancelKeySpec&&(i=this.convertToCancelAccList(this.cancelKeySpec)),this.alterKeySpec&&this.convertToAlterAccList(this.alterKeySpec),this.accList.length>0){const s=(this.position===Vt.Position.END?this.stave.endClef:this.stave.clef)||this.stave.clef;i&&this.convertAccLines(s,i.type,i.accList),this.convertAccLines(s,e,t);for(let r=0;r0){this.stave.context.openGroup("keysignature");for(let t=0;t{const t=n.split("/").filter(e=>e!=="");if(t.length!==2)throw new M.RERR("BadTimeSignature",`Invalid time spec: ${n}. Must be in the form "/"`);t.forEach(e=>{if(isNaN(Number(e)))throw new M.RERR("BadTimeSignature",`Invalid time spec: ${n}. Must contain two valid numbers.`)})};class Wi extends Vt{static get CATEGORY(){return"timesignatures"}static get glyphs(){return{C:{code:"v41",point:40,line:2},"C|":{code:"vb6",point:40,line:2}}}constructor(t=null,e=15,i=!0){if(super(),this.setAttribute("type","TimeSignature"),this.validate_args=i,t===null)return;const s=e;this.point=40,this.topLine=2,this.bottomLine=4,this.setPosition(Vt.Position.BEGIN),this.setTimeSig(t),this.setWidth(this.timeSig.glyph.getMetrics().width),this.setPadding(s)}getCategory(){return Wi.CATEGORY}parseTimeSpec(t){if(t==="C"||t==="C|"){const{line:s,code:r,point:o}=Wi.glyphs[t];return{line:s,num:!1,glyph:new xt(r,o)}}this.validate_args&&vc(t);const[e,i]=t.split("/").map(s=>s.split(""));return{num:!0,glyph:this.makeTimeSignatureGlyph(e,i)}}makeTimeSignatureGlyph(t,e){const i=new xt("v0",this.point);i.topGlyphs=[],i.botGlyphs=[];let s=0;for(let u=0;ur?s:r,a=i.getMetrics().x_min;i.getMetrics=()=>({x_min:a,x_max:a+o,width:o});const l=(o-s)/2,h=(o-r)/2,c=this;return i.renderToStave=function(f){let d=f+l;for(let p=0;pe.visible).filter(Boolean).length}getOptions(){return this.options}setNoteStartX(t){this.formatted||this.format(),this.setStartX(t);const e=this.modifiers[0];return e.setX(this.start_x-e.getWidth()),this}setStartX(t){this.start_x=t}getNoteStartX(){return this.formatted||this.format(),this.start_x}getNoteEndX(){return this.formatted||this.format(),this.end_x}getTieStartX(){return this.start_x}getTieEndX(){return this.x+this.width}getX(){return this.x}getNumLines(){return this.options.num_lines}setNumLines(t){return this.options.num_lines=parseInt(t,10),this.resetLines(),this}setY(t){return this.y=t,this}getTopLineTopY(){return this.getYForLine(0)-V.STAVE_LINE_THICKNESS/2}getBottomLineBottomY(){return this.getLines()===2?this.getYForLine(6)+V.STAVE_LINE_THICKNESS/2:this.getYForLine(this.getNumLines()-1)+V.STAVE_LINE_THICKNESS/2}setX(t){const e=t-this.x;this.formatted=!1,this.x=t,this.start_x+=e,this.end_x+=e;for(let i=0;ii.getWidth()&&(e-=i.getWidth()),e}setRepetitionTypeLeft(t,e){return this.modifiers.push(new _e(t,this.x,e)),this}setRepetitionTypeRight(t,e){return this.modifiers.push(new _e(t,this.x,e)),this}setVoltaType(t,e,i){if(t===2)Le.type===2&&Le.stave.modifiers.push(new ti(Le.type,Le.number_t,Le.x,Le.y)),Le={stave:this,type:t,number_t:e,MeasureNumber:this.MeasureNumber,y:i,x:this.x};else if(t===4){let s=this.MeasureNumber-Le.MeasureNumber,r=Math.max(Le.y,i);for(let o=0;o<=s;o++)fr[Le.MeasureNumber+o]={type:o===0?2:o===s?4:0,number_t:e,y:r};Le={}}else this.modifiers.push(new ti(t,e,this.x,i));return this}drawVolta(){let t=fr[this.MeasureNumber];t&&(this.modifiers.push(new ti(t.type,t.number_t,this.x,t.y)),delete fr[this.MeasureNumber]),Le.type&&Le.MeasureNumber==this.MeasureNumber&&(this.modifiers.push(new ti(Le.type,Le.number_t,this.x,Le.y)),Le={})}setSection(t,e,i=0,s=12){const r=new ho(t,this.x+i,e);return r.font.size=s,this.modifiers.push(r),this}setTempo(t,e){return this.modifiers.push(new $n(t,this.x,e)),this}setText(t,e,i){let s=new co(t,e,i);return s.setFont({family:"Arial",size:14,weight:"normal"}),this.modifiers.push(s),this}getHeight(){return this.height}getSpacingBetweenLines(){return this.options.spacing_between_lines_px}getBoundingBox(){return new es(this.x,this.y,this.width,this.getBottomY()-this.y)}getBottomY(){const t=this.options,e=t.spacing_between_lines_px;return this.getYForLine(t.num_lines)+t.space_below_staff_ln*e}getBottomLineY(){return this.getYForLine(this.options.num_lines)}getYForLine(t){const e=this.options,i=e.spacing_between_lines_px,s=e.space_above_staff_ln;return this.y+t*i+s*i}getLineForY(t){const e=this.options,i=e.spacing_between_lines_px,s=e.space_above_staff_ln;return(t-this.y)/i-s}getYForTopText(t){const e=t||0;return this.getYForLine(-e-this.options.top_text_position)}getYForBottomText(t){const e=t||0;return this.getYForLine(this.options.bottom_text_position+e)}getYForNote(t){const e=this.options,i=e.spacing_between_lines_px,s=e.space_above_staff_ln;return this.y+s*i+5*i-t*i}getYForGlyphs(){return this.getYForLine(3)}addModifier(t,e,i){return e!==void 0&&t.setPosition(e),i&&(this.timeSignature.numerator=i.numerator,this.timeSignature.denominator=i.denominator),t.setStave(this),this.formatted=!1,this.modifiers.push(t),this}addEndModifier(t){return this.addModifier(t,Vt.Position.END),this}setBegBarType(t){const{SINGLE:e,REPEAT_BEGIN:i,NONE:s}=Xt.type;return(t===e||t===i||t===s)&&(this.modifiers[0].setType(t),this.formatted=!1),this}setEndBarType(t){return t!==Xt.type.REPEAT_BEGIN&&(this.modifiers[1].setType(t),this.formatted=!1),this}setClef(t,e,i,s){s===void 0&&(s=Vt.Position.BEGIN),s===Vt.Position.END?this.endClef=t:this.clef=t;const r=this.getModifiers(s,hi.CATEGORY);return r.length===0?this.addClef(t,e,i,s):r[0].setType(t,e,i),this}setEndClef(t,e,i){return this.setClef(t,e,i,Vt.Position.END),this}setKeySignature(t,e,i){this.options.keySignature=t,i===void 0&&(i=Vt.Position.BEGIN);const s=this.getModifiers(i,ss.CATEGORY);return s.length===0?this.options.DYMusicScoreType!=="jianpu"&&this.addKeySignature(t,e,i):s[0].setKeySig(t,e),this}setEndKeySignature(t,e){return this.setKeySignature(t,e,Vt.Position.END),this}setTimeSignature(t,e,i){i===void 0&&(i=Vt.Position.BEGIN);const s=this.getModifiers(i,Wi.CATEGORY);return s.length===0?this.addTimeSignature(t,e,i):s[0].setTimeSig(t),this}setEndTimeSignature(t,e){return this.setTimeSignature(t,e,Vt.Position.END),this}addKeySignature(t,e,i){return i===void 0&&(i=Vt.Position.BEGIN),this.addModifier(new ss(t,e).setPosition(i),i),this}addClef(t,e,i,s){return s===void 0||s===Vt.Position.BEGIN?this.clef=t:s===Vt.Position.END&&(this.endClef=t),this.addModifier(new hi(t,e,i),s),this}addEndClef(t,e,i){return this.addClef(t,e,i,Vt.Position.END),this}addTimeSignature(t,e,i){return this.addModifier(new Wi(t,e),i),this}addEndTimeSignature(t,e){return this.addTimeSignature(t,e,Vt.Position.END),this}addTrebleGlyph(){return this.addClef("treble"),this}getModifiers(t,e){return t===void 0&&e===void 0?this.modifiers:this.modifiers.filter(i=>(t===void 0||t===i.getPosition())&&(e===void 0||e===i.getCategory()))}sortByCategory(t,e){for(let i=t.length-1;i>=0;i--)for(let s=0;se[t[s+1].getCategory()]){const r=t[s];t[s]=t[s+1],t[s+1]=r}}format(){const t=this.modifiers[0],e=this.modifiers[1],i=this.getModifiers(Vt.Position.BEGIN),s=this.getModifiers(Vt.Position.END);this.sortByCategory(i,{barlines:0,clefs:1,keysignatures:2,timesignatures:3}),this.sortByCategory(s,{timesignatures:0,keysignatures:1,barlines:2,clefs:3}),i.length>1&&t.getType()===Xt.type.REPEAT_BEGIN&&(i.push(i.splice(0,1)[0]),i.splice(0,0,new Xt(Xt.type.SINGLE))),s.indexOf(e)>0&&s.splice(0,0,new Xt(Xt.type.NONE));let r,o,a,l=0,h=this.x;for(let f=0;f{o.includes(l)?a.visible=!0:a.visible=!1})}for(let o=0;othis.drawStaveTempo()),this.measure>0){this.context.save(),this.context.setFont(this.font.family,this.font.size,this.font.weight);const o=this.context.measureText(""+this.measure).width;s=this.getYForTopText(0)+3,this.context.fillText(""+this.measure,this.x-o/2,s),this.context.restore()}return this}drawStaveTempo(){if(!this.staveTempos.length)return;const t=document.querySelector(`#${this.attrs.id}`);if(!t)return;const e=t.parentElement.getBBox(),i=this.getYForLine(0),s=t.parentElement.parentElement.querySelectorAll(".vf-curve");if(s.length){const r=this.x+this.staveTempos[0].shift_x+this.getModifierXShift(0),o=this.getYForTopText(1)+e.y-i+5;s.forEach(a=>{const l=a.getBBox();l.x-10r&&l.y-10o&&(e.y=l.y+5)})}for(let r=0;r=0&&this.timeSignature.numerator){let t=40,e=0;this.MeasureNumber<2&&(t=70,e=-72),this.setText(`${this.timeSignature.numerator}`,1,{justification:1,shift_x:t,shift_y:e-13}),this.setText("\u1173",1,{justification:1,shift_x:t+3,shift_y:e-2}),this.setText(`${this.timeSignature.denominator}`,1,{justification:1,shift_x:t,shift_y:e+8})}}drawVertical(t,e){this.drawVerticalFixed(this.x+t,e)}drawVerticalFixed(t,e){this.checkContext();const i=this.getYForLine(0),s=this.getYForLine(this.options.num_lines-1);e&&this.context.fillRect(t-3,i,1,s-i+1),this.context.fillRect(t,i,1,s-i+1)}drawVerticalBar(t){this.drawVerticalBarFixed(this.x+t,!1)}drawVerticalBarFixed(t){this.checkContext();const e=this.getYForLine(0),i=this.getYForLine(this.options.num_lines-1);this.context.fillRect(t,e,1,i-e+1)}getConfigForLines(){return this.options.line_config}setConfigForLine(t,e){if(t>=this.options.num_lines||t<0)throw new M.RERR("StaveConfigError","The line number must be within the range of the number of lines in the Stave.");if(e.visible===void 0)throw new M.RERR("StaveConfigError","The line configuration object is missing the 'visible' property.");if(typeof e.visible!="boolean")throw new M.RERR("StaveConfigError","The line configuration objects 'visible' property must be true or false.");return this.options.line_config[t]=e,this}setConfigForLines(t){if(t.length!==this.options.num_lines)throw new M.RERR("StaveConfigError","The length of the lines configuration array must match the number of lines in the Stave");for(const e in t)t[e]||(t[e]=this.options.line_config[e]),M.Merge(this.options.line_config[e],t[e]);return this.options.line_config=t,this}}class Ia extends sn{constructor(t,e,i,s){const r={spacing_between_lines_px:13,num_lines:6,top_text_position:1};M.Merge(r,s),super(t,e,i,r),this.setAttribute("type","TabStave")}getYForGlyphs(){return this.getYForLine(2.5)}addTabGlyph(){return this.addClef("tab"),this}}function _c(n,t){const e=[];let i=[];for(let s=1;s<=n;s++)t.indexOf(s)>-1?(e.push(i),i=[]):i.push(s);return i.length>0&&e.push(i),e}function wc(n,t,e,i){const s=i!==1,r=i!==-1,o=e.getSpacingBetweenLines(),a=e.getNumLines(),l=[];return t.forEach(h=>{const c=h.indexOf(a)>-1,u=h.indexOf(1)>-1;if(s&&u||r&&c)return;h.length===1&&h.push(h[0]);const f=[];h.forEach((d,p,g)=>{const m=d===1,S=d===a;let b=e.getYForLine(d-1);p===0&&!m?b-=o/2-1:p===g.length-1&&!S&&(b+=o/2-1),f.push(b),i===1&&m?f.push(n-2):i===-1&&S&&f.push(n+2)}),l.push(f.sort((d,p)=>d-p))}),l}class nn extends oo{static get CATEGORY(){return"tabnotes"}constructor(t,e){if(super(t),this.setAttribute("type","TabNote"),this.ghost=!1,this.positions=t.positions,M.Merge(this.render_options,{glyph_font_scale:V.DEFAULT_TABLATURE_FONT_SCALE,draw_stem:e,draw_dots:e,draw_stem_through_stave:!1,y_shift:0,scale:1,font:"10pt Arial"}),this.glyph=V.getGlyphProps(this.duration,this.noteType),!this.glyph)throw new M.RuntimeError("BadArguments",`Invalid note initialization data (No glyph found): ${JSON.stringify(t)}`);this.buildStem(),t.stem_direction?this.setStemDirection(t.stem_direction):this.setStemDirection(ft.UP),this.ghost=!1,this.updateWidth()}reset(){this.stave&&this.setStave(this.stave)}getCategory(){return nn.CATEGORY}setGhost(t){return this.ghost=t,this.updateWidth(),this}hasStem(){return this.render_options.draw_stem}getStemExtension(){const t=this.getGlyph();return this.stem_extension_override!=null?this.stem_extension_override:t?this.getStemDirection()===1?t.tabnote_stem_up_extension:t.tabnote_stem_down_extension:0}addDot(){const t=new Gi;return this.dots+=1,this.addModifier(t,0)}updateWidth(){this.glyphs=[],this.width=0;for(let t=0;tthis.width}setStave(t){super.setStave(t),this.context=t.context;let e;if(this.context){const s=this.context;for(this.width=0,e=0;er.width),this.width=Math.max(r.getWidth(),this.width)}this.glyph.getWidth=()=>this.width}const i=this.positions.map(({str:s})=>t.getYForLine(s-1));return this.setYs(i),this.stem&&this.stem.setYBounds(this.getStemY(),this.getStemY()),this}getPositions(){return this.positions}addToModifierContext(t){this.setModifierContext(t);for(let e=0;e{t.getCategory()==="dots"&&!this.render_options.draw_dots||(t.setContext(this.context),t.drawWithStyle())})}drawStemThrough(){const t=this.getStemX(),e=this.getStemY(),i=this.context,s=this.render_options.draw_stem_through_stave;if(this.render_options.draw_stem&&s){const o=this.stave.getNumLines(),a=this.positions.map(c=>c.str),l=_c(o,a),h=wc(e,l,this.getStave(),this.getStemDirection());i.save(),i.setLineWidth(ft.WIDTH),h.forEach(c=>{c.length!==0&&(i.beginPath(),i.moveTo(t,c[0]),i.lineTo(t,c[c.length-1]),i.stroke(),i.closePath())}),i.restore()}}drawPositions(){const t=this.context,e=this.getAbsoluteX(),i=this.ys;for(let s=0;sparseInt(s,10)?pi.SLIDE_DOWN:pi.SLIDE_UP}this.slide_direction=e,this.render_options.cp1=11,this.render_options.cp2=14,this.render_options.y_shift=.5,this.setFont({font:"Times",size:10,style:"bold italic"}),this.setNotes(t)}renderTie(t){if(t.first_ys.length===0||t.last_ys.length===0)throw new M.RERR("BadArguments","No Y-values to render");const e=this.context,i=t.first_x_px,s=t.first_ys,r=t.last_x_px,o=this.slide_direction;if(o!==pi.SLIDE_UP&&o!==pi.SLIDE_DOWN)throw new M.RERR("BadSlide","Invalid slide direction");for(let a=0;athis.numStrings)throw new M.RERR("BadArguments",`String number must be between 1 and ${this.numStrings}:${t}`);return this.tuningValues[e-1]}getValueForFret(t,e){const i=this.getValueForString(e),s=parseInt(t,10);if(s<0)throw new M.RERR("BadArguments","Fret number must be 0 or higher: "+t);return i+s}getNoteForFret(t,e){const i=this.getValueForFret(t,e),s=Math.floor(i/12),r=i%12;return V.integerToNote(r)+"/"+s}}class Pc{constructor(t){this.music=new te,this.setKey(t)}setKey(t){return this.key=t,this.reset(),this}getKey(){return this.key}reset(){if(this.keyParts=this.music.getKeyParts(this.key),this.keyString=this.keyParts.root,this.keyParts.accidental&&(this.keyString+=this.keyParts.accidental),!te.scaleTypes[this.keyParts.type])throw new M.RERR("BadArguments",`Unsupported key type: ${this.key}`);this.scale=this.music.getScaleTones(this.music.getNoteValue(this.keyString),te.scaleTypes[this.keyParts.type]),this.scaleMap={},this.scaleMapByValue={},this.originalScaleMapByValue={};const e=te.root_indices[this.keyParts.root];for(let i=0;i{const i=_s.GLYPHS[e];if(!i)throw new M.RERR("Invalid dynamics character: "+e);const s=this.render_options.glyph_font_size,r=new xt(i.code,s);this.glyphs.push(r),t+=i.width}),this.setWidth(t),this.preFormatted=!0,this}draw(){this.setRendered();const t=this.getAbsoluteX(),e=this.stave.getYForLine(this.line+-3);Ko("Rendering Dynamics: ",this.sequence);let i=t;this.glyphs.forEach((s,r)=>{const o=this.sequence[r];s.render(this.context,i,e),i+=_s.GLYPHS[o].width})}}function qo(n,t,e,i,s,r,o){n.beginPath(),n.moveTo(t,e),n.lineTo(i,s),n.lineTo(r,o),n.lineTo(t,e),n.closePath(),n.fill()}function Lc(n,t,e,i){const s=i.draw_start_arrow&&i.draw_end_arrow,r=t.x,o=t.y,a=e.x,l=e.y,h=Math.sqrt((a-r)*(a-r)+(l-o)*(l-o)),c=(h-i.arrowhead_length/3)/h;let u,f,d,p;i.draw_end_arrow||s?(u=Math.round(r+(a-r)*c),f=Math.round(o+(l-o)*c)):(u=a,f=l),i.draw_start_arrow||s?(d=r+(a-r)*(1-c),p=o+(l-o)*(1-c)):(d=r,p=o),i.color&&(n.setStrokeStyle(i.color),n.setFillStyle(i.color)),n.beginPath(),n.moveTo(d,p),n.lineTo(u,f),n.stroke(),n.closePath();const g=Math.atan2(l-o,a-r),m=Math.abs(i.arrowhead_length/Math.cos(i.arrowhead_angle));let S,b,y,x,w,T;(i.draw_end_arrow||s)&&(S=g+Math.PI+i.arrowhead_angle,y=a+Math.cos(S)*m,x=l+Math.sin(S)*m,b=g+Math.PI-i.arrowhead_angle,w=a+Math.cos(b)*m,T=l+Math.sin(b)*m,qo(n,y,x,a,l,w,T)),(i.draw_start_arrow||s)&&(S=g+i.arrowhead_angle,y=r+Math.cos(S)*m,x=o+Math.sin(S)*m,b=g-i.arrowhead_angle,w=r+Math.cos(b)*m,T=o+Math.sin(b)*m,qo(n,y,x,r,o,w,T))}class mi extends he{static get TextVerticalPosition(){return{TOP:1,BOTTOM:2}}static get TextJustification(){return{LEFT:1,CENTER:2,RIGHT:3}}constructor(t){super(),this.setAttribute("type","StaveLine"),this.notes=t,this.text="",this.font={family:"Arial",size:10,weight:""},this.render_options={padding_left:4,padding_right:3,line_width:1,line_dash:null,rounded_end:!0,color:null,draw_start_arrow:!1,draw_end_arrow:!1,arrowhead_length:10,arrowhead_angle:Math.PI/8,text_position_vertical:mi.TextVerticalPosition.TOP,text_justification:mi.TextJustification.CENTER},this.setNotes(t)}setFont(t){return this.font=t,this}setText(t){return this.text=t,this}setNotes(t){if(!t.first_note&&!t.last_note)throw new M.RuntimeError("BadArguments","Notes needs to have either first_note or last_note set.");if(t.first_indices||(t.first_indices=[0]),t.last_indices||(t.last_indices=[0]),t.first_indices.length!==t.last_indices.length)throw new M.RuntimeError("BadArguments","Connected notes must have similar index sizes");return this.first_note=t.first_note,this.first_indices=t.first_indices,this.last_note=t.last_note,this.last_indices=t.last_indices,this}applyLineStyle(){const t=this.checkContext(),e=this.render_options;e.line_dash&&t.setLineDash(e.line_dash),e.line_width&&t.setLineWidth(e.line_width),e.rounded_end?t.setLineCap("round"):t.setLineCap("square")}applyFontStyle(){const t=this.checkContext();this.font&&t.setFont(this.font.family,this.font.size,this.font.weight),this.render_options.color&&(t.setStrokeStyle(this.render_options.color),t.setFillStyle(this.render_options.color))}draw(){const t=this.checkContext();this.setRendered();const e=this.first_note,i=this.last_note,s=this.render_options;t.save(),this.applyLineStyle();let r,o;this.first_indices.forEach((f,d)=>{const p=this.last_indices[d];r=e.getModifierStartXY(2,f),o=i.getModifierStartXY(1,p);const g=r.y>o.y;r.x+=e.getMetrics().modRightPx+s.padding_left,o.x-=i.getMetrics().modLeftPx+s.padding_right;const m=e.getGlyph().getWidth();e.getKeyProps()[f].displaced&&e.getStemDirection()===1&&(r.x+=m+s.padding_left),i.getKeyProps()[p].displaced&&i.getStemDirection()===-1&&(o.x-=m+s.padding_right),r.y+=g?-3:1,o.y+=g?2:0,Lc(t,r,o,this.render_options)}),t.restore();const a=t.measureText(this.text).width,l=s.text_justification;let h=0;l===mi.TextJustification.LEFT?h=r.x:l===mi.TextJustification.CENTER?h=(o.x-r.x)/2+r.x-a/2:l===mi.TextJustification.RIGHT&&(h=o.x-a);let c;const u=s.text_position_vertical;return u===mi.TextVerticalPosition.TOP?c=e.getStave().getYForTopText():u===mi.TextVerticalPosition.BOTTOM&&(c=e.getStave().getYForBottomText(V.TEXT_HEIGHT_OFFSET_HACK)),t.save(),this.applyFontStyle(),t.fillText(this.text,h,c),t.restore(),this}}function Tc(...n){Ot.DEBUG&&M.L("Vex.Flow.PedalMarking",n)}function pr(n,t,e,i,s){const r=Ot.GLYPHS[n];new xt(r.code,s).render(t,e+r.x_shift,i+r.y_shift)}class Ot extends he{static get GLYPHS(){return{pedal_depress:{code:"v36",x_shift:-10,y_shift:0},pedal_release:{code:"v5d",x_shift:-2,y_shift:3}}}static get Styles(){return{TEXT:1,BRACKET:2,MIXED:3,MIXED_OPEN_END:4,BRACKET_OPEN_BEGIN:5,BRACKET_OPEN_END:6,BRACKET_OPEN_BOTH:7}}static get StylesString(){return{text:Ot.Styles.TEXT,bracket:Ot.Styles.BRACKET,mixed:Ot.Styles.MIXED,mixed_open_end:Ot.Styles.MIXED_OPEN_END,bracket_open_begin:Ot.Styles.BRACKET_OPEN_BEGIN,bracket_open_end:Ot.Styles.BRACKET_OPEN_END,bracket_open_both:Ot.Styles.BRACKET_OPEN_BOTH}}static createSustain(t){return new Ot(t)}static createSostenuto(t){const e=new Ot(t);return e.setStyle(Ot.Styles.MIXED),e.setCustomText("Sost. Ped."),e}static createUnaCorda(t){const e=new Ot(t);return e.setStyle(Ot.Styles.TEXT),e.setCustomText("una corda","tre corda"),e}constructor(t){super(),this.setAttribute("type","PedalMarking"),this.EndsStave=!1,this.ChangeBegin=!1,this.ChangeEnd=!1,this.notes=t,this.style=Ot.TEXT,this.line=0,this.custom_depress_text="",this.custom_release_text="",this.font={family:"Times New Roman",size:12,weight:"italic bold"},this.render_options={bracket_height:10,text_margin_right:6,bracket_line_width:1,glyph_point_size:40,color:"black"}}setEndStave(t){if(this.endStave=t,this.endStaveAddedWidth=0,this.startMargin=0,this.endMargin=0,Array.isArray(this.endStave.modifiers))for(let e=0;e3)throw new M.RERR("InvalidParameter","The style must be one found in PedalMarking.Styles");return this.style=t,this}setLine(t){return this.line=t,this}drawBracketed(){const t=this.context;let e=!1,i,s;const r=this;this.notes.forEach((o,a,l)=>{e=!e;let h=0;if(o?h=o.getNoteHeadBeginX():h=this.endStave.end_x+this.endStaveAddedWidth,this.EndsStave)e?this.ChangeBegin&&(h=o.getAbsoluteX()):(o?this.ChangeEnd?h=o.getAbsoluteX():h=o.getStave().end_x+this.endStaveAddedWidth-r.render_options.text_margin_right:h=this.endStave.end_x+this.endStaveAddedWidth-r.render_options.text_margin_right,this.endMargin=-r.render_options.text_margin_right);else if(o)if(e)this.ChangeBegin&&(h=o.getAbsoluteX());else switch(r.style){case Ot.Styles.BRACKET_OPEN_END:case Ot.Styles.BRACKET_OPEN_BOTH:case Ot.Styles.MIXED_OPEN_END:h=o.getNoteHeadEndX();break;default:this.ChangeEnd?h=o.getAbsoluteX():(h=o.getNoteHeadBeginX()-r.render_options.text_margin_right,this.startMargin=-r.render_options.text_margin_right);break}let c=this.endStave;o&&(c=o.getStave());let u=c.getYForBottomText(r.line+3);s&&s>u&&(u=s);const f=l[a+1]===o,d=l[a-1]===o;let p=0;if(e)if(p=d?5:0,(r.style===Ot.Styles.MIXED||r.style===Ot.Styles.MIXED_OPEN_END)&&!d)if(r.custom_depress_text){const g=t.measureText(r.custom_depress_text).width;t.fillText(r.custom_depress_text,h-g/2,u),p=g/2+r.render_options.text_margin_right}else pr("pedal_depress",t,h,u,r.render_options.glyph_point_size),p=20+r.render_options.text_margin_right;else t.beginPath(),r.style===Ot.Styles.BRACKET_OPEN_BEGIN||r.style===Ot.Styles.BRACKET_OPEN_BOTH?t.moveTo(h+p,u):(this.ChangeBegin&&(h+=5),t.moveTo(h,u-r.render_options.bracket_height),this.ChangeBegin&&(h+=5),t.lineTo(h+p,u)),t.stroke(),t.closePath();else p=f&&!this.EndsStave?-5:0,t.beginPath(),t.moveTo(i,s),t.lineTo(h+p,u),r.style!==Ot.Styles.BRACKET_OPEN_END&&r.style!==Ot.Styles.MIXED_OPEN_END&&r.style!==Ot.Styles.BRACKET_OPEN_BOTH&&(this.ChangeEnd&&(h+=5),t.lineTo(h,u-r.render_options.bracket_height)),t.stroke(),t.closePath();i=h+p,s=u})}drawText(){const t=this.context;let e=!1;const i=this,s=i.render_options.glyph_point_size;this.notes.forEach(r=>{e=!e;const o=r.getStave(),a=r.getAbsoluteX(),l=o.getYForBottomText(i.line+3);let h=0;e?i.custom_depress_text?(h=t.measureText(i.custom_depress_text).width,t.fillText(i.custom_depress_text,a-h/2,l)):pr("pedal_depress",t,a,l,s):i.custom_release_text?(h=t.measureText(i.custom_release_text).width,t.fillText(i.custom_release_text,a-h/2,l)):pr("pedal_release",t,a,l,s)})}draw(){const t=this.checkContext();this.setRendered(),t.save(),t.setStrokeStyle(this.render_options.color),t.setFillStyle(this.render_options.color),t.setFont(this.font.family,this.font.size,this.font.weight),Tc("Rendering Pedal Marking"),this.style===Ot.Styles.BRACKET||this.style===Ot.Styles.MIXED||this.style===Ot.Styles.MIXED_OPEN_END||this.style===Ot.Styles.BRACKET_OPEN_BEGIN||this.style===Ot.Styles.BRACKET_OPEN_END||this.style===Ot.Styles.BRACKET_OPEN_BOTH?(t.setLineWidth(this.render_options.bracket_line_width),this.drawBracketed()):this.style===Ot.Styles.TEXT&&this.drawText(),t.restore()}}function Cc(...n){Ze.DEBUG&&M.L("Vex.Flow.TextBracket",n)}class Ze extends he{static get Positions(){return{TOP:1,BOTTOM:-1}}static get PositionString(){return{top:Ze.Positions.TOP,bottom:Ze.Positions.BOTTOM}}constructor({start:t,stop:e,text:i="",superscript:s="",position:r=Ze.Positions.TOP}){super(),this.setAttribute("type","TextBracket"),this.start=t,this.stop=e,this.text=i,this.superscript=s,this.position=typeof r=="string"?Ze.PositionString[r]:r,this.line=1,this.font={family:"Serif",size:15,weight:"italic"},this.render_options={dashed:!0,dash:[5],color:"black",line_width:1,show_bracket:!0,bracket_height:8,underline_superscript:!0}}applyStyle(t){return t.setFont(this.font.family,this.font.size,this.font.weight),t.setStrokeStyle(this.render_options.color),t.setFillStyle(this.render_options.color),t.setLineWidth(this.render_options.line_width),this}setDashed(t,e){return this.render_options.dashed=t,e&&(this.render_options.dash=e),this}setFont(t){return this.font=be(be({},this.font),t),this}setLine(t){return this.line=t,this}draw(){const t=this.context;this.setRendered();let e=0;switch(this.position){case Ze.Positions.TOP:e=this.start.getStave().getYForTopText(this.line);break;case Ze.Positions.BOTTOM:e=this.start.getStave().getYForBottomText(this.line+V.TEXT_HEIGHT_OFFSET_HACK);break;default:throw new M.RERR("InvalidPosition",`The position ${this.position} is invalid`)}const i={x:this.start.getAbsoluteX(),y:e},s={x:this.stop.getAbsoluteX(),y:e};Cc("Rendering TextBracket: start:",i,"stop:",s,"y:",e);const r=this.render_options.bracket_height*this.position;t.save(),this.applyStyle(t),t.fillText(this.text,i.x,i.y);const o=t.measureText(this.text).width,a=t.measureText("M").width,l=i.y-a/2.5;t.setFont(this.font.family,this.font.size/1.4,this.font.weight),t.fillText(this.superscript,i.x+o+1,l);const h=t.measureText(this.superscript).width,c=t.measureText("M").width;let u=i.x,f=l;const d=s.x+this.stop.getGlyph().getWidth();this.position===Ze.Positions.TOP?(u+=o+h+5,f-=c/2.7):this.position===Ze.Positions.BOTTOM&&(f+=c/2.7,u+=o+2,this.render_options.underline_superscript||(u+=h)),this.render_options.dashed?(Zt.drawDashedLine(t,u,f,d,f,this.render_options.dash),this.render_options.show_bracket&&Zt.drawDashedLine(t,d,f+1*this.position,d,f+r,this.render_options.dash)):(t.beginPath(),t.moveTo(u,f),t.lineTo(d,f),this.render_options.show_bracket&&t.lineTo(d,f+r),t.stroke(),t.closePath()),t.restore()}}function Rc(...n){po.DEBUG&&M.L("Vex.Flow.BarNote",n)}class po extends Ie{constructor(t=Xt.type.SINGLE){super({duration:"b"}),this.setAttribute("type","BarNote"),this.metrics={widths:{}};const e=Xt.type;this.metrics.widths={[e.SINGLE]:8,[e.DOUBLE]:12,[e.END]:15,[e.REPEAT_BEGIN]:14,[e.REPEAT_END]:14,[e.REPEAT_BOTH]:18,[e.NONE]:0},this.ignore_ticks=!0,this.setType(t)}getType(){return this.type}setType(t){return this.type=typeof t=="string"?Xt.typeString[t]:t,this.setWidth(this.metrics.widths[this.type]),this}getBoundingBox(){return super.getBoundingBox()}addToModifierContext(){return this}preFormat(){return this.setPreFormatted(!0),this}draw(){if(this.checkContext(),!this.stave)throw new M.RERR("NoStave","Can't draw without a stave.");Rc("Rendering bar line at: ",this.getAbsoluteX());const t=new Xt(this.type);t.setX(this.getAbsoluteX()),t.draw(this.stave),this.setRendered()}}class Fa extends oo{constructor(t){if(!t)throw new M.RuntimeError("BadArguments","Ghost note must have valid initialization data to identify duration.");let e;if(typeof t=="string")e={duration:t};else if(typeof t=="object")e=t;else throw new M.RuntimeError("BadArguments","Ghost note must have valid initialization data to identify duration.");super(e),this.setAttribute("type","GhostNote"),this.setWidth(0)}isRest(){return!0}setStave(t){super.setStave(t)}addToModifierContext(){return this}preFormat(){return this.setPreFormatted(!0),this}draw(){if(!this.stave)throw new M.RERR("NoStave","Can't draw without a stave.");this.setRendered();for(let t=0;t0||e===!0;return e&&!(r>0)&&(this.pos=s),a?this.matchSuccess():this.matchFail(s),{success:a,results:i,numMatches:r}}expectZeroOrMore(t){return this.expectOneOrMore(t,!0)}expect(t){Ic("Evaluating rules:",t);let e;if(!t)throw new Jo("Invalid Rule: "+t,t);const i=t.bind(this.grammar)();if(i.token)e=this.matchToken(i.token,i.noSpace===!0),e.success&&(this.pos+=e.incrementPos);else if(i.expect)i.oneOrMore?e=this.expectOneOrMore(i):i.zeroOrMore?e=this.expectZeroOrMore(i):e=this.expectOne(i);else throw new Jo("Bad grammar! No `token` or `expect` property",i);return e.matches=[],e.results&&e.results.forEach(s=>e.matches.push(Sn(s))),i.run&&e.success&&i.run(e),e}}function di(...n){go.DEBUG&&M.L("Vex.Flow.EasyScore",n)}const kc=M.MakeException("EasyScoreError");class Bc{constructor(t){this.builder=t}begin(){return this.LINE}LINE(){return{expect:[this.PIECE,this.PIECES,this.EOL]}}PIECE(){return{expect:[this.CHORDORNOTE,this.PARAMS],run:()=>this.builder.commitPiece()}}PIECES(){return{expect:[this.COMMA,this.PIECE],zeroOrMore:!0}}PARAMS(){return{expect:[this.DURATION,this.TYPE,this.DOTS,this.OPTS]}}CHORDORNOTE(){return{expect:[this.CHORD,this.SINGLENOTE],or:!0}}CHORD(){return{expect:[this.LPAREN,this.NOTES,this.RPAREN],run:t=>this.builder.addChord(t.matches[1])}}NOTES(){return{expect:[this.NOTE],oneOrMore:!0}}NOTE(){return{expect:[this.NOTENAME,this.ACCIDENTAL,this.OCTAVE]}}SINGLENOTE(){return{expect:[this.NOTENAME,this.ACCIDENTAL,this.OCTAVE],run:t=>this.builder.addSingleNote(t.matches[0],t.matches[1],t.matches[2])}}ACCIDENTAL(){return{expect:[this.ACCIDENTALS],maybe:!0}}DOTS(){return{expect:[this.DOT],zeroOrMore:!0,run:t=>this.builder.setNoteDots(t.matches[0])}}TYPE(){return{expect:[this.SLASH,this.MAYBESLASH,this.TYPES],maybe:!0,run:t=>this.builder.setNoteType(t.matches[2])}}DURATION(){return{expect:[this.SLASH,this.DURATIONS],maybe:!0,run:t=>this.builder.setNoteDuration(t.matches[1])}}OPTS(){return{expect:[this.LBRACKET,this.KEYVAL,this.KEYVALS,this.RBRACKET],maybe:!0}}KEYVALS(){return{expect:[this.COMMA,this.KEYVAL],zeroOrMore:!0}}KEYVAL(){const t=e=>e.slice(1,-1);return{expect:[this.KEY,this.EQUALS,this.VAL],run:e=>this.builder.addNoteOption(e.matches[0],t(e.matches[2]))}}VAL(){return{expect:[this.SVAL,this.DVAL],or:!0}}KEY(){return{token:"[a-zA-Z][a-zA-Z0-9]*"}}DVAL(){return{token:'["][^"]*["]'}}SVAL(){return{token:"['][^']*[']"}}NOTENAME(){return{token:"[a-gA-G]"}}OCTAVE(){return{token:"[0-9]+"}}ACCIDENTALS(){return{token:"bbs|bb|bss|bs|b|db|d|##|#|n|\\+\\+-|\\+-|\\+\\+|\\+|k|o"}}DURATIONS(){return{token:"[0-9whq]+"}}TYPES(){return{token:"[rRsSxX]"}}LPAREN(){return{token:"[(]"}}RPAREN(){return{token:"[)]"}}COMMA(){return{token:"[,]"}}DOT(){return{token:"[.]"}}SLASH(){return{token:"[/]"}}MAYBESLASH(){return{token:"[/]?"}}EQUALS(){return{token:"[=]"}}LBRACKET(){return{token:"\\["}}RBRACKET(){return{token:"\\]"}}EOL(){return{token:"$"}}}class Dc{constructor(t){this.factory=t,this.commitHooks=[],this.reset()}reset(t={}){this.options={stem:"auto",clef:"treble"},this.elements={notes:[],accidentals:[]},this.rollingDuration="8",this.resetPiece(),Object.assign(this.options,t)}getFactory(){return this.factory}getElements(){return this.elements}addCommitHook(t){this.commitHooks.push(t)}resetPiece(){di("resetPiece"),this.piece={chord:[],duration:this.rollingDuration,dots:0,type:void 0,options:{}}}setNoteDots(t){di("setNoteDots:",t),t&&(this.piece.dots=t.length)}setNoteDuration(t){di("setNoteDuration:",t),this.rollingDuration=this.piece.duration=t||this.rollingDuration}setNoteType(t){di("setNoteType:",t),t&&(this.piece.type=t)}addNoteOption(t,e){di("addNoteOption: key:",t,"value:",e),this.piece.options[t]=e}addNote(t,e,i){di("addNote:",t,e,i),this.piece.chord.push({key:t,accid:e,octave:i})}addSingleNote(t,e,i){di("addSingleNote:",t,e,i),this.addNote(t,e,i)}addChord(t){di("startChord"),typeof t[0]!="object"?this.addSingleNote(t[0]):t.forEach(e=>{e&&this.addNote(...e)}),di("endChord")}commitPiece(){di("commitPiece");const{factory:t}=this;if(!t)return;const e=be(be({},this.options),this.piece.options),{stem:i,clef:s}=e,r=i.toLowerCase()==="auto",o=!r&&i.toLowerCase()==="up"?ae.STEM_UP:ae.STEM_DOWN,{chord:a,duration:l,dots:h,type:c}=this.piece,u=a.map(p=>p.key+"/"+p.octave),f=t.StaveNote({keys:u,duration:l,dots:h,type:c,clef:s,auto_stem:r});r||f.setStemDirection(o);const d=a.map(p=>p.accid||null);d.forEach((p,g)=>{p&&f.addAccidental(g,t.Accidental({type:p}))});for(let p=0;pp(e,f,this)),this.elements.notes.push(f),this.elements.accidentals.concat(d),this.resetPiece()}}function Fc({id:n},t){n!==void 0&&t.setAttribute("id",n)}function Oc(n,t){if(!n.class)return;const e=/\s*,\s*/;n.class.split(e).forEach(i=>t.addClass(i))}class go{constructor(t={}){this.setOptions(t),this.defaults={clef:"treble",time:"4/4",stem:"auto"}}set(t){return Object.assign(this.defaults,t),this}setOptions(t){return this.options=be({factory:null,builder:null,commitHooks:[Fc,Oc,Ri.easyScoreHook],throwOnError:!1},t),this.factory=this.options.factory,this.builder=this.options.builder||new Dc(this.factory),this.grammar=new Bc(this.builder),this.parser=new mo(this.grammar),this.options.commitHooks.forEach(e=>this.addCommitHook(e)),this}setContext(t){return this.factory&&this.factory.setContext(t),this}parse(t,e={}){this.builder.reset(e);const i=this.parser.parse(t);if(!i.success&&this.options.throwOnError)throw new kc("Error parsing line: "+t,i);return i}beam(t,e={}){return this.factory.Beam({notes:t,options:e}),t}tuplet(t,e={}){return this.factory.Tuplet({notes:t,options:e}),t}notes(t,e={}){return e=be({clef:this.defaults.clef,stem:this.defaults.stem},e),this.parse(t,e),this.builder.getElements().notes}voice(t,e){return e=be({time:this.defaults.time},e),this.factory.Voice(e).addTickables(t)}addCommitHook(t){return this.builder.addCommitHook(t)}}function cs(){return{notes:[],finish:!1,total:0,staveId:""}}let Nn=null,ds="C",Be=cs(),gn="",ls="",De="";class ai extends ae{static get CATEGORY(){return"numberednotes"}static accidentalAndKey(t){switch(t){case"G":return{"4":"#"};case"D":return{"1":"#","4":"#"};case"A":return{"1":"#","4":"#","5":"#"};case"E":return{"1":"#","2":"#","4":"#","5":"#"};case"B":return{"1":"#","2":"#","4":"#","5":"#","6":"#"};case"F#":return{"1":"#","2":"#","3":"#","4":"#","5":"#","6":"#"};case"C#":return{"1":"#","2":"#","3":"#","4":"#","5":"#","6":"#","7":"#"};case"F":return{"7":"b"};case"Bb":return{"7":"b","3":"b"};case"Eb":return{"7":"b","3":"b","6":"b"};case"Ab":return{"7":"b","2":"b","3":"b","6":"b"};case"Db":return{"7":"b","2":"b","3":"b","5":"b","6":"b"};case"Gb":return{"7":"b","1":"b","2":"b","3":"b","5":"b","6":"b"};case"Cb":return{"7":"b","1":"b","2":"b","3":"b","4":"b","5":"b","6":"b"};default:return{}}}static accidentalMap(t){switch(t){case"C":return"";case"F":case"Bb":case"Eb":case"Ab":case"Db":case"Gb":case"Cb":return{bb:"b",b:"",n:"#","#":"##"};default:return{b:"bb",n:"b","#":"","##":"#"}}}static get noteLift(){switch(ds){case"G":return["7"];case"D":return["7","3"];case"A":return["7","3","6"];case"E":return["2","6","3","7"];case"B":return["5","2","6","3","7"];case"F#":return["1","5","2","6","3","7"];case"C#":return["4","1","5","2","6","3","7"];case"F":return["4"];case"Bb":return["1","4"];case"Eb":return["5","1","4"];case"Ab":return["2","5","1","4"];case"Db":return["6","2","5","1","4"];case"Gb":return["3","6","2","5","1","4"];case"Cb":return["7","3","6","2","5","1","4"]}}static get longDurationLine(){return{"1":3,"2":1,"6":2}}static get numberedDurationLine(){return{"8":1,"16":2,"32":3,"64":4,"128":5}}static get durationTime(){return{8:6144,4:4096}}constructor(t){super(t),this.setAttribute("type","NumberedNote"),ds=t.keyString,this.ornament=!!t.ornament,this.line=0,this.keys=t.keys||[],this.fontSize=20,this.offset_x=0,this.offset_y=0,this.note_tones=[],this.duration_lines=0,this.long_duration_lines=0,this.note_size=t.note_size||16;const e=V.sanitizeDuration(this.duration);var i=ai.numberedDurationLine[e.toString()];if(i&&(this.duration_lines=i),i=ai.longDurationLine[e.toString()],i&&(this.long_duration_lines=i),!Nn){var s="__$text_wraper$$__";let o=document.createElement("canvas");o.id=s,document.body.append(o);const a=document.getElementById(s),l=a.getContext("2d");l.font="Arial 22px";var r=l.measureText("5");Nn=r.width+2,document.body.removeChild(a)}}getCategory(){return ai.CATEGORY}setKeySignature(t){this.keySignature=t}preFormat(){this.preFormatted||(this.modifierContext&&this.modifierContext.preFormat(),this.setWidth(this.full_width),this.setPreFormatted(!0))}filterNote(){if(window&&window.sett&&window.sett.keySignature||!this.keys||!this.keys.length)return;const t=ai.accidentalMap(ds);if(!t)return;const e=ai.noteLift;if(!e)return;var i=this.keys[0].split("/"),s=i[0];s==="b"&&(s="R"),s=s.replaceAll("#",""),s=s.replaceAll("n",""),s.length>1&&(s=s.replaceAll("b",""));const r=Fi.numberedNotationMapping[s.toUpperCase()];if(e.includes(r))for(let o=0;o{switch(i.getAttribute("type")){case"Accidental":i.render_options.font_scale=this.note_width*1.4,i.x_shift=2,i.y_shift=this.unit_height/2,this.ornament&&(i.render_options.font_scale=this.note_width,i.x_shift=14,i.y_shift=-10);break;case"Stroke":i.x_shift=-1*t,i.y_shift=1*this.unit_height;break;case"Dot":i.x_shift=e*this.duration_dot_width+7,i.y_shift=1*this.unit_height,e++;break;case"Ornament":i.y_shift=-3;break;default:i.y_shift=1*this.unit_height}i.reset&&i.reset(),t+=i.getWidth()/2})}handleDeleteDot(){for(let t=0;to),i=e.length?e[0]/e[1]:0;if(this.ornament)return;if(i===0)return this.long_duration_lines=this.intrinsicTicks/t-1,this.long_duration_lines>=ls&&(this.long_duration_lines=ls-1),gn==8&&(this.long_duration_lines=0,ls==3&&this.draw_dot(this.context,this.bottom_x+25,this.bottom_y-30,this.dot_width),ls==6&&(this.draw_dot(this.context,this.bottom_x+25,this.bottom_y-30,this.dot_width),new xt("v0",40).render(this.context,this.bottom_x+40,this.top_y),this.draw_dot(this.context,this.bottom_x+65,this.bottom_y-30,this.dot_width))),Be=cs();let s={lines:this.duration_lines,duration:i,id:this.attrs.id,x:this.x-this.duration_line_space/2-this.left_width,y:this.y,width:this.full_width};i>t*2&&(this.long_duration_lines=parseInt(i/t)-1,this.handleDeleteDot()),De&&(s.x+=this.note_width),Be.notes.push(s);let r=Be.notes.reduce((o,a)=>o+a.duration,0);r=parseInt(r),r>t&&(r-=t),r>t-10&&ra.lines===0).length&&(this.drawDurationLoneLine(),Be=cs()))}draw(){if(this.checkContext(),!this.stave)throw new M.RERR("NoStave","Can't draw without a stave.");let t=this.context;t.save(),t.setFont("Arial",this.note_height,"normal"),this.setAttribute("el",t.openGroup("stavenote",this.getAttribute("id"))),t.openGroup("note",null,{pointerBBox:!0});let e=this.getAbsoluteX()+2.5;this.x=e;let i=this.stave.getYForLine(2)+this.note_height/2;this.y=i,this.buildToneHeads(),this.preFormatModifier(),this.applyStyle(),this.note_tones.forEach(s=>{s.draw(t)}),t.openGroup("modifier",null,{pointerBBox:!0}),this.drawModifiers(),t.closeGroup(),t.closeGroup(),t.closeGroup(),this.calcGroup(),Be.staveId=this.stave.attrs.id,this.drawDurationLine(t,{}),this.drawLongDurationLines(t),this.restoreStyle(),this.setRendered(),this.ornament?De?De=Object.assign(De,{lines:this.duration_lines,id:this.attrs.id,x:this.x-this.duration_line_space/2-this.left_width,width:this.full_width}):De={lines:this.duration_lines,id:this.attrs.id,x:this.x-this.duration_line_space/2-this.left_width,width:this.full_width}:De=""}drawDurationLoneLine(t,e){t=t||this.context;let i=e||this.y+this.duration_line_space;for(let s=0;s<5;s++){let r=[],o=0;for(let a=0;as)r.push(l),o++;else{if(r.length>1){let h=r.length-1;i=r[0].y+this.duration_line_space,t.rect(r[0].x,i+s*3,r[h].x-r[0].x+r[h].width,.5)}r=[],o=a+1}}if(r.length>1){let a=r.length-1;i=r[0].y+this.duration_line_space,t.rect(r[0].x,i+s*3,r[a].x-r[0].x+r[a].width,.5)}}}draw_dot(t,e,i,s){t.openGroup("numbered-note-dot"),t.beginPath(),t.arc(e,i,s,0,2*Math.PI),t.closePath(),t.fill(),t.closeGroup()}drawDurationLine(t,e){var i=this.attrs.id+"-lines";t.openGroup("numbered_note_lines",i);var s,r;if(this.duration_lines>0){const l=this.duration_line_space;var o=this.full_width;if(e&&e.width&&(o=e.width),o<0&&(o=this.note_width),!e||typeof e.startX=="undefined"?s=this.x-l/2-this.left_width:s=e.startX,!e||typeof e.startY=="undefined"?r=this.y+this.duration_line_space:r=e.startY,Be.finish&&(this.drawDurationLoneLine(t,r),Be=cs()),this.ornament?(s+=12,r-=22,o=15,De&&(s-=10,o+=10)):De&&(s+=this.note_width,o-=this.note_width),o>0){for(var a=0;aa.getAttribute("type")==="Accidental"),o=this.modifiers.findIndex(a=>a.getAttribute("type")==="Accidental");s&&o>-1?this.modifiers[o].accidental.code=s==="#"?"v18":"v44":this.modifiers.splice(o,1)}}catch(s){console.log("\u{1F680} ~ error",s)}}this.setYs(t)}getFullWidth(){return this.full_width}getFullHeight(){return this.full_height}getLine(){return this.keyProps[0].line}get full_width(){return this.note_width+this.left_width+this.right_width+this.long_duration_line_width}get long_duration_line_width(){return(this.long_duration_width+this.long_duration_space)*this.long_duration_lines}get full_height(){return this.bottom_y-this.top_y}get note_width(){return this.note_size||0}get note_dot_width(){return 6}get note_height(){return this.unit_height}get unit_height(){return this.note_size||0}get note_x(){return this.x||0}get top_x(){return this.x||0}get top_y(){var t=this;return(this.y||0)-(t.note_tones.map(i=>(i.td+i.bd)*(t.dot_space+t.dot_width)).reduce((i,s)=>i+s,0)+this.note_height*this.note_tones.length-this.unit_height-this.note_tones[0].bd*(t.dot_space+t.dot_width)+(this.note_tones.length-1)*this.head_space)}get bottom_x(){return this.x||0}get bottom_y(){return(this.y||0)+this.unit_height+this.duration_lines*(this.duration_line_height+this.duration_line_space)+this.note_tones[0].meta.bd*(this.dot_width+this.dot_space)}get left_width(){return this.modifiers_width}get right_width(){return this.full_duration_dot_width}get duration_dot_width(){return 6}get full_duration_dot_width(){return this.duration_dot_width*this.getModifiersByCategory(Gi.CATEGORY).length}getModifiersByCategory(t){var e=[];return this.modifiers.forEach(i=>{i.getCategory()===t&&e.push(i)}),e}get head_space(){return 6}get duration_line_height(){return 2}get duration_line_space(){return 4}get dot_width(){return 2}get dot_space(){return 2}get long_duration_space(){return 10}get long_duration_width(){return 20}getWidth(){return this.full_width}get modifiers_width(){let t=0;return this.modifiers.forEach(e=>{t+=e.getWidth()}),t}}class Fi{static get numberedNotationMapping(){let t=ds;switch(window&&window.sett&&window.sett.keySignature&&(t="C"),t){case"A":return{C:"3",D:"4",E:"5",F:"6",G:"7",A:"1",B:"2",R:"0",min:2.5,max:5.5};case"B":return{C:"2",D:"3",E:"4",F:"5",G:"6",A:"7",B:"1",R:"0",min:-.5,max:2.5};case"D":return{C:"7",D:"1",E:"2",F:"3",G:"4",A:"5",B:"6",R:"0",min:.5,max:3.5};case"E":return{C:"6",D:"7",E:"1",F:"2",G:"3",A:"4",B:"5",R:"0",min:1,max:4};case"F":return{C:"5",D:"6",E:"7",F:"1",G:"2",A:"3",B:"4",R:"0",min:1.5,max:4.5};case"G":case"Gb":return{C:"4",D:"5",E:"6",F:"7",G:"1",A:"2",B:"3",R:"0",min:2,max:5};case"Eb":return{C:"6",D:"7",E:"1",F:"2",G:"3",A:"4",B:"5",R:"0",min:1,max:4};case"D#":case"Db":return{C:"7",D:"1",E:"2",F:"3",G:"4",A:"5",B:"6",R:"0",min:.5,max:3.5};case"F#":return{C:"5",D:"6",E:"7",F:"1",G:"2",A:"3",B:"4",R:"0",min:1.5,max:4.5};case"Ab":case"G#":return{C:"3",D:"4",E:"5",F:"6",G:"7",A:"1",B:"2",R:"0",min:-1,max:2};case"Bb":case"A#":return{C:"2",D:"3",E:"4",F:"5",G:"6",A:"7",B:"1",R:"0",min:-.5,max:2.5};case"C#":case"Cb":default:return{C:"1",D:"2",E:"3",F:"4",G:"5",A:"6",B:"7",R:"0",min:0,max:3}}}tone_to_numbered_key(){var t=this.key.split("/"),e=t[0];e==="b"&&(e="R"),e=e.replaceAll("#",""),e=e.replaceAll("n",""),e.length>1&&(e=e.replaceAll("b",""));let i=0,s=0;this.note.stave&&this.note.stave.options&&this.note.stave.options.keySignature&&(ds=this.note.stave.options.keySignature);const r=this.note.getLine();return rFi.numberedNotationMapping.max&&(s=Math.ceil((r-Fi.numberedNotationMapping.max)/3.5)),e.toUpperCase()==="R"&&(i=0,s=0),{key:Fi.numberedNotationMapping[e.toUpperCase()],td:s,bd:i}}constructor(t){this.key=t.key,this.x=t.x||0,this.y=t.y||0,this.idx=t.idx||0,this.note=t.note||0,this.meta=this.tone_to_numbered_key(),this.noteSize=t.noteSize||16,this.td=this.meta.td,this.bd=this.meta.bd}draw(t){let e=this.y;t.openGroup("numbered-note-head");var i=this.x+(this.note.ornament?-2:0);let s=e-this.note.unit_height-this.note.dot_space-(this.note.ornament?-4:2);for(let o=0;o1&&(a-=this.note.duration_line_space),e+=a}this.draw_dot(t,i+Nn,e,this.note.dot_width),e+=this.note.dot_width+this.note.dot_space}t.closeGroup()}get height(){return this.note.note_height+(this.meta.bd+this.meta.td)*(this.note.dot_width+this.note.dot_space)}draw_dot(t,e,i,s){t.openGroup("numbered-note-dot"),t.beginPath(),t.arc(e,i,s,0,2*Math.PI),t.closePath(),t.fill(),t.closeGroup()}}function Vc(...n){rn.DEBUG&&M.L("Vex.Flow.Factory",n)}const Gc=M.MakeException("FactoryError");function fe(n={},t){const e=t.options;return n=Object.assign(t,n),n.options=Object.assign(e,n.options),n}class rn{constructor(t){Vc("New factory: ",t);const e={stave:{space:10},renderer:{context:null,elementId:"",backend:Zt.Backends.SVG,width:500,height:200,background:"#FFF"},font:{face:"Arial",point:10,style:""}};this.options=e,this.setOptions(t)}static newFromElementId(t,e=500,i=200){return new rn({renderer:{elementId:t,width:e,height:i}})}reset(){this.renderQ=[],this.systems=[],this.staves=[],this.voices=[],this.stave=null}getOptions(){return this.options}setOptions(t){for(const e of["stave","renderer","font"])Object.assign(this.options[e],t[e]);(this.options.renderer.elementId!==null||this.options.renderer.context)&&this.initRenderer(),this.reset()}initRenderer(){const{elementId:t,backend:e,width:i,height:s,background:r}=this.options.renderer;if(t==="")throw new Gc("HTML DOM element not set in Factory");this.context=Zt.buildContext(t,e,i,s,r)}getContext(){return this.context}setContext(t){return this.context=t,this}getStave(){return this.stave}getVoices(){return this.voices}space(t){return this.options.stave.space*t}Stave(t){t=fe(t,{x:0,y:0,width:this.options.renderer.width-this.space(1),options:{spacing_between_lines_px:this.options.stave.space}});const e=new sn(t.x,t.y,t.width,t.options);return this.staves.push(e),e.setContext(this.context),this.stave=e,e}TabStave(t){t=fe(t,{x:0,y:0,width:this.options.renderer.width-this.space(1),options:{spacing_between_lines_px:this.options.stave.space*1.3}});const e=new Ia(t.x,t.y,t.width,t.options);return this.staves.push(e),e.setContext(this.context),this.stave=e,e}StaveNote(t){const e=new ae(t);return this.stave&&e.setStave(this.stave),e.setContext(this.context),this.renderQ.push(e),e}GhostNote(t){const e=new Fa(t);return this.stave&&e.setStave(this.stave),e.setContext(this.context),this.renderQ.push(e),e}TextNote(t){const e=new li(t);return this.stave&&e.setStave(this.stave),e.setContext(this.context),this.renderQ.push(e),e}NumberedNote(t){const e=new ai(t);return this.stave&&e.setStave(this.stave),e.setContext(this.context),this.renderQ.push(e),e}BarNote(t){t=fe(t,{type:"single",options:{}});const e=new po(t.type);return this.stave&&e.setStave(this.stave),e.setContext(this.context),this.renderQ.push(e),e}ClefNote(t){t=fe(t,{type:"treble",options:{size:"default"}});const e=new tr(t.type,t.options.size,t.options.annotation);return this.stave&&e.setStave(this.stave),e.setContext(this.context),this.renderQ.push(e),e}TimeSigNote(t){t=fe(t,{time:"4/4",options:{}});const e=new Da(t.time);return this.stave&&e.setStave(this.stave),e.setContext(this.context),this.renderQ.push(e),e}KeySigNote(t){const e=new Ba(t.key,t.cancelKey,t.alterKey);return this.stave&&e.setStave(this.stave),e.setContext(this.context),this.renderQ.push(e),e}TabNote(t){const e=new nn(t);return this.stave&&e.setStave(this.stave),e.setContext(this.context),this.renderQ.push(e),e}GraceNote(t){const e=new ts(t);return this.stave&&e.setStave(this.stave),e.setContext(this.context),e}GraceNoteGroup(t){const e=new Ps(t.notes,t.slur);return e.setContext(this.context),e}Accidental(t){t=fe(t,{type:null,options:{}});const e=new is(t.type);return e.setContext(this.context),e}Annotation(t){t=fe(t,{text:"p",vJustify:"below",hJustify:"center",fontFamily:"Times",fontSize:14,fontWeight:"bold italic",options:{}});const e=new se(t.text);return e.setJustification(t.hJustify),e.setVerticalJustification(t.vJustify),e.setFont(t.fontFamily,t.fontSize,t.fontWeight),e.setContext(this.context),e}Articulation(t){t=fe(t,{type:"a.",position:"above",options:{}});const e=new Ri(t.type);return e.setPosition(t.position),e.setContext(this.context),e}TextDynamics(t){t=fe(t,{text:"p",duration:"q",dots:0,line:0,options:{}});const e=new _s({text:t.text,line:t.line,duration:t.duration,dots:t.dots});return this.stave&&e.setStave(this.stave),e.setContext(this.context),this.renderQ.push(e),e}Fingering(t){t=fe(t,{number:"0",position:"left",options:{}});const e=new Qs(t.number);return e.setPosition(t.position),e.setContext(this.context),e}StringNumber(t){t=fe(t,{number:"0",position:"left",options:{}});const e=new tn(t.number);return e.setPosition(t.position),e.setContext(this.context),e}TickContext(){return new xs().setContext(this.context)}ModifierContext(){return new Ys}MultiMeasureRest(t){const e=new ka(t.number_of_measures,t);return e.setContext(this.context),this.renderQ.push(e),e}Voice(t){t=fe(t,{time:"4/4",options:{}});const e=new ye(t.time);return this.voices.push(e),e}StaveConnector(t){t=fe(t,{top_stave:null,bottom_stave:null,type:"double",options:{}});const e=new Bt(t.top_stave,t.bottom_stave);return e.setType(t.type).setContext(this.context),this.renderQ.push(e),e}Formatter(){return new si}Tuplet(t){t=fe(t,{notes:[],options:{}});const e=new He(t.notes,t.options).setContext(this.context);return this.renderQ.push(e),e}Beam(t){t=fe(t,{notes:[],options:{autoStem:!1,secondaryBeamBreaks:[]}});const e=new Vi(t.notes,t.options.autoStem).setContext(this.context);return e.breakSecondaryAt(t.options.secondaryBeamBreaks),this.renderQ.push(e),e}Curve(t){t=fe(t,{from:null,to:null,options:{}});const e=new oi(t.from,t.to,t.options).setContext(this.context);return this.renderQ.push(e),e}StaveTie(t){t=fe(t,{from:null,to:null,first_indices:[0],last_indices:[0],text:null,options:{direction:void 0}});const e=new Qn({first_note:t.from,last_note:t.to,first_indices:t.first_indices,last_indices:t.last_indices},t.text);return t.options.direction&&e.setDirection(t.options.direction),e.setContext(this.context),this.renderQ.push(e),e}StaveLine(t){t=fe(t,{from:null,to:null,first_indices:[0],last_indices:[0],options:{}});const e=new mi({first_note:t.from,last_note:t.to,first_indices:t.first_indices,last_indices:t.last_indices});return t.options.text&&e.setText(t.options.text),t.options.font&&e.setFont(t.options.font),e.setContext(this.context),this.renderQ.push(e),e}VibratoBracket(t){t=fe(t,{from:null,to:null,options:{harsh:!1}});const e=new uo({start:t.from,stop:t.to});return t.options.line&&e.setLine(t.options.line),t.options.harsh&&e.setHarsh(t.options.harsh),e.setContext(this.context),this.renderQ.push(e),e}TextBracket(t){t=fe(t,{from:null,to:null,text:"",options:{superscript:"",position:1}});const e=new Ze({start:t.from,stop:t.to,text:t.text,superscript:t.options.superscript,position:t.options.position});return t.options.line&&e.setLine(t.options.line),t.options.font&&e.setFont(t.options.font),e.setContext(this.context),this.renderQ.push(e),e}System(t={}){t.factory=this;const e=new Va(t).setContext(this.context);return this.systems.push(e),e}EasyScore(t={}){return t.factory=this,new go(t)}PedalMarking(t={}){t=fe(t,{notes:[],options:{style:"mixed"}});const e=new Ot(t.notes);return e.setStyle(Ot.StylesString[t.options.style]),e.setContext(this.context),this.renderQ.push(e),e}NoteSubGroup(t={}){t=fe(t,{notes:[],options:{}});const e=new $s(t.notes);return e.setContext(this.context),e}draw(){this.systems.forEach(t=>t.setContext(this.context).format()),this.staves.forEach(t=>t.setContext(this.context).draw()),this.voices.forEach(t=>t.setContext(this.context).draw()),this.renderQ.forEach(t=>{t.isRendered()||t.setContext(this.context).draw()}),this.systems.forEach(t=>t.setContext(this.context).draw()),this.reset()}}function Zo(n,t){const e=t.options;return n=Object.assign(t,n),n.options=Object.assign(e,n.options),n}class Va extends he{constructor(t={}){super(),this.setAttribute("type","System"),this.setOptions(t),this.parts=[]}setOptions(t={}){this.options=Zo(t,{x:10,y:10,width:500,connector:null,spaceBetweenStaves:12,factory:null,debugFormatter:!1,formatIterations:0,options:{}}),this.factory=this.options.factory||new rn({renderer:{el:null}})}setContext(t){return super.setContext(t),this.factory.setContext(t),this}addConnector(t="double"){return this.connector=this.factory.StaveConnector({top_stave:this.parts[0].stave,bottom_stave:this.parts[this.parts.length-1].stave,type:t}),this.connector}addStave(t){return t=Zo(t,{stave:null,voices:[],spaceAbove:0,spaceBelow:0,debugNoteMetrics:!1,options:{left_bar:!1}}),t.stave||(t.stave=this.factory.Stave({x:this.options.x,y:this.options.y,width:this.options.width,options:t.options})),t.voices.forEach(e=>e.setContext(this.context).setStave(t.stave).getTickables().forEach(i=>i.setStave(t.stave))),this.parts.push(t),t.stave}format(){const t=new si;this.formatter=t;let e=this.options.y,i=0,s=[];const r=[];this.parts.forEach(a=>{e=e+a.stave.space(a.spaceAbove),a.stave.setY(e),t.joinVoices(a.voices),e=e+a.stave.space(a.spaceBelow),e=e+a.stave.space(this.options.spaceBetweenStaves),a.debugNoteMetrics&&(r.push({y:e,voice:a.voices[0]}),e+=15),s=s.concat(a.voices),i=Math.max(i,a.stave.getNoteStartX())}),this.parts.forEach(a=>a.stave.setNoteStartX(i));const o=this.options.width-(i-this.options.x)-Ie.STAVEPADDING;t.format(s,o);for(let a=0;a{e.voice.getTickables().forEach(i=>Ie.plotMetrics(t,i,e.y))})}}M.Flow=V;M.Flow.Element=he;M.Flow.Fraction=Rt;M.Flow.Renderer=Zt;M.Flow.Formatter=si;M.Flow.Music=te;M.Flow.Glyph=xt;M.Flow.Stave=sn;M.Flow.StaveNote=ae;M.Flow.StaveModifier=Vt;M.Flow.StaveTempo=$n;M.Flow.Voice=ye;M.Flow.Accidental=is;M.Flow.Beam=Vi;M.Flow.StaveTie=Qn;M.Flow.TabStave=Ia;M.Flow.TabNote=nn;M.Flow.Bend=Oe;M.Flow.Vibrato=vs;M.Flow.VibratoBracket=uo;M.Flow.Note=Ie;M.Flow.ModifierContext=Ys;M.Flow.MultiMeasureRest=ka;M.Flow.TickContext=xs;M.Flow.Articulation=Ri;M.Flow.Annotation=se;M.Flow.Barline=Xt;M.Flow.NoteHead=Ms;M.Flow.StaveConnector=Bt;M.Flow.ClefNote=tr;M.Flow.KeySignature=ss;M.Flow.KeySigNote=Ba;M.Flow.TimeSignature=Wi;M.Flow.TimeSigNote=Da;M.Flow.Stem=ft;M.Flow.TabTie=ys;M.Flow.Clef=hi;M.Flow.Dot=Gi;M.Flow.Modifier=St;M.Flow.TabSlide=pi;M.Flow.Tuplet=He;M.Flow.GraceNote=ts;M.Flow.GraceTabNote=fo;M.Flow.Tuning=Rn;M.Flow.KeyManager=Pc;M.Flow.StaveHairpin=Ws;M.Flow.BoundingBox=es;M.Flow.Stroke=Te;M.Flow.TextNote=li;M.Flow.Curve=oi;M.Flow.TextDynamics=_s;M.Flow.StaveLine=mi;M.Flow.Ornament=en;M.Flow.PedalMarking=Ot;M.Flow.TextBracket=Ze;M.Flow.FretHandFinger=Qs;M.Flow.Repetition=_e;M.Flow.BarNote=po;M.Flow.GhostNote=Fa;M.Flow.NoteSubGroup=$s;M.Flow.GraceNoteGroup=Ps;M.Flow.Tremolo=Zi;M.Flow.StringNumber=tn;M.Flow.Crescendo=Oa;M.Flow.Volta=ti;M.Flow.Font=bn;M.Flow.System=Va;M.Flow.Factory=rn;M.Flow.Parser=mo;M.Flow.EasyScore=go;M.Flow.Registry=gi;var Et=(n=>(n[n.SingleThin=0]="SingleThin",n[n.DoubleThin=1]="DoubleThin",n[n.ThinBold=2]="ThinBold",n[n.BoldThinDots=3]="BoldThinDots",n[n.DotsThinBold=4]="DotsThinBold",n[n.DotsBoldBoldDots=5]="DotsBoldBoldDots",n[n.None=6]="None",n[n.Dotted=7]="Dotted",n[n.Dashed=8]="Dashed",n[n.Bold=9]="Bold",n[n.BoldThin=10]="BoldThin",n[n.DoubleBold=11]="DoubleBold",n[n.Tick=12]="Tick",n[n.Short=13]="Short",n))(Et||{});class Wc{static xmlBarlineStyleToSystemLinesEnum(t){return t==="regular"?0:t==="dotted"?7:t==="dashed"?8:t==="heavy"?9:t==="light-light"?1:t==="light-heavy"?2:t==="heavy-light"?10:t==="heavy-heavy"?11:t==="tick"?12:t==="short"?13:t==="none"?6:0}}class js{constructor(){this.matrix=[];for(let t=0;t<2;t++){this.matrix[t]=[];for(let e=0;e<2;e++)this.matrix[t][e]=0}}static getRotationMatrix(t){const e=new js,i=Math.cos(t),s=Math.sin(t);return e.matrix[0][0]=i,e.matrix[0][1]=-s,e.matrix[1][0]=s,e.matrix[1][1]=i,e}scalarMultiplication(t){for(let e=0;e<2;e++)for(let i=0;i<2;i++)this.matrix[e][i]*=t}getTransposeMatrix(){const t=new js;for(let e=0;e<2;e++)for(let i=0;i<2;i++)t.matrix[e][i]=this.matrix[i][e];return t}vectorMultiplication(t){const e=new O;return e.x=t.x*this.matrix[0][0]+t.y*this.matrix[0][1],e.y=t.x*this.matrix[1][0]+t.y*this.matrix[1][1],e}}class Uc{constructor(){this.measureErrors={},this.errors=[],this.tempErrors=[]}finalizeMeasure(t){let e=this.measureErrors[t];e||(e=[]),this.measureErrors[t]=e.concat(this.tempErrors),this.tempErrors=[]}pushMeasureError(t){this.tempErrors.push(t)}push(t){this.errors.push(t)}}class zc{constructor(t,e=Xe.ARPEGGIO_DIRECTIONLESS){this.parentVoiceEntry=t,this.type=e,this.notes=[]}addNote(t){this.notes.push(t),t.Arpeggio=this}}var Xe=(n=>(n[n.BRUSH_DOWN=1]="BRUSH_DOWN",n[n.BRUSH_UP=2]="BRUSH_UP",n[n.ROLL_DOWN=3]="ROLL_DOWN",n[n.ROLL_UP=4]="ROLL_UP",n[n.RASQUEDO_DOWN=5]="RASQUEDO_DOWN",n[n.RASQUEDO_UP=6]="RASQUEDO_UP",n[n.ARPEGGIO_DIRECTIONLESS=7]="ARPEGGIO_DIRECTIONLESS",n))(Xe||{});class Hc{constructor(t=1,e=0){this.notes=[],this.extendedNoteList=[],this.BeamNumberOffsetToXML=0,this.BeamNumber=t,this.BeamNumberOffsetToXML=e}get Notes(){return this.notes}set Notes(t){this.notes=t}get ExtendedNoteList(){return this.extendedNoteList}set ExtendedNoteList(t){this.extendedNoteList=t}addNoteToBeam(t){t&&(t.NoteBeam=this,this.notes.push(t),this.extendedNoteList.push(t))}}class bo{constructor(t,e){this.voiceEntries=[],this.volume=1,this.parent=t,this.visible=!0,this.audible=!0,this.following=!0,this.voiceId=e,this.uniqueVoiceId="I:"+this.parent.Id+" V: "+this.voiceId}get VoiceEntries(){return this.voiceEntries}get Parent(){return this.parent}get Visible(){return this.visible}set Visible(t){this.visible=t}get Audible(){return this.audible}set Audible(t){this.audible=t}get Following(){return this.following}set Following(t){this.following=t}get Solo(){return this.solo}set Solo(t){this.solo=t}get VoiceId(){return this.voiceId}get Volume(){return this.volume}set Volume(t){this.volume=t}toString(){return this.uniqueVoiceId}}class bs extends bo{constructor(t,e,i){super(t,e),this.master=i}get Master(){return this.master}}class So{constructor(t,e,i=void 0){this.sourceNote=t,this.setShapeFromXml(e,i)}setShapeFromXml(t,e=void 0){this.shape=So.ShapeTypeXmlToShape(t);let i=e;i===void 0&&(this.sourceNote?i=this.sourceNote.Length.Denominator>2:(j.warn("notehead: sourceNote and filledXmlAttribute undefined."),i=!0)),this.filled=i}get SourceNote(){return this.sourceNote}get Shape(){return this.shape}get Filled(){return this.filled}static ShapeTypeXmlToShape(t){switch(t.toLowerCase()){case"normal":return Qt.NORMAL;case"x":return Qt.X;case"slash":return Qt.SLASH;case"diamond":return Qt.DIAMOND;case"square":return Qt.SQUARE;case"la":return Qt.SQUARE;case"do":case"triangle":return Qt.TRIANGLE;case"rectangle":return Qt.RECTANGLE;case"circle-x":return Qt.CIRCLEX;default:return j.info("unsupported/unhandled xml notehead '"+t+"'. Using normal notehead."),Qt.NORMAL}}}var Qt=(n=>(n[n.CIRCLEX=0]="CIRCLEX",n[n.DIAMOND=1]="DIAMOND",n[n.NORMAL=2]="NORMAL",n[n.RECTANGLE=3]="RECTANGLE",n[n.SLASH=4]="SLASH",n[n.SQUARE=5]="SQUARE",n[n.TRIANGLE=6]="TRIANGLE",n[n.X=7]="X",n))(Qt||{});class Tt{static translateText(t,e){if(!this.defaultTextTranslation)return e}}var yo=(n=>(n[n.UNDEFINED=0]="UNDEFINED",n[n._1024th=1]="_1024th",n[n._512th=2]="_512th",n[n._256th=3]="_256th",n[n._128th=4]="_128th",n[n._64th=5]="_64th",n[n._32nd=6]="_32nd",n[n._16th=7]="_16th",n[n.EIGTH=8]="EIGTH",n[n.QUARTER=9]="QUARTER",n[n.HALF=10]="HALF",n[n.WHOLE=11]="WHOLE",n[n.BREVE=12]="BREVE",n[n.LONG=13]="LONG",n[n.MAXIMA=14]="MAXIMA",n))(yo||{});class ws{static NoteTypeToString(t){return this.NoteTypeXmlValues[t]}static StringToNoteType(t){const e=this.NoteTypeXmlValues.indexOf(t);return e!==-1?e:0}static getNoteDurationFromType(t){switch(t){case"1024th":return new W(1,1024);case"512th":return new W(1,512);case"256th":return new W(1,256);case"128th":return new W(1,128);case"64th":return new W(1,64);case"32th":case"32nd":return new W(1,32);case"16th":return new W(1,16);case"eighth":return new W(1,8);case"quarter":return new W(1,4);case"half":return new W(1,2);case"whole":return new W(1,1);case"breve":return new W(2,1);case"long":return new W(4,1);case"maxima":return new W(8,1);default:{const e=Tt.translateText("ReaderErrorMessages/NoteDurationError","Invalid note duration.");throw new Ee(e)}}}}ws.NoteTypeXmlValues=["","1024th","512th","256th","128th","64th","32nd","16th","eigth","quarter","half","whole","breve","long","maxima"];class Xc{constructor(t){this.placement=z.Above,this.accidentalAbove=yt.NONE,this.accidentalBelow=yt.NONE,this.ornament=t}get GetOrnament(){return this.ornament}get AccidentalAbove(){return this.accidentalAbove}set AccidentalAbove(t){this.accidentalAbove=t}get AccidentalBelow(){return this.accidentalBelow}set AccidentalBelow(t){this.accidentalBelow=t}}var Ne=(n=>(n[n.Trill=0]="Trill",n[n.Turn=1]="Turn",n[n.InvertedTurn=2]="InvertedTurn",n[n.DelayedTurn=3]="DelayedTurn",n[n.DelayedInvertedTurn=4]="DelayedInvertedTurn",n[n.Mordent=5]="Mordent",n[n.InvertedMordent=6]="InvertedMordent",n))(Ne||{});class yn{constructor(t,e,i){this.staffEntries=[],this.comments=[],this.timestamp=e,this.staffEntries=new Array(i),this.parentMeasure=t}$get$(t){return this.staffEntries[t]}$set$(t,e){this.staffEntries[t]=e}get Timestamp(){return this.timestamp}set Timestamp(t){this.timestamp=t}get StaffEntries(){return this.staffEntries}set StaffEntries(t){this.staffEntries=t}get Comments(){return this.comments}set Comments(t){this.comments=t}get ParentMeasure(){return this.parentMeasure}set ParentMeasure(t){this.parentMeasure=t}getAbsoluteTimestamp(){return W.plus(this.timestamp,this.parentMeasure.AbsoluteTimestamp)}}class we{constructor(t,e){this.voiceEntries=[],this.instructions=[],this.chordSymbolContainers=[],this.verticalContainerParent=t,this.parentStaff=e}get ParentStaff(){return this.parentStaff}get VerticalContainerParent(){return this.verticalContainerParent}get Timestamp(){if(this.VerticalContainerParent)return this.VerticalContainerParent.Timestamp}get AbsoluteTimestamp(){if(this.VerticalContainerParent)return W.plus(this.VerticalContainerParent.ParentMeasure.AbsoluteTimestamp,this.VerticalContainerParent.Timestamp)}get VoiceEntries(){return this.voiceEntries}set VoiceEntries(t){this.voiceEntries=t}get Link(){return this.staffEntryLink}set Link(t){this.staffEntryLink=t}get Instructions(){return this.instructions}set Instructions(t){this.instructions=t}get ChordContainers(){return this.chordSymbolContainers}set ChordContainers(t){this.chordSymbolContainers=t}removeAllInstructionsOfTypeClefInstruction(){let t=0,e=0;for(;t0)return!0;return!1}hasTie(){for(let t=0,e=this.VoiceEntries.length;te.parentRepetition.StartIndex)return-1}if(t.alignment===Dt.Begin&&e.alignment===Dt.Begin){if(t.parentRepetition.EndIndexe.parentRepetition.EndIndex)return-1}}return 0}}class It{constructor(t,e,i=Dt.End,s=void 0,r=void 0){this.endingIndices=void 0,this.measureIndex=t,r&&(this.endingIndices=r.slice()),this.type=e,this.alignment=i,this.parentRepetition=s}CompareTo(t){const e=t;if(this.measureIndex>e.measureIndex)return 1;if(this.measureIndex(n[n.StartLine=0]="StartLine",n[n.ForwardJump=1]="ForwardJump",n[n.BackJumpLine=2]="BackJumpLine",n[n.Ending=3]="Ending",n[n.DaCapo=4]="DaCapo",n[n.DalSegno=5]="DalSegno",n[n.Fine=6]="Fine",n[n.ToCoda=7]="ToCoda",n[n.DalSegnoAlFine=8]="DalSegnoAlFine",n[n.DaCapoAlFine=9]="DaCapoAlFine",n[n.DalSegnoAlCoda=10]="DalSegnoAlCoda",n[n.DaCapoAlCoda=11]="DaCapoAlCoda",n[n.Coda=12]="Coda",n[n.Segno=13]="Segno",n[n.None=14]="None",n))(q||{}),Dt=(n=>(n[n.Begin=0]="Begin",n[n.End=1]="End",n))(Dt||{});let xi=null;class Yc{constructor(t,e){this.printNewSystemXml=!1,this.printNewPageXml=!1,this.IsSystemStartMeasure=!1,this.hasLyrics=!1,this.hasMoodExpressions=!1,this.allRests=!1,this.isReducedToMultiRest=!1,this.multipleRestMeasureNumber=0,this.staffLinkedExpressions=[],this.tempoExpressions=[],this.verticalSourceStaffEntryContainers=[],this.graphicalMeasureErrors=[],this.firstRepetitionInstructions=[],this.lastRepetitionInstructions=[],this.metronomeNoteIndex=0,this.completeNumberOfStaves=t,this.implicitMeasure=!1,this.hasEndLine=!1,this.endingBarStyleXml="",this.endingBarStyleEnum=Et.SingleThin,this.firstInstructionsStaffEntries=new Array(t),this.lastInstructionsStaffEntries=new Array(t),this.rules=e,this.TempoInBPM=0;for(let i=0;i1)return t[this.measureListIndex-1]}get Rules(){return this.rules}get VerticalMeasureList(){return this.verticalMeasureList}set VerticalMeasureList(t){this.verticalMeasureList=t}get TempoInBPM(){return this.tempoInBPM}set TempoInBPM(t){this.tempoInBPM=t}findOrCreateStaffEntry(t,e,i){let s,r;for(const a of this.verticalSourceStaffEntryContainers)if(a.Timestamp.Equals(t)){r=a;break}if(r)return r.StaffEntries[e]?s=r.StaffEntries[e]:(s=new we(r,i),r.StaffEntries[e]=s),{createdNewContainer:!1,staffEntry:s};const o=this.verticalSourceStaffEntryContainers[this.verticalSourceStaffEntryContainers.length-1];if(this.verticalSourceStaffEntryContainers.length===0||o.Timestamp.lt(t)){const a=new yn(this,t.clone(),this.completeNumberOfStaves);this.verticalSourceStaffEntryContainers.push(a),s=new we(a,i),a.StaffEntries[e]=s}else for(let a=this.verticalSourceStaffEntryContainers.length-1;a>=0;a--){if(this.verticalSourceStaffEntryContainers[a].Timestamp.lt(t)){const l=new yn(this,t.clone(),this.completeNumberOfStaves);this.verticalSourceStaffEntryContainers.splice(a+1,0,l),s=new we(l,i),l.StaffEntries[e]=s;break}if(a===0){const l=new yn(this,t.clone(),this.completeNumberOfStaves);this.verticalSourceStaffEntryContainers.splice(a,0,l),s=new we(l,i),l.StaffEntries[e]=s;break}}return{createdNewContainer:!0,staffEntry:s}}findOrCreateVoiceEntry(t,e){let i,s=!1;for(const r of t.VoiceEntries)if(r.ParentVoice===e){i=r;break}return i||(i=new ir(t.Timestamp,e,t),s=!0),{createdVoiceEntry:s,voiceEntry:i}}getPreviousSourceStaffEntryFromIndex(t,e){for(let i=e-1;i>=0;i--)if(this.verticalSourceStaffEntryContainers[i][t])return this.verticalSourceStaffEntryContainers[i][t]}getVerticalContainerIndexByTimestamp(t){for(let e=0,i=this.VerticalSourceStaffEntryContainers.length;e=0;u--){const f=this.verticalSourceStaffEntryContainers[u][a+l];if(f!==void 0&&f.hasTie()&&o.lt(W.plus(f.Timestamp,f.calculateMaxNoteLength()))){o=W.plus(f.Timestamp,f.calculateMaxNoteLength());break}}}}s.push(o)}for(let r=0,o=s.length;r0)return!0}return!1}beginsWithLineRepetition(){for(let t=0,e=this.FirstRepetitionInstructions.length;t=0&&(e=this.verticalSourceStaffEntryContainers[i].StaffEntries[t],!e);i--);return e}canBeReducedToMultiRest(){var i,s,r,o,a,l;let t=!0,e=!1;for(const h of this.verticalSourceStaffEntryContainers)if(!!h){for(const c of h.StaffEntries)if(!(!c||!c.ParentStaff.ParentInstrument.Visible)){if(c.ChordContainers.length>0||(c.ParentStaff.hasLyrics&&(e=!0),this.firstRepetitionInstructions.length>0||this.lastRepetitionInstructions.length>0))return!1;for(const u of c.VoiceEntries){for(const f of u.Notes)if(!f.isRest()){t=!1;break}if(!t)break}}}if(!t||e||this.hasMoodExpressions||this.tempoExpressions.length>0)return!1;for(const h of this.staffLinkedExpressions)if(h.length>0)return!1;for(const h of this.lastInstructionsStaffEntries)for(let c=0,u=h==null?void 0:h.Instructions.length;c=0;e--)for(let i=0;i(n[n.Fingering=0]="Fingering",n[n.String=1]="String",n))(Pr||{});class Jc{}class er{constructor(t,e){this.parentEntry=t,this.parentNote=e,this.ParentNote.PlaybackNote=this,this.Length=this.ParentNote.Length,e.Pitch!==void 0?this.ParentNote.ParentStaff.ParentInstrument.MidiInstrumentId===st.Percussion?this.MidiKey=er.noteToMidiDrumKey(e):this.MidiKey=e.Pitch.getHalfTone()+12:this.MidiKey=0}setLength(){this.ParentNote.NoteTie!==void 0&&this.ParentNote.NoteTie.StartNote===this.ParentNote&&(this.Length=this.ParentNote.NoteTie.Duration)}get ParentEntry(){return this.parentEntry}get ParentNote(){return this.parentNote}static noteToMidiDrumKey(t){var s;const e=t.Pitch.getHalfTone()-12,i=(s=t.Notehead)==null?void 0:s.Shape;switch(t.Pitch.Octave){case 1:switch(t.Pitch.FundamentalNote){case ut.D:switch(i){default:return 44}case ut.E:switch(i){default:return 35}case ut.F:switch(i){default:return 36}case ut.G:switch(i){default:return 41}case ut.A:switch(i){default:return 43}case ut.B:switch(i){case Qt.TRIANGLE:return 54;default:return 47}default:return e}case 2:switch(t.Pitch.FundamentalNote){case ut.C:switch(i){case Qt.X:return 37;default:return 38}case ut.D:switch(i){case Qt.X:return 59;default:return 48}case ut.E:switch(i){case Qt.X:return 42;case Qt.CIRCLEX:return 46;case Qt.TRIANGLE:return 56;default:return 50}case ut.F:switch(i){case Qt.DIAMOND:return 53;default:return 51}case ut.G:switch(i){case Qt.CIRCLEX:case Qt.DIAMOND:return 46;default:return 42}case ut.A:switch(i){default:return 49}case ut.B:switch(i){default:return 57}default:return e}case 3:switch(t.Pitch.FundamentalNote){case ut.C:switch(i){case Qt.CIRCLEX:return 52;default:return 55}default:return e}default:return e}}}class Zc{constructor(t){this.notes=[],this.TimestampShift=new W,this.parentVoiceEntry=t;for(const e of t.Notes)this.Notes.push(new er(this,e))}get ParentVoiceEntry(){return this.parentVoiceEntry}get Notes(){return this.notes}get Length(){if(this.Notes.length>0)return this.Notes[0].Length}set Length(t){for(const e of this.Notes)e.Length=t}get HasNotes(){return this.Notes.length>0}}class ir{constructor(t,e,i,s=!0,r=!1,o=!1,a=!1){if(this.notes=[],this.graceVoiceEntriesBefore=[],this.graceVoiceEntriesAfter=[],this.articulations=[],this.playbackEntries=[],this.technicalInstructions=[],this.lyricsEntries=new Ye,this.wantedStemDirection=Ft.Undefined,this.stemDirectionXml=Ft.Undefined,this.stemDirection=Ft.Undefined,this.timestamp=t,this.parentVoice=e,this.parentSourceStaffEntry=i,this.isGrace=r,this.graceAfterMainNote=!1,this.graceNoteSlash=o,this.graceSlur=a,r||e.VoiceEntries.push(this),s&&i!==void 0){const l=i.VoiceEntries;l.indexOf(this)===-1&&l.push(this)}this.mainPlaybackEntry=new Zc(this),this.PlaybackEntries.push(this.mainPlaybackEntry)}get ParentSourceStaffEntry(){return this.parentSourceStaffEntry}get ParentVoice(){return this.parentVoice}get Timestamp(){return this.timestamp}set Timestamp(t){this.timestamp=t}get Notes(){return this.notes}addNote(t){this.notes.push(t),!t.isRest()&&(t.NoteTie===void 0||t.NoteTie.StartNote===t)&&this.MainPlaybackEntry.Notes.push(new er(this.MainPlaybackEntry,t))}get GraceVoiceEntriesBefore(){return this.graceVoiceEntriesBefore}set GraceVoiceEntriesBefore(t){this.graceVoiceEntriesBefore=t;for(const e of this.graceVoiceEntriesBefore)e.parentSourceStaffEntry=this.ParentSourceStaffEntry}get GraceVoiceEntriesAfter(){return this.graceVoiceEntriesAfter}set GraceVoiceEntriesAfter(t){this.graceVoiceEntriesAfter=t;for(const e of this.graceVoiceEntriesAfter)e.parentSourceStaffEntry=this.ParentSourceStaffEntry}get IsGrace(){return this.isGrace}set IsGrace(t){this.isGrace=t}get GraceAfterMainNote(){return this.graceAfterMainNote}set GraceAfterMainNote(t){this.graceAfterMainNote=t}get GraceNoteSlash(){return this.graceNoteSlash}set GraceNoteSlash(t){this.graceNoteSlash=t}get GraceSlur(){return this.graceSlur}set GraceSlur(t){this.graceSlur=t}get Articulations(){return this.articulations}get PlaybackEntries(){return this.playbackEntries}get Fermata(){return this.fermata}get MainPlaybackEntry(){return this.mainPlaybackEntry}set MainPlaybackEntry(t){this.mainPlaybackEntry=t}removeMainPlaybackEntry(){this.mainPlaybackEntry!==void 0&&this.removePlaybackEntry(this.mainPlaybackEntry)}removePlaybackEntry(t){this.mainPlaybackEntry===t&&(this.mainPlaybackEntry=void 0);const e=this.playbackEntries.indexOf(t);e>-1&&this.playbackEntries.splice(e,1)}get TechnicalInstructions(){return this.technicalInstructions}get LyricsEntries(){return this.lyricsEntries}get Arpeggio(){return this.arpeggio}set Arpeggio(t){this.arpeggio=t}get OrnamentContainer(){return this.ornamentContainer}set OrnamentContainer(t){this.ornamentContainer=t}set WantedStemDirection(t){this.wantedStemDirection=t}get WantedStemDirection(){return this.wantedStemDirection}set StemDirectionXml(t){this.stemDirectionXml=t}get StemDirectionXml(){return this.stemDirectionXml}set StemDirection(t){this.stemDirection=t}get StemDirection(){return this.stemDirection}get StemColorXml(){return this.stemColorXml}set StemColorXml(t){this.stemColorXml=t}get StemColor(){return this.stemColor}set StemColor(t){this.stemColor=t}get VolumeModifier(){return this.volumeModifier}set VolumeModifier(t){this.volumeModifier=t}get DurationModifier(){return this.durationModifier}set DurationModifier(t){this.durationModifier=t}hasArticulation(t){for(const e of this.articulations)if(e.Equals(t))return!0;return!1}static isSupportedArticulation(t){switch(t){case wt.accent:case wt.strongaccent:case wt.invertedstrongaccent:case wt.staccato:case wt.staccatissimo:case wt.spiccato:case wt.tenuto:case wt.fermata:case wt.invertedfermata:case wt.breathmark:case wt.caesura:case wt.lefthandpizzicato:case wt.naturalharmonic:case wt.snappizzicato:case wt.upbow:case wt.downbow:case wt.bend:case wt.detachedlegato:return!0;default:return!1}}hasTie(){for(let t=0,e=this.Notes.length;t0)return!0;return!1}isStaccato(){for(const t of this.Articulations)if(t.articulationEnum===wt.staccato)return!0;return!1}isAccent(){for(const t of this.Articulations)if(t.articulationEnum===wt.accent||t.articulationEnum===wt.strongaccent)return!0;return!1}getVerseNumberForLyricEntry(t){let e=1;return this.lyricsEntries.forEach((i,s)=>{t===s&&(e=i)}),e}}var wt=(n=>(n[n.accent=0]="accent",n[n.strongaccent=1]="strongaccent",n[n.marcatoup=2]="marcatoup",n[n.marcatodown=3]="marcatodown",n[n.invertedstrongaccent=4]="invertedstrongaccent",n[n.staccato=5]="staccato",n[n.staccatissimo=6]="staccatissimo",n[n.spiccato=7]="spiccato",n[n.tenuto=8]="tenuto",n[n.fermata=9]="fermata",n[n.invertedfermata=10]="invertedfermata",n[n.breathmark=11]="breathmark",n[n.caesura=12]="caesura",n[n.lefthandpizzicato=13]="lefthandpizzicato",n[n.naturalharmonic=14]="naturalharmonic",n[n.snappizzicato=15]="snappizzicato",n[n.upbow=16]="upbow",n[n.downbow=17]="downbow",n[n.scoop=18]="scoop",n[n.plop=19]="plop",n[n.doit=20]="doit",n[n.falloff=21]="falloff",n[n.stress=22]="stress",n[n.unstress=23]="unstress",n[n.detachedlegato=24]="detachedlegato",n[n.otherarticulation=25]="otherarticulation",n[n.bend=26]="bend",n))(wt||{}),Ft=(n=>(n[n.Undefined=-1]="Undefined",n[n.Up=0]="Up",n[n.Down=1]="Down",n[n.None=2]="None",n[n.Double=3]="Double",n))(Ft||{}),ns=(n=>(n[n.MeasureBegin=0]="MeasureBegin",n[n.MeasureEnd=1]="MeasureEnd",n))(ns||{});class Se extends Tn{constructor(t,e,i,s,r=void 0){super(),this.label=t,this.boundingBox=new le(this,r),this.label.fontHeight=e,this.label.textAlignment=i,this.rules=s,this.rules.MpatMode&&this.label.text==="TRIO"&&(this.label.fontFamily="Arial")}get Label(){return this.label}toString(){return`${this.label.text} (${this.boundingBox.RelativePosition.x},${this.boundingBox.RelativePosition.y})`}setLabelPositionAndShapeBorders(){var a,l;if(this.Label.text.trim()==="")return;this.TextLines=[];const t=(l=(a=this.rules)==null?void 0:a.LabelMarginBorderFactor)!=null?l:.1,e=this.Label.text.split(/[\n\r]+/g),i=e.length;let s=0;for(let h=0;h0&&this.TextLines.length>1&&(r+=this.rules.SpacingBetweenTextLines*i/10);const o=this.PositionAndShape;switch(this.Label.textAlignment){case vt.CenterBottom:o.BorderTop=-r,o.BorderLeft=-s/2,o.BorderBottom=0,o.BorderRight=s/2;break;case vt.CenterCenter:o.BorderTop=-r/2,o.BorderLeft=-s/2,o.BorderBottom=r/2,o.BorderRight=s/2;break;case vt.CenterTop:o.BorderTop=0,o.BorderLeft=-s/2,o.BorderBottom=r,o.BorderRight=s/2;break;case vt.LeftBottom:o.BorderTop=-r,o.BorderLeft=0,o.BorderBottom=0,o.BorderRight=s;break;case vt.LeftCenter:o.BorderTop=-r/2,o.BorderLeft=0,o.BorderBottom=r/2,o.BorderRight=s;break;case vt.LeftTop:o.BorderTop=0,o.BorderLeft=0,o.BorderBottom=r,o.BorderRight=s;break;case vt.RightBottom:o.BorderTop=-r,o.BorderLeft=-s,o.BorderBottom=0,o.BorderRight=0;break;case vt.RightCenter:o.BorderTop=-r/2,o.BorderLeft=-s,o.BorderBottom=r/2,o.BorderRight=0;break;case vt.RightTop:o.BorderTop=0,o.BorderLeft=-s,o.BorderBottom=r,o.BorderRight=0;break}o.BorderMarginTop=o.BorderTop-r*t,o.BorderMarginLeft=o.BorderLeft-r*t,o.BorderMarginBottom=o.BorderBottom+r*t,o.BorderMarginRight=o.BorderRight+r*t}}class jt{constructor(t="",e=vt.CenterBottom,i=void 0,s=!0){this.IsCreditLabel=!1,this.text=t,this.print=s,this.textAlignment=e,this.font=i,this.fontFamily=void 0}set font(t){this.fontEnumValue=t,this.fontFamily=Jh[t]}get font(){return this.fontEnumValue}ToString(){return this.text}}const Lr={Grava:40,Largo:46,Lento:52,Adagio:56,Larghetto:60,Andante:66,Anderato:69,Andantino:69,Moderato:88,Allegretto:108,"Allegro Moderato":108,Allegro:132,Vivace:152,Vivo:160,Vivacissimo:168,Presto:184,Prestissimo:208},Qc=["\u7EAF\u5F8B","\u7EAF\u5F8B\u7ED3\u675F"],$c=["\u8DF3\u8FC7\u4E0B\u4E00\u4E2A","b","#","\xA7","\xBA","X"],Ga=["poco rit.","rall.","rit.","accel.","molto rit.","molto rall","lentando","poco accel.","calando"],Wa="\u7ED3\u675F\u8303\u56F4\u901F\u5EA6",$1="a tempo",tu=[Wa],Ua="\u901F\u5EA6 ",za="\u4EC5\u6587\u672C\u901F\u5EA6 ";function ps(n){return n.indexOf(Ua)===0}function An(n){return n.indexOf(za)===0}function eu(n){return n.replace(za,"").replace(Ua,"")}function tp(n){return Ga.includes(n)}function Ha(n){return[...Object.keys(Lr),...Qc,...tu,...$c].map(t=>t.trim().toLocaleUpperCase()).includes(n.toLocaleUpperCase().trim())}function $o(n){return[vt.CenterTop,vt.RightTop].includes(n)}var Ge=(n=>(n[n.Unused_first_Symbol=0]="Unused_first_Symbol",n[n.BLACK_HEAD=1]="BLACK_HEAD",n[n.UPWARDS_TAIL=2]="UPWARDS_TAIL",n[n.DOWNWARDS_TAIL=3]="DOWNWARDS_TAIL",n[n.UPWARDS_DOUBLE_TAIL=4]="UPWARDS_DOUBLE_TAIL",n[n.DOWNWARDS_DOUBLE_TAIL=5]="DOWNWARDS_DOUBLE_TAIL",n[n.UPWARDS_TRIPLE_TAIL=6]="UPWARDS_TRIPLE_TAIL",n[n.DOWNWARDS_TRIPLE_TAIL=7]="DOWNWARDS_TRIPLE_TAIL",n[n.UPWARDS_QUAD_TAIL=8]="UPWARDS_QUAD_TAIL",n[n.DOWNWARDS_QUAD_TAIL=9]="DOWNWARDS_QUAD_TAIL",n[n.ROUND_HEAD=10]="ROUND_HEAD",n[n.WHITE_HEAD=11]="WHITE_HEAD",n[n.G_CLEF=12]="G_CLEF",n[n.F_CLEF=13]="F_CLEF",n[n.C_CLEF=14]="C_CLEF",n[n.BREVE=15]="BREVE",n[n.BREVE_REST=16]="BREVE_REST",n[n.COMMON_TIME=17]="COMMON_TIME",n[n.CUT_TIME=18]="CUT_TIME",n[n.WHOLE_REST=19]="WHOLE_REST",n[n.HALF_REST=20]="HALF_REST",n[n.QUARTER_REST=21]="QUARTER_REST",n[n.EIGHTH_REST=22]="EIGHTH_REST",n[n.SIXTEENTH_REST=23]="SIXTEENTH_REST",n[n.THIRTYSECOND_REST=24]="THIRTYSECOND_REST",n[n.SIXTYFOURTH_REST=25]="SIXTYFOURTH_REST",n[n.FLAT=26]="FLAT",n[n.SHARP=27]="SHARP",n[n.NATURAL=28]="NATURAL",n[n.DOUBLE_FLAT=29]="DOUBLE_FLAT",n[n.DOUBLE_SHARP=30]="DOUBLE_SHARP",n[n.ZERO=31]="ZERO",n[n.ONE=32]="ONE",n[n.TWO=33]="TWO",n[n.THREE=34]="THREE",n[n.FOUR=35]="FOUR",n[n.FIVE=36]="FIVE",n[n.SIX=37]="SIX",n[n.SEVEN=38]="SEVEN",n[n.EIGHT=39]="EIGHT",n[n.NINE=40]="NINE",n[n.DOT=41]="DOT",n[n.FERMATA=42]="FERMATA",n[n.INVERTED_FERMATA=43]="INVERTED_FERMATA",n[n.SPICCATO=44]="SPICCATO",n[n.TENUTO=45]="TENUTO",n[n.MARCATO=46]="MARCATO",n[n.MARCATISSIMO=47]="MARCATISSIMO",n[n.INVERTED_MARCATISSIMO=48]="INVERTED_MARCATISSIMO",n[n.P=49]="P",n[n.F=50]="F",n[n.S=51]="S",n[n.Z=52]="Z",n[n.M=53]="M",n[n.R=54]="R",n[n.SEGNO=55]="SEGNO",n[n.CODA=56]="CODA",n[n.DRUM_CLEF=57]="DRUM_CLEF",n[n.G_CLEF_SUB8=58]="G_CLEF_SUB8",n[n.G_CLEF_SUPER8=59]="G_CLEF_SUPER8",n[n.G_CLEF_SUB15=60]="G_CLEF_SUB15",n[n.G_CLEF_SUPER15=61]="G_CLEF_SUPER15",n[n.F_CLEF_SUB8=62]="F_CLEF_SUB8",n[n.F_CLEF_SUPER8=63]="F_CLEF_SUPER8",n[n.F_CLEF_SUB15=64]="F_CLEF_SUB15",n[n.F_CLEF_SUPER15=65]="F_CLEF_SUPER15",n[n.DOWN_BOW=66]="DOWN_BOW",n[n.MORDENT=67]="MORDENT",n[n.INVERTED_MORDENT=68]="INVERTED_MORDENT",n[n.TURN=69]="TURN",n[n.INVERTED_TURN=70]="INVERTED_TURN",n[n.LEFTHAND_PIZZICATO=71]="LEFTHAND_PIZZICATO",n[n.RELEASE_PED=72]="RELEASE_PED",n[n.ENGAGE_PED=73]="ENGAGE_PED",n[n.VA8=74]="VA8",n[n.VB8=75]="VB8",n[n.TRILL=76]="TRILL",n[n.MA15=77]="MA15",n[n.MB15=78]="MB15",n[n.HIGH=79]="HIGH",n[n.PLAY=80]="PLAY",n[n.MIC=81]="MIC",n[n.SNAP_PIZZICATO=82]="SNAP_PIZZICATO",n[n.NATURAL_HARMONIC=83]="NATURAL_HARMONIC",n[n.EditPen=84]="EditPen",n[n.PEDAL_BRACKET=85]="PEDAL_BRACKET",n[n.PEDAL_MIXED=86]="PEDAL_MIXED",n[n.PEDAL_SYMBOL=87]="PEDAL_SYMBOL",n))(Ge||{}),xn=(n=>(n[n.Normal=0]="Normal",n[n.Disabled=1]="Disabled",n[n.Selected=2]="Selected",n[n.Clickable=3]="Clickable",n[n.PlaybackSymbols=4]="PlaybackSymbols",n[n.FollowSymbols=5]="FollowSymbols",n[n.QFeedbackNotFound=6]="QFeedbackNotFound",n[n.QFeedbackOk=7]="QFeedbackOk",n[n.QFeedbackPerfect=8]="QFeedbackPerfect",n[n.Debug1=9]="Debug1",n[n.Debug2=10]="Debug2",n[n.Debug3=11]="Debug3",n))(xn||{}),vn=(n=>(n[n.Following=0]="Following",n[n.Midi=1]="Midi",n[n.Manual=2]="Manual",n))(vn||{});class ta{}class iu{constructor(t,e){this.drawableBoundingBoxElement="None",this.skyLineVisible=!1,this.bottomLineVisible=!1,this.phonicScoreMode=vn.Manual,this.textMeasurer=t,this.splitScreenLineColor=-1,this.drawingParameters=e,this.rules=e.Rules}set Mode(t){this.phonicScoreMode=t}drawSheet(t){if(this.graphicalMusicSheet=t,this.rules=t.ParentMusicSheet.Rules,this.drawSplitScreenLine(),this.drawingParameters.drawCursors)for(const i of t.Cursors){if(!i)continue;const s=new le(i);s.AbsolutePosition=i.Start,s.BorderBottom=i.End.y-i.Start.y,s.BorderRight=i.Width/2,s.BorderLeft=-i.Width/2,this.isVisible(s)&&this.drawLineAsVerticalRectangle(i,pe.Cursor)}this.drawingParameters.drawScrollIndicator&&this.drawScrollIndicator();const e=Math.min(this.graphicalMusicSheet.MusicPages.length,this.rules.MaxPageToDrawNumber);for(let i=0;i0&&($o(t.Label.textAlignment)||[vt.CenterBottom].includes(t.Label.textAlignment))){let m=-1,S=!1;for(const b of(a==null?void 0:a.AbstractExpressions)||[])if(b.Label===t?m=(p=b==null?void 0:b.parentMeasure)==null?void 0:p.measureListIndex:(g=b.expression)!=null&&g.TempoInBpm&&(S=b.expression.TempoInBpm>0),S&&m>-1){r.ScreenPosition.y-=4*10;break}}this.rules.DYMusicScoreType==="jianpu"?isNaN(parseInt(t.Label.text,10))&&this.renderLabel(t,e,r):this.renderLabel(t,e,r)}calculateLabel(t){const e=new ta,i=t.Label,s=new le(this);s.AbsolutePosition.x=t.PositionAndShape.AbsolutePosition.x,s.AbsolutePosition.y=t.PositionAndShape.AbsolutePosition.y||t.PositionAndShape.Parent.AbsolutePosition.y,e.ScreenPosition=this.applyScreenTransformation(s.AbsolutePosition),e.FontHeightInPixel=this.calculatePixelDistance(i.fontHeight);const r=this.calculatePixelDistance(t.PositionAndShape.Size.width);switch(e.BitmapWidth=Math.ceil(r),e.BitmapHeight=t.TextLines?Math.ceil(e.FontHeightInPixel*(.2+t.TextLines.length)):10,i.textAlignment){case vt.LeftTop:e.ScreenPosition.x-=e.BitmapWidth/2,e.ScreenPosition.y+=e.BitmapHeight*1.5;break;case vt.LeftCenter:e.ScreenPosition.y-=e.BitmapHeight/2;break;case vt.LeftBottom:e.ScreenPosition.y-=e.BitmapHeight;break;case vt.CenterTop:e.ScreenPosition.x-=e.BitmapWidth/2;break;case vt.CenterCenter:e.ScreenPosition.x-=e.BitmapWidth/2,e.ScreenPosition.y-=e.BitmapHeight/2;break;case vt.CenterBottom:e.ScreenPosition.x-=e.BitmapWidth/2,e.ScreenPosition.y-=e.BitmapHeight;break;case vt.RightTop:e.ScreenPosition.x-=e.BitmapWidth;break;case vt.RightCenter:e.ScreenPosition.x-=e.BitmapWidth,e.ScreenPosition.y-=e.BitmapHeight/2;break;case vt.RightBottom:e.ScreenPosition.x-=e.BitmapWidth,e.ScreenPosition.y-=e.BitmapHeight;break;default:throw new Li("")}return e}applyScreenTransformations(t){const e=[];for(const i of t)e.push(this.applyScreenTransformation(i));return e}drawSplitScreenLine(){}renderRectangle(t,e,i,s=void 0,r=1){throw new Error("not implemented")}drawScrollIndicator(){}drawSelectionStartSymbol(t){}drawSelectionEndSymbol(t){}renderLabel(t,e,i){throw new Error("not implemented")}renderSystemToScreen(t,e,i){}drawSkyLine(t){}drawBottomLine(t){}drawInstrumentBrace(t,e){}drawGroupBracket(t,e){}isVisible(t){return!0}drawMusicSystem(t){const e=this.getSystemAbsBoundingRect(t),i=this.getSytemBoundingBoxInPixels(e);this.drawMusicSystemComponents(t,i,e)}getSytemBoundingBoxInPixels(t){const e=this.applyScreenTransformationForRect(t);return e.x=Math.round(e.x),e.y=Math.round(e.y),e}getSystemAbsBoundingRect(t){const e=t.PositionAndShape.BoundingRectangle;return new Qe(t.PositionAndShape.AbsolutePosition.x+t.PositionAndShape.BorderLeft-1,t.PositionAndShape.AbsolutePosition.y+t.PositionAndShape.BorderTop-1,e.width+6,e.height+2)}drawMusicSystemComponents(t,e,i){const s=this.graphicalMusicSheet.SelectionStartSymbol,r=this.graphicalMusicSheet.SelectionEndSymbol;this.drawingParameters.drawSelectionStartSymbol&&s!==void 0&&this.isVisible(s.PositionAndShape)&&this.drawSelectionStartSymbol(s),this.drawingParameters.drawSelectionEndSymbol&&r!==void 0&&this.isVisible(r.PositionAndShape)&&this.drawSelectionEndSymbol(r);for(const l of t.StaffLines)this.drawStaffLine(l),this.rules.RenderLyrics&&(l.LyricsDashes.length>0&&this.drawDashes(l.LyricsDashes),l.LyricLines.length>0&&this.drawLyricLines(l.LyricLines,l));for(const l of t.SystemLines)this.drawSystemLineObject(l);if(t.Parent===t.Parent.Parent.MusicPages[0])for(const l of t.Labels)l.SVGNode=this.drawLabel(l,pe.Notes);const o=this.graphicalMusicSheet.ParentMusicSheet.Instruments,a=o.filter(l=>l.Visible).length;for(const l of t.InstrumentBrackets)this.drawInstrumentBrace(l,t);if(o.length>0)if(a>1)for(const l of t.GroupBrackets)this.drawGroupBracket(l,t);else for(const l of t.GroupBrackets)l.Visible=!1;if(!this.leadSheet)for(const l of t.MeasureNumberLabels)l.SVGNode=this.drawLabel(l,pe.Notes);for(const l of t.StaffLines)this.drawStaffLineSymbols(l);this.drawingParameters.drawMarkedAreas&&this.drawMarkedAreas(t)}activateSystemRendering(t,e,i,s){return!0}drawSystemLineObject(t){}drawStaffLine(t){for(const e of t.Measures)this.drawMeasure(e);this.rules.RenderLyrics&&t.LyricsDashes.length>0&&this.drawDashes(t.LyricsDashes),this.drawOctaveShifts(t),this.drawPedals(t),this.drawWavyLines(t),this.drawExpressions(t),this.skyLineVisible&&this.drawSkyLine(t),this.bottomLineVisible&&this.drawBottomLine(t)}drawLyricLines(t,e){e.LyricLines.forEach(i=>{i.Start.y+=e.PositionAndShape.AbsolutePosition.y,i.End.y+=e.PositionAndShape.AbsolutePosition.y,i.Start.x+=e.PositionAndShape.AbsolutePosition.x,i.End.x+=e.PositionAndShape.AbsolutePosition.x,this.drawGraphicalLine(i,this.rules.LyricUnderscoreLineWidth)})}drawExpressions(t){}drawGraphicalLine(t,e,i="black"){return this.drawLine(t.Start,t.End,i,e)}drawLine(t,e,i="#FF0000FF",s){}drawDashes(t){t.forEach(e=>e.SVGNode=this.drawLabel(e,pe.Notes))}drawOctaveShifts(t){}drawStaffLines(t){if(t.StaffLines){const e=t.PositionAndShape.AbsolutePosition;for(let i=0;i<5;i++)this.drawLineAsHorizontalRectangleWithOffset(t.StaffLines[i],e,pe.Notes)}}drawSymbol(t,e,i,s=1,r=pe.Notes){}get leadSheet(){return this.graphicalMusicSheet.LeadSheet}set leadSheet(t){this.graphicalMusicSheet.LeadSheet=t}drawPage(t){if(!!this.isVisible(t.PositionAndShape)){for(const e of t.MusicSystems)this.isVisible(e.PositionAndShape)&&this.drawMusicSystem(e);if(t===t.Parent.MusicPages[0])for(const e of t.Labels)e.SVGNode=this.drawLabel(e,pe.Notes);this.drawableBoundingBoxElement&&this.drawBoundingBoxes(t.PositionAndShape,0,this.drawableBoundingBoxElement)}}drawBoundingBoxes(t,e=0,i="all"){const s=t.DataObject.constructor.name;let r=!1;i==="all"&&(r=!0),(r||s===i)&&this.drawBoundingBox(t,void 0,!0,s,e),e++,t.ChildElements.forEach(o=>this.drawBoundingBoxes(o,e,i))}drawBoundingBox(t,e=void 0,i=!1,s=void 0,r=0){let o=new Qe(t.AbsolutePosition.x+t.BorderMarginLeft,t.AbsolutePosition.y+t.BorderMarginTop,t.BorderMarginRight-t.BorderMarginLeft,t.BorderMarginBottom-t.BorderMarginTop);i&&(this.drawLineAsHorizontalRectangle(new ci(new O(t.AbsolutePosition.x-1,t.AbsolutePosition.y),new O(t.AbsolutePosition.x+1,t.AbsolutePosition.y),.1,fs.BaseWritingColor,e),r-1),this.drawLineAsVerticalRectangle(new ci(new O(t.AbsolutePosition.x,t.AbsolutePosition.y-1),new O(t.AbsolutePosition.x,t.AbsolutePosition.y+1),.1,fs.BaseWritingColor,e),r-1)),o=this.applyScreenTransformationForRect(o);const a=this.renderRectangle(o,pe.Background,r,e,.5);if(s){const l=new jt(s),h=new ta;h.BitmapWidth=o.width,h.BitmapHeight=o.height,h.FontHeightInPixel=o.height,h.ScreenPosition=new O(o.x,o.y+12),this.renderLabel(new Se(l,.8,vt.CenterCenter,this.rules),r,h)}return a}drawMarkedAreas(t){for(const e of t.GraphicalMarkedAreas)e&&(e.systemRectangle&&this.drawRectangle(e.systemRectangle,pe.Background),e.settings&&(e.settings.SVGNode=this.drawLabel(e.settings,pe.Comment)),e.labelRectangle&&this.drawRectangle(e.labelRectangle,pe.Background),e.label&&(e.label.SVGNode=this.drawLabel(e.label,pe.Comment)))}drawStaffLineSymbols(t){const e=t.ParentStaff.ParentInstrument,i=t.PositionAndShape.AbsolutePosition.x,s=t.PositionAndShape.AbsolutePosition.y+2,r=t.PositionAndShape.BorderRight;e.highlight&&this.drawingParameters.drawHighlights&&this.drawLineAsHorizontalRectangle(new ci(new O(i,s),new O(i+r,s),4,fs.Highlighted),pe.Highlight);let o=xn.Disabled,a=Ge.PLAY,l=this.drawingParameters.drawActivitySymbols;switch(this.phonicScoreMode){case vn.Midi:a=Ge.PLAY,this.midiPlaybackAvailable&&t.ParentStaff.audible&&(o=xn.PlaybackSymbols);break;case vn.Following:a=Ge.MIC,t.ParentStaff.following&&(o=xn.FollowSymbols);break;default:l=!1;break}if(l){const h=new O(i+r+2,s);this.drawSymbol(a,o,h)}if(this.drawingParameters.drawErrors)for(const h of t.Measures){const c=h.PositionAndShape,u=c.AbsolutePosition.x,f=c.AbsolutePosition.y+2;h.hasError&&this.graphicalMusicSheet.ParentMusicSheet.DrawErroneousMeasures&&this.drawLineAsHorizontalRectangle(new ci(new O(u,f),new O(u+c.BorderRight,f),4,fs.ErrorUnderlay),pe.MeasureError)}}}class Xa{constructor(t){this.fontSize=20,this.fontSizeStandard=this.fontSize;const e=document.createElement("canvas");this.context=e.getContext("2d"),this.rules=t}computeTextWidthToHeightRatio(t,e,i,s=void 0,r=this.fontSize){return this.context.font=Yt.font(r,i,e,this.rules,s),this.context.measureText(t).width/r}setFontSize(t=this.fontSizeStandard){return this.fontSize=t,t}}class sr extends Pe{constructor(t,e,i){super(),this.expression=e,this.parentMeasure=i,this.boundingBox=new le(this,t.PositionAndShape),this.parentStaffLine=t,this.parentStaffLine.AbstractExpressions.push(this),this.rules=t.ParentMusicSystem.rules}get Label(){return this.label}get ParentStaffLine(){return this.parentStaffLine}get SourceExpression(){return this.expression}get Placement(){return this.expression.Placement}}class Tr extends sr{constructor(t,e){super(e.PositionAndShape.Parent.DataObject,t,t.parentMeasure),this.label=e}get GraphicalLabel(){return this.label}updateSkyBottomLine(){}}class Ya extends sr{constructor(t,e,i){super(e,t,i.parentSourceMeasure),this.mInstantaneousDynamicExpression=t,this.mMeasure=i}updateSkyBottomLine(){const t=this.parentStaffLine.SkyBottomLineCalculator,e=this.PositionAndShape.RelativePosition.x+this.PositionAndShape.BorderMarginLeft,i=this.PositionAndShape.RelativePosition.x+this.PositionAndShape.BorderMarginRight;let s=0;switch(this.Placement){case z.Above:s=this.PositionAndShape.RelativePosition.y+this.PositionAndShape.BorderMarginTop,t.updateSkyLineInRange(e,i,s);break;case z.Below:s=this.PositionAndShape.RelativePosition.y+this.PositionAndShape.BorderMarginBottom,t.updateBottomLineInRange(e,i,s);break;default:j.error("Placement for GraphicalInstantaneousDynamicExpression is unknown")}}}class xo extends sr{constructor(t,e,i){super(e,t,i),this.lines=[],this.isSplittedPart=!1,this.notToBeRemoved=!1}get StartMeasure(){return this.startMeasure}set StartMeasure(t){this.startMeasure=t}get EndMeasure(){return this.endMeasure}set EndMeasure(t){this.endMeasure=t}get EndStaffLine(){return this.endMeasure?this.endMeasure.ParentStaffLine:void 0}get IsSplittedPart(){return this.isSplittedPart}set IsSplittedPart(t){this.isSplittedPart=t}get IsVerbal(){return this.ContinuousDynamic.Label&&this.ContinuousDynamic.Label.length>0}get NotToBeRemoved(){return this.notToBeRemoved}set NotToBeRemoved(t){this.notToBeRemoved=t}get Lines(){return this.lines}get ContinuousDynamic(){return this.SourceExpression}updateSkyBottomLine(){var s;const t=this.parentStaffLine.SkyBottomLineCalculator,e=this.IsVerbal?this.label.PositionAndShape.RelativePosition.x+this.label.PositionAndShape.BorderMarginLeft:0,i=this.IsVerbal?this.label.PositionAndShape.RelativePosition.x+this.label.PositionAndShape.BorderMarginRight:0;switch(!this.IsVerbal&&this.lines.length<2&&j.warn("Not enough lines for SkyBottomLine calculation"),this.IsVerbal||this.ContinuousDynamic.DynamicType!==Re.crescendo&&this.ContinuousDynamic.DynamicType!==Re.diminuendo&&j.warn("GraphicalContinuousDynamicExpression.updateSkyBottomLine(): unhandled continuous dynamic type. start measure: "+((s=this.startMeasure)==null?void 0:s.MeasureNumber)),this.Placement){case z.Above:if(!this.IsVerbal)this.ContinuousDynamic.DynamicType===Re.crescendo?t.updateSkyLineWithWedge(this.lines[0].Start,this.lines[0].End):this.ContinuousDynamic.DynamicType===Re.diminuendo&&t.updateSkyLineWithWedge(this.lines[0].End,this.lines[0].Start);else{const r=this.label.PositionAndShape.BorderMarginTop+this.label.PositionAndShape.RelativePosition.y;t.updateSkyLineInRange(e,i,r)}break;case z.Below:if(!this.IsVerbal)this.ContinuousDynamic.DynamicType===Re.crescendo?t.updateBottomLineWithWedge(this.lines[1].Start,this.lines[1].End):this.ContinuousDynamic.DynamicType===Re.diminuendo&&t.updateBottomLineWithWedge(this.lines[1].End,this.lines[1].Start);else{const r=this.label.PositionAndShape.BorderMarginBottom+this.label.PositionAndShape.RelativePosition.y;t.updateBottomLineInRange(e,i,r)}break;default:j.error("Placement for GraphicalContinuousDynamicExpression is unknown")}}createCrescendoLines(t,e,i,s=this.rules.WedgeOpeningLength,r=this.rules.WedgeLineWidth){const o=new O(t,i),a=new O(e,i-s/2),l=new O(e,i+s/2);this.addWedgeLines(o,a,l,r)}createFirstHalfCrescendoLines(t,e,i,s=this.rules.WedgeMeasureEndOpeningLength,r=this.rules.WedgeLineWidth){const o=new O(t,i),a=new O(e,i-s/2),l=new O(e,i+s/2);this.addWedgeLines(o,a,l,r)}createSecondHalfCrescendoLines(t,e,i,s=this.rules.WedgeMeasureBeginOpeningLength,r=this.rules.WedgeOpeningLength,o=this.rules.WedgeLineWidth){const a=new O(t,i-s/2),l=new O(t,i+s/2),h=new O(e,i-r/2),c=new O(e,i+r/2);this.addDoubleLines(a,h,l,c,o)}recalculateCrescendoLines(t,e,i){const s=Math.abs(this.lines[0].Start.y-this.lines[1].Start.y)>1e-4;this.lines.clear(),s?this.createSecondHalfCrescendoLines(t,e,i):this.isSplittedPart?this.createFirstHalfCrescendoLines(t,e,i):this.createCrescendoLines(t,e,i)}createDiminuendoLines(t,e,i,s=this.rules.WedgeOpeningLength,r=this.rules.WedgeLineWidth){const o=new O(t,i-s/2),a=new O(t,i+s/2),l=new O(e,i);this.addWedgeLines(l,o,a,r)}createFirstHalfDiminuendoLines(t,e,i,s=this.rules.WedgeOpeningLength,r=this.rules.WedgeMeasureEndOpeningLength,o=this.rules.WedgeLineWidth){const a=new O(t,i-s/2),l=new O(t,i+s/2),h=new O(e,i-r/2),c=new O(e,i+r/2);this.addDoubleLines(a,h,l,c,o)}createSecondHalfDiminuendoLines(t,e,i,s=this.rules.WedgeMeasureBeginOpeningLength,r=this.rules.WedgeLineWidth){const o=new O(t,i-s/2),a=new O(t,i+s/2),l=new O(e,i);this.addWedgeLines(l,o,a,r)}recalculateDiminuendoLines(t,e,i){const s=Math.abs(this.lines[0].End.y-this.lines[1].End.y)>1e-4;this.lines.clear(),s?this.createFirstHalfDiminuendoLines(t,e,i):this.isSplittedPart?this.createSecondHalfDiminuendoLines(t,e,i):this.createDiminuendoLines(t,e,i)}calcPsi(){if(this.IsVerbal){this.PositionAndShape.calculateBoundingBox();return}this.PositionAndShape.RelativePosition=this.lines[0].Start,this.PositionAndShape.BorderMarginTop=this.lines[0].End.y-this.lines[0].Start.y,this.PositionAndShape.BorderMarginBottom=this.lines[1].End.y-this.lines[1].Start.y,this.PositionAndShape.Center.y=(this.PositionAndShape.BorderMarginTop+this.PositionAndShape.BorderMarginBottom)/2,this.ContinuousDynamic.DynamicType===Re.crescendo?(this.PositionAndShape.BorderMarginLeft=0,this.PositionAndShape.BorderMarginRight=this.lines[0].End.x-this.lines[0].Start.x):(this.PositionAndShape.BorderMarginLeft=this.lines[0].End.x-this.lines[0].Start.x,this.PositionAndShape.BorderMarginRight=0)}cleanUp(){this.lines.clear()}shiftYPosition(t){this.IsVerbal?(this.PositionAndShape.RelativePosition.y+=t,this.PositionAndShape.calculateBoundingBox()):(this.lines[0].Start.y+=t,this.lines[0].End.y+=t,this.lines[1].End.y+=t)}squeeze(t){this.IsVerbal||Math.abs(this.lines[0].End.x-this.lines[0].Start.x)0?this.lines[0].Start.x+=t:(this.lines[0].End.x+=t,this.lines[1].End.x+=t):t<0?this.lines[0].Start.x+=t:(this.lines[0].End.x+=t,this.lines[1].End.x+=t),this.calcPsi())}addWedgeLines(t,e,i,s){const r=new ci(t,e,s),o=new ci(t,i,s);this.lines.push(r),this.lines.push(o)}addDoubleLines(t,e,i,s,r){const o=new ci(t,e,r),a=new ci(i,s,r);this.lines.push(o),this.lines.push(a)}}class Us extends sr{constructor(t,e,i,s,r=void 0){super(t,new Ii(i),s),this.label=e,this.sourceMultiExpression=r}updateSkyBottomLine(){const t=this.parentStaffLine.SkyBottomLineCalculator,e=this.label.PositionAndShape.RelativePosition.x+this.label.PositionAndShape.BorderMarginLeft,i=this.label.PositionAndShape.RelativePosition.x+this.label.PositionAndShape.BorderMarginRight;switch(this.Placement){case z.Above:const s=this.label.PositionAndShape.BorderMarginTop+this.label.PositionAndShape.RelativePosition.y;t.updateSkyLineInRange(e,i,s);break;case z.Below:const r=this.label.PositionAndShape.BorderMarginBottom+this.label.PositionAndShape.RelativePosition.y;t.updateBottomLineInRange(e,i,r);break;default:j.error("Placement for GraphicalUnknownExpression is unknown")}}}const _t=10;class su extends iu{constructor(t=new Ja){super(new Xa(t.Rules),t),this.backends=[],this.zoom=1,this.pageIdx=0,this.getDotId=(e,i)=>i?String(e.Label.PositionAndShape.RelativePosition[i]):String(e.Label.PositionAndShape.RelativePosition.x)+String(e.Label.PositionAndShape.RelativePosition.y),this.hasDot=(e,i,s,r)=>{const o=i||Object.values(r);for(const a of o){if(s)return e.x===a.x&&e.y===a.y;if(e.x===a.x)return!0}return!1}}get Zoom(){return this.zoom}get Backends(){return this.backends}initializeBackendForPage(t){this.backend=this.backends[t.PageNumber-1]}drawSheet(t){var e,i,s;this.rules.DefaultVexFlowNoteFont==="gonville"&&(M.Flow.DEFAULT_FONT_STACK=[(e=M.Flow.Fonts)==null?void 0:e.Gonville,(i=M.Flow.Fonts)==null?void 0:i.Bravura,(s=M.Flow.Fonts)==null?void 0:s.Custom]),M.Flow.STAVE_LINE_THICKNESS=this.rules.StaffLineWidth*_t,M.Flow.STEM_WIDTH=this.rules.StemWidth*_t,M.Flow.DEFAULT_NOTATION_FONT_SCALE=this.rules.VexFlowDefaultNotationFontScale,M.Flow.DEFAULT_TAB_FONT_SCALE=this.rules.VexFlowDefaultTabFontScale,this.pageIdx=0;for(const r of t.MusicPages){if(r.PageNumber>this.rules.MaxPageToDrawNumber)break;const o=this.backends[this.pageIdx];o.graphicalMusicPage=r,o.scale(this.zoom),this.pageIdx+=1}this.pageIdx=0,this.backend=this.backends[0],super.drawSheet(t)}drawPage(t){!t||(this.backend=this.backends[t.PageNumber-1],super.drawPage(t),this.pageIdx+=1)}clear(){for(const t of this.backends)t.clear()}setZoom(t){this.zoom=t}calculatePixelDistance(t){return t*_t}drawStaffLine(t){const e=this.backend.getContext().openGroup();e&&e.classList.add("staffline"),super.drawStaffLine(t);const i=t.PositionAndShape.AbsolutePosition;this.rules.RenderSlurs&&this.drawSlurs(t,i),this.backend.getContext().closeGroup()}drawSlurs(t,e){for(const i of t.GraphicalSlurs)i.slur.isCrossed()||this.drawSlur(i,e)}drawSlur(t,e){const i=[];let s,r,o,a;this.rules.DYMusicScoreType==="jianpu"?((t.placement>0||t.bezierStartPt.y>0)&&(t.bezierStartPt.y=-.8,t.bezierStartControlPt.y=-2.5),s=new O(t.bezierStartPt.x+e.x,t.bezierStartPt.y+e.y),r=new O(t.bezierStartControlPt.x+e.x,t.bezierStartControlPt.y+e.y),o=new O(t.bezierEndControlPt.x+e.x,t.bezierStartControlPt.y+e.y),a=new O(t.bezierEndPt.x+e.x,t.bezierStartPt.y+e.y)):(s=new O(t.bezierStartPt.x+e.x,t.bezierStartPt.y+e.y),r=new O(t.bezierStartControlPt.x+e.x,t.bezierStartControlPt.y+e.y),o=new O(t.bezierEndControlPt.x+e.x,t.bezierEndControlPt.y+e.y),a=new O(t.bezierEndPt.x+e.x,t.bezierEndPt.y+e.y)),i.push(this.applyScreenTransformation(s)),i.push(this.applyScreenTransformation(r)),i.push(this.applyScreenTransformation(o)),i.push(this.applyScreenTransformation(a)),t.placement===z.Above?(s.y-=.05,r.y-=.3,o.y-=.3,a.y-=.05):(s.y+=.05,r.y+=.3,o.y+=.3,a.y+=.05),i.push(this.applyScreenTransformation(s)),i.push(this.applyScreenTransformation(r)),i.push(this.applyScreenTransformation(o)),i.push(this.applyScreenTransformation(a)),t.SVGElement=this.backend.renderCurve(i)}drawMeasure(t){t.setAbsoluteCoordinates(t.PositionAndShape.AbsolutePosition.x*_t,t.PositionAndShape.AbsolutePosition.y*_t);const e=this.backend.getContext();try{t.draw(e)}catch(i){j.warn("VexFlowMusicSheetDrawer.drawMeasure",i)}for(const i of t.staffEntries)this.drawStaffEntry(i)}drawLine(t,e,i="#FF0000FF",s=.2){return t=this.applyScreenTransformation(t),e=this.applyScreenTransformation(e),this.backend.renderLine(t,e,i,s*_t)}DrawOverlayLine(t,e,i,s="#FF0000FF",r=.2){if(!i.PageNumber||i.PageNumber>this.backends.length||i.PageNumber<1){console.log("VexFlowMusicSheetDrawer.drawOverlayLine: invalid page number / music page number doesn't correspond to an existing backend.");return}const o=i.PageNumber-1,a=this.backends[o];return t=this.applyScreenTransformation(t),e=this.applyScreenTransformation(e),a.renderLine(t,e,s,r*_t)}drawSkyLine(t){const e=t.PositionAndShape.AbsolutePosition,i=t.PositionAndShape.Size.width;this.drawSampledLine(t.SkyLine,e,i)}drawBottomLine(t){const e=new O(t.PositionAndShape.AbsolutePosition.x,t.PositionAndShape.AbsolutePosition.y),i=t.PositionAndShape.Size.width;this.drawSampledLine(t.BottomLine,e,i,"#0000FFFF")}drawSampledLine(t,e,i,s="#FF0000FF"){const r=[];let o=0;for(let l=0;l0){const l=this.rules.SamplingUnit;let h=new O(a.x,a.y),c=new O(r[0]/l+a.x,a.y);this.drawLine(h,c,s);let u,f;t[0]>=0&&(u=new O(r[0]/l+a.x,a.y),f=new O(r[0]/l+a.x,a.y+t[r[0]]),this.drawLine(u,f,s));for(let d=1;d0)for(const e of t.FingeringEntries)e.SVGNode=this.drawLabel(e,pe.Notes);if(t.graphicalChordContainers!==void 0&&t.graphicalChordContainers.length>0)for(const e of t.graphicalChordContainers){const i=e.GraphicalLabel;i.SVGNode=this.drawLabel(i,pe.Notes)}this.rules.RenderLyrics&&t.LyricsEntries.length>0&&this.drawLyrics(t.LyricsEntries,pe.Notes)}drawLyrics(t,e){t.forEach(i=>{const s=i.GraphicalLabel;s.SVGNode=this.drawLabel(s,e)})}drawInstrumentBrace(t,e){t.draw(this.backend.getContext())}drawGroupBracket(t,e){t.draw(this.backend.getContext())}drawOctaveShifts(t){for(const e of t.OctaveShifts)if(e){const i=e,s=this.backend.getContext(),r=i.getTextBracket();r.setContext(s);try{r.draw()}catch(o){j.warn(o)}}}drawPedals(t){for(const e of t.Pedals)if(e){const i=e,s=this.backend.getContext(),r=i.getPedalMarking();r.setContext(s),r.draw()}}drawWavyLines(t){for(const e of t.WavyLines)if(e){const i=e,s=this.backend.getContext(),r=i.getVibratoBracket();r.setContext(s),r.draw()}}getMaxExpressionsYAndDots(t){var l,h;const e=[];let i=0;for(const c of t.measures)e.push(c.measureNumber);const s={},r={},o={};for(const c of t.AbstractExpressions)if(c instanceof Us&&e.includes(c.parentMeasure.MeasureNumber)){const u=this.getDotId(c),f=this.getDotId(c,"x");r[u]||(r[u]=[]),o[f]||(o[f]=[]),this.hasDot(c.Label.PositionAndShape.RelativePosition,r[u],!0)||(r[u].push(c.Label.PositionAndShape.RelativePosition),o[f].push(c.Label.PositionAndShape.RelativePosition)),s[u]=c.Label.PositionAndShape.RelativePosition}let a=0;for(const c of t.AbstractExpressions){const u=(l=c.parentMeasure)==null?void 0:l.MeasureNumber;if(c instanceof Us&&e.includes(u)){const f=(h=c.parentMeasure.verticalMeasureList[0])==null?void 0:h.stave,d=(f==null?void 0:f.end_x)-(f==null?void 0:f.x),p=this.getDotId(c,"x");if((o[p]||[]).length===1&&a!==u){const g=c.Label.PositionAndShape.AbsolutePosition.y;i=i===0?g:Math.min(i,g)}(o[p]||[]).length!==1&&d/101){let i=Math.min(...t.Lines.map(s=>s.Start.x));t.Lines[0].Start.x=i,t.Lines[1].Start.x=i,[t.Lines[0].Start.y,t.Lines[1].Start.y]=[t.Lines[1].Start.y,t.Lines[0].Start.y],t.Lines[0].End.y+=this.rules.WedgeOpeningLength/2,t.Lines[1].End.y+=this.rules.WedgeOpeningLength}}catch{}const e=this.backend.getContext();e.openGroup("lineGroup");for(const i of t.Lines){const s=new O(t.ParentStaffLine.PositionAndShape.AbsolutePosition.x+i.Start.x,t.ParentStaffLine.PositionAndShape.AbsolutePosition.y+i.Start.y),r=new O(t.ParentStaffLine.PositionAndShape.AbsolutePosition.x+i.End.x,t.ParentStaffLine.PositionAndShape.AbsolutePosition.y+i.End.y);this.drawLine(s,r,"black",i.Width)}e.closeGroup()}}renderLabel(t,e,i){return this._renderLabel(t,i)}_renderLabel(t,e){var h;if(!t.Label.print)return;const i=t.Label.fontHeight*_t,{font:s}=t.Label;let r;this.rules.ColoringEnabled&&(r=t.Label.colorDefault,t.Label.color&&(r=t.Label.color.toString()),r||(r=this.rules.DefaultColorLabel));let{fontStyle:o,fontFamily:a}=t.Label;o||(o=this.rules.DefaultFontStyle),a||(a=this.rules.DefaultFontFamily);let l;for(let c=0;c<((h=t.TextLines)==null?void 0:h.length);c++){const u=t.TextLines[c],f=this.calculatePixelDistance(u.xOffset),d=new O(e.ScreenPosition.x+f,e.ScreenPosition.y),p=this.backend.renderText(i,o,s,u.text,e.FontHeightInPixel,d,r,t.Label.fontFamily);l?l.appendChild(p):l=p,e.ScreenPosition.y=e.ScreenPosition.y+e.FontHeightInPixel,t.TextLines.length>1&&(e.ScreenPosition.y+=this.rules.SpacingBetweenTextLines)}return l}renderRectangle(t,e,i,s,r){return this.backend.renderRectangle(t,i,s,r)}applyScreenTransformation(t){return new O(t.x*_t,t.y*_t)}applyScreenTransformationForRect(t){return new Qe(t.x*_t,t.y*_t,t.width*_t,t.height*_t)}}const ht=M.Flow,ze=class{static durations(n,t){const e=[],i=n.clone();for(;i.RealValue>0;){const s=i.RealValue;if(s>=2)e.push("1/2"),i.Sub(new W(2,1));else if(s>=1)e.push("w"),i.Sub(new W(1,1));else if(s<1&&s>=.5){if(t&&s>.5)return["w"];e.push("h"),i.Sub(new W(1,2))}else if(s<.5&&s>=.25){if(t&&s>.25)return["h"];e.push("q"),i.Sub(new W(1,4))}else if(s<.25&&s>=.125){if(t&&s>.125)return["q"];e.push("8"),i.Sub(new W(1,8))}else if(s<.125&&s>=.0625){if(t&&s>.0625)return["8"];e.push("16"),i.Sub(new W(1,16))}else if(s<.0625&&s>=.03125){if(t&&s>.03125)return["16"];e.push("32"),i.Sub(new W(1,32))}else if(s<.03125&&s>=.015625){if(t&&s>.015625)return["32"];e.push("64"),i.Sub(new W(1,64))}else{if(t)return["64"];e.push("128"),i.Sub(new W(1,128))}}return e}static pitch(n,t,e,i=void 0,s=void 0){let r=s;s===void 0&&(r=3),t&&s===void 0&&(r=0,e.ClefType===Pt.F&&(r=2),e.ClefType===Pt.C&&(r=2));const o=ut[n.FundamentalNote].toLowerCase(),a=Kt.accidentalVexflow(n.Accidental),l=n.Octave-e.OctaveOffset+r;let h="";return i&&(h=this.NoteHeadCode(i)),[o+"n/"+l+h,a,e]}static restToNotePitch(n,t){let e=n.Octave;switch(t){case Pt.C:case Pt.F:{e+=2;break}case Pt.G:}return new Kt(n.FundamentalNote,e,yt.NONE)}static NoteHeadCode(n){const t="/",e=n.Filled?"2":"1";switch(n.Shape){case Qt.NORMAL:return"";case Qt.DIAMOND:return t+"D"+e;case Qt.TRIANGLE:return t+"T"+e;case Qt.X:return t+"X"+e;case Qt.CIRCLEX:return t+"X3";case Qt.RECTANGLE:return t+"R"+e;case Qt.SQUARE:return t+"S"+e;case Qt.SLASH:return"";default:return""}}static GhostNotes(n){const t=[],e=ze.durations(n,!1);for(const i of e)t.push(new ht.GhostNote({duration:i}));return t}static StaveNote(n){var w,T,E,C,P,I,F,L,k,v,G,et,H,nt,K,lt;n.sortForVexflow();const t=n.notes,e=n.parentStaffEntry.parentMeasure.parentSourceMeasure.Rules,i=t[0];let s=[],r;const o=[],a=i.graphicalNoteLength,l=i.sourceNote.NoteTuplet!==void 0;let h=ze.durations(a,l)[0];i.sourceNote.TypeLength!==void 0&&i.sourceNote.TypeLength!==a&&i.sourceNote.TypeLength.RealValue!==0&&(h=ze.durations(i.sourceNote.TypeLength,l)[0],i.numberOfDots=i.sourceNote.DotsXml);let c,u=i.numberOfDots,f=!1,d=0,p=!1,g=!1,m;for(const A of t){if(u=1&&ct.length-1>=dt+1&&(Nt=(P=(C=ct[dt-1])==null?void 0:C.graphicalVoiceEntries[0])==null?void 0:P.parentVoiceEntry,pt=(F=(I=ct[dt+1])==null?void 0:I.graphicalVoiceEntries[0])==null?void 0:F.parentVoiceEntry,Nt&&pt)){const Ct=Nt.Notes[0],Ht=pt.Notes[0];if(((L=Ct.NoteBeam)==null?void 0:L.Notes.includes(Ht))&&Ht.ParentStaffEntry.ParentStaff.StafflineCount!==1){const me=Nt.Notes.last().Pitch,ce=A.Clef(),_=ze.pitch(ze.restToNotePitch(me.getTransposedPitch(-2),ce.ClefType),!1,ce);me.FundamentalNote===4&&(s=[_[0]])}}}}if(a.RealValue===A.sourceNote.SourceMeasure.ActiveTimeSignature.RealValue&&(s=e.DYMusicScoreType==="staff"?["d/5"]:["R/5"],h="w",u=0,f=!0,d=e.WholeRestXShiftVexflow*_t),[...A.sourceNote.ParentStaff.Voices].filter(J=>(J==null?void 0:J.VoiceId)!=1).length){const J=A.parentVoiceEntry.parentStaffEntry.graphicalVoiceEntries,ct=A.parentVoiceEntry.parentVoiceEntry.ParentVoice.VoiceId;let Nt,pt;for(const dt of J)for(const Ct of dt.notes){if(Ct===A||Ct.sourceNote.isRest()||!Ct.sourceNote.PrintObject){A.lineShift=-2;continue}const Ht=Ct.parentVoiceEntry.parentVoiceEntry.WantedStemDirection,me=ct===1||ct===5,ce=me?1:-1,Z=Ct.sourceNote.Pitch.getHalfTone(),Y=ce===1&&Z>Nt,N=ce===-1&&Z0){let dt=3;const Ct=A.Clef();switch(Ct.ClefType){case Pt.F:dt=5;break;case Pt.C:dt=4;break}m=Kt.fromHalftone(Nt),s=[ze.pitch(m,!0,Ct,void 0,dt)[0]]}}break}A.sourceNote.Notehead&&A.sourceNote.Notehead.Shape===Qt.SLASH&&(p=!0);const B=A.vfpitch;if((v=(k=B[2])==null?void 0:k.Parent)!=null&&v.Instructions)for(let ot=0,rt=B[2].Parent.Instructions.length;otn.notes[B].staffLine=A),(e.LedgerLineWidth||e.LedgerLineStrokeStyle)&&(S.ledgerLineStyle||(S.ledgerLineStyle={}),e.LedgerLineWidth&&(S.ledgerLineStyle.lineWidth=e.LedgerLineWidth),e.LedgerLineStrokeStyle&&(S.ledgerLineStyle.strokeStyle=e.LedgerLineStrokeStyle)),e.ColoringEnabled){const A=e.DefaultColorStem;let B=n.parentVoiceEntry.StemColor;!B&&A&&(B=A);const ot={fillStyle:B,strokeStyle:B};B&&(S.setStemStyle(ot),S.flag&&e.ColorFlags&&S.setFlagStyle(ot))}if(S.x_shift=d,n.parentVoiceEntry.IsGrace&&n.notes[0].sourceNote.NoteBeam&&(n.parentVoiceEntry.WantedStemDirection=n.notes[0].sourceNote.NoteBeam.Notes[0].ParentVoiceEntry.WantedStemDirection),n.parentVoiceEntry)switch(n.parentVoiceEntry.WantedStemDirection){case Ft.Up:S.setStemDirection(ht.Stem.UP),n.parentVoiceEntry.StemDirection=Ft.Up;break;case Ft.Down:S.setStemDirection(ht.Stem.DOWN),n.parentVoiceEntry.StemDirection=Ft.Down;break}for(let A=0,B=t.length;A0&&rt==="single"){const J=new ht.Tremolo(ot);J.extra_stroke_scale=e.TremoloStrokeScale,J.y_spacing_scale=e.TremoloYSpacingScale,S&&S.duration==="w"&&S.stem.setExtension(-9),S.addModifier(A,J)}if(ot>0&&rt==="start"&&this.noteTremoloList.push(S),ot>0&&rt==="stop"){this.noteTremoloList.push(S);const J=new ht.Tremolo(ot,[...this.noteTremoloList]);J.extra_stroke_scale=1.2,J.y_spacing_scale=1.2,J.x_shift=-30,S.addModifier(A,J),this.noteTremoloList=[]}this.glissandoList.length&&(S.setVibrato(this.glissandoList[0].vfnote[0]),((H=(et=(G=this.glissandoList[0])==null?void 0:G.sourceNote)==null?void 0:et.SourceMeasure)==null?void 0:H.MeasureNumberXML)!=((lt=(K=(nt=t[A])==null?void 0:nt.sourceNote)==null?void 0:K.SourceMeasure)==null?void 0:lt.MeasureNumberXML),this.glissandoList=[]),t[A].sourceNote.glissandoType==="start"&&this.glissandoList.push(t[A])}if(y.Length.RealValue===.25&&y.Notehead&&y.Notehead.Filled===!1){const A=S.getKeyProps();for(let B=0;B1&&S.getKeyProps().filter(B=>!B.code&&B.line>3).length===s.length&&S.setStemDirection(-1),e.DYMusicScoreType==="jianpu"&&window&&window.sett&&window.sett.keySignature&&S.addAccidental(0,new ht.Accidental("#"));try{const A=["b","#","\xA7","\xBA","X"],B={b:"b","#":"#","\xA7":"n",\u00BA:"bb",X:"##"};for(const ot of t){const rt=ot.sourceNote.voiceEntry.Timestamp;for(const J of ot.sourceNote.SourceMeasure.StaffLinkedExpressions)for(const ct of J){const Nt=W.Equal(rt,ct.Timestamp),dt=ct.EntriesList.map(Ct=>Ct.label).filter(Ct=>A.includes(Ct)).map(Ct=>B[Ct]);if(Nt){for(const Ct of dt)Ct&&S.addAnnotation(0,new ht.Annotation(Ct));break}}}}catch{}return S}static generateArticulations(n,t,e){var i,s;if(!(!n||n.getAttribute("type")==="GhostNote"))for(const r of t){let o=ht.Modifier.Position.ABOVE;n.getStemDirection()===ht.Stem.UP&&(o=ht.Modifier.Position.BELOW);let a;const l=r.articulationEnum;switch(e.ArticulationPlacementFromXML&&(r.placement===z.Above?o=ht.Modifier.Position.ABOVE:r.placement===z.Below&&(o=ht.Modifier.Position.BELOW)),l){case wt.accent:{a=new ht.Articulation("a>");break}case wt.downbow:{a=new ht.Articulation("am"),r.placement===void 0&&(o=ht.Modifier.Position.ABOVE);break}case wt.fermata:{a=new ht.Articulation("a@a"),o=ht.Modifier.Position.ABOVE;break}case wt.marcatodown:{a=new ht.Articulation("a|");break}case wt.marcatoup:{a=new ht.Articulation("a^");break}case wt.invertedfermata:{a=new ht.Articulation("a@u"),o=ht.Modifier.Position.BELOW;break}case wt.lefthandpizzicato:{a=new ht.Articulation("a+");break}case wt.naturalharmonic:{a=new ht.Articulation("ah");break}case wt.snappizzicato:{a=new ht.Articulation("ao");break}case wt.staccatissimo:{a=new ht.Articulation("av");break}case wt.staccato:{a=new ht.Articulation("a.");break}case wt.tenuto:{a=new ht.Articulation("a-");break}case wt.upbow:{a=new ht.Articulation("a|"),r.placement===void 0&&(o=ht.Modifier.Position.ABOVE);break}case wt.strongaccent:{a=new ht.Articulation("a^");break}}a&&(!n.hasStem()&&!n.isRest()&&l==wt.accent&&n.getLineNumber()>=3&&(o=ht.Modifier.Position.ABOVE,(s=(i=n==null?void 0:n.modifiers)==null?void 0:i.filter(h=>["TREMOLO"].includes(h.getCategory().toLocaleUpperCase())))!=null&&s.length&&a.setYShift(-16)),l===wt.strongaccent&&(o=ht.Modifier.Position.ABOVE),a.setPosition(o),n.addModifier(0,a))}}static generateOrnaments(n,t){let e=ht.Modifier.Position.ABOVE;t.placement===z.Below&&(e=ht.Modifier.Position.BELOW);let i;switch(t.GetOrnament){case Ne.DelayedInvertedTurn:{i=new ht.Ornament("turn_inverted"),i.setDelayed(!0);break}case Ne.DelayedTurn:{i=new ht.Ornament("turn"),i.setDelayed(!0);break}case Ne.InvertedMordent:{i=new ht.Ornament("mordent"),i.setDelayed(!1);break}case Ne.InvertedTurn:{i=new ht.Ornament("turn_inverted"),i.setDelayed(!1);break}case Ne.Mordent:{i=new ht.Ornament("mordent_inverted"),i.setDelayed(!1);break}case Ne.Trill:{i=new ht.Ornament("tr"),i.setDelayed(!1);break}case Ne.Turn:{i=new ht.Ornament("turn"),i.setDelayed(!1);break}default:{j.warn("unhandled OrnamentEnum type: "+t.GetOrnament);return}}i&&(t.AccidentalBelow!==yt.NONE&&i.setLowerAccidental(Kt.accidentalVexflow(t.AccidentalBelow)),t.AccidentalAbove!==yt.NONE&&i.setUpperAccidental(Kt.accidentalVexflow(t.AccidentalAbove)),i.setPosition(e),n.addModifier(0,i))}static StrokeTypeFromArpeggioType(n){switch(n){case Xe.ARPEGGIO_DIRECTIONLESS:return ht.Stroke.Type.ARPEGGIO_DIRECTIONLESS;case Xe.BRUSH_DOWN:return ht.Stroke.Type.BRUSH_UP;case Xe.BRUSH_UP:return ht.Stroke.Type.BRUSH_DOWN;case Xe.RASQUEDO_DOWN:return ht.Stroke.Type.RASQUEDO_UP;case Xe.RASQUEDO_UP:return ht.Stroke.Type.RASQUEDO_DOWN;case Xe.ROLL_DOWN:return ht.Stroke.Type.ROLL_UP;case Xe.ROLL_UP:return ht.Stroke.Type.ROLL_DOWN;default:return ht.Stroke.Type.ARPEGGIO_DIRECTIONLESS}}static CreateTabNote(n){const t=[],e=n.notes.reverse(),i=[],s=n.notes[0].graphicalNoteLength,r=n.notes[0].sourceNote.NoteTuplet!==void 0;let o=ze.durations(s,r)[0],a=0;for(const h of n.notes){const c=h.sourceNote,u={str:c.StringNumberTab,fret:c.FretNumber};t.push(u),c.BendArray&&c.BendArray.forEach(function(f){let d;const p=f.bendalter-u.fret;p>1?d="Full":p===1?d="1/2":d="1/4",f.direction==="up"?i.push({type:ht.Bend.UP,text:d,width:10}):i.push({type:ht.Bend.DOWN,text:d,width:10})}),a(n[n.VA8=0]="VA8",n[n.VB8=1]="VB8",n[n.MA15=2]="MA15",n[n.MB15=3]="MB15",n[n.NONE=4]="NONE",n))(oe||{});class nr extends Ii{constructor(t,e,i,s){super(e),this.label=t,this.staffNumber=i,this.parentMultiTempoExpression=s}get Label(){return this.label}set Label(t){this.label=t}get Placement(){return this.placement}set Placement(t){this.placement=t}get StaffNumber(){return this.staffNumber}set StaffNumber(t){this.staffNumber=t}get ParentMultiTempoExpression(){return this.parentMultiTempoExpression}static isStringInStringList(t,e){for(const i of t)if(nr.stringContainsSeparatedWord(e.toLowerCase().trim(),i.toLowerCase().trim()))return!0;return!1}static stringContainsSeparatedWord(t,e){return t===e||t.indexOf(" "+e)!==-1||t.indexOf(e+" ")!==-1}}const tt=class extends nr{constructor(n,t,e,i,s,r=!1){super(n,t,e,s),this.setTempoAndTempoType(i)}static getDefaultValueForTempoType(n){switch(n){case bt.larghissimo:return 20;case bt.grave:return 30;case bt.lento:return 48;case bt.largo:return 52;case bt.larghetto:return 63;case bt.adagio:return 70;case bt.adagietto:return 75;case bt.andanteModerato:return 88;case bt.andante:return 92;case bt.andantino:return 96;case bt.moderato:return 106;case bt.allegretto:return 112;case bt.allegroModerato:return 118;case bt.allegro:return 130;case bt.vivace:return 140;case bt.vivacissimo:return 155;case bt.allegrissimo:return 170;case bt.presto:return 184;case bt.prestissimo:return 200;default:throw new Li("tempoEnum")}}static isInputStringInstantaneousTempo(n){return n?tt.isStringInStringList(tt.listInstantaneousTempoLarghissimo,n)||tt.isStringInStringList(tt.listInstantaneousTempoGrave,n)||tt.isStringInStringList(tt.listInstantaneousTempoLento,n)||tt.isStringInStringList(tt.listInstantaneousTempoLargo,n)||tt.isStringInStringList(tt.listInstantaneousTempoLarghetto,n)||tt.isStringInStringList(tt.listInstantaneousTempoAdagio,n)||tt.isStringInStringList(tt.listInstantaneousTempoAdagietto,n)||tt.isStringInStringList(tt.listInstantaneousTempoAndanteModerato,n)||tt.isStringInStringList(tt.listInstantaneousTempoAndante,n)||tt.isStringInStringList(tt.listInstantaneousTempoAndantino,n)||tt.isStringInStringList(tt.listInstantaneousTempoModerato,n)||tt.isStringInStringList(tt.listInstantaneousTempoAllegretto,n)||tt.isStringInStringList(tt.listInstantaneousTempoAllegroModerato,n)||tt.isStringInStringList(tt.listInstantaneousTempoAllegro,n)||tt.isStringInStringList(tt.listInstantaneousTempoVivace,n)||tt.isStringInStringList(tt.listInstantaneousTempoVivacissimo,n)||tt.isStringInStringList(tt.listInstantaneousTempoAllegrissimo,n)||tt.isStringInStringList(tt.listInstantaneousTempoPresto,n)||tt.isStringInStringList(tt.listInstantaneousTempoPrestissimo,n)||tt.isStringInStringList(tt.listInstantaneousTempoChangesGeneral,n):!1}get Label(){return this.label}set Label(n){this.label=n}get Placement(){return this.placement}set Placement(n){this.placement=n}get StaffNumber(){return this.staffNumber}set StaffNumber(n){this.staffNumber=n}get Enum(){return this.tempoEnum}get TempoInBpm(){return this.tempoInBpm}set TempoInBpm(n){this.tempoInBpm=n}get ParentMultiTempoExpression(){return this.parentMultiTempoExpression}getAbsoluteTimestamp(){return W.plus(this.ParentMultiTempoExpression.SourceMeasureParent.AbsoluteTimestamp,this.ParentMultiTempoExpression.Timestamp)}getAbsoluteFloatTimestamp(){return W.plus(this.ParentMultiTempoExpression.SourceMeasureParent.AbsoluteTimestamp,this.ParentMultiTempoExpression.Timestamp).RealValue}setTempoAndTempoType(n){if(!this.label){this.tempoInBpm=n,this.tempoEnum=bt.metronomeMark;return}if(tt.isStringInStringList(tt.listInstantaneousTempoLarghissimo,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.larghissimo)),this.tempoInBpm=n,this.tempoEnum=bt.larghissimo;return}if(tt.isStringInStringList(tt.listInstantaneousTempoGrave,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.grave)),this.tempoInBpm=n,this.tempoEnum=bt.grave;return}if(tt.isStringInStringList(tt.listInstantaneousTempoLento,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.lento)),this.tempoInBpm=n,this.tempoEnum=bt.lento;return}if(tt.isStringInStringList(tt.listInstantaneousTempoLargo,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.largo)),this.tempoInBpm=n,this.tempoEnum=bt.largo;return}if(tt.isStringInStringList(tt.listInstantaneousTempoLarghetto,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.larghetto)),this.tempoInBpm=n,this.tempoEnum=bt.larghetto;return}if(tt.isStringInStringList(tt.listInstantaneousTempoAdagio,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.adagio)),this.tempoInBpm=n,this.tempoEnum=bt.adagio;return}if(tt.isStringInStringList(tt.listInstantaneousTempoAdagietto,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.adagietto)),this.tempoInBpm=n,this.tempoEnum=bt.adagietto;return}if(tt.isStringInStringList(tt.listInstantaneousTempoAndanteModerato,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.andanteModerato)),this.tempoInBpm=n,this.tempoEnum=bt.andanteModerato;return}if(tt.isStringInStringList(tt.listInstantaneousTempoAndante,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.andante)),this.tempoInBpm=n,this.tempoEnum=bt.andante;return}if(tt.isStringInStringList(tt.listInstantaneousTempoAndantino,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.andantino)),this.tempoInBpm=n,this.tempoEnum=bt.andantino;return}if(tt.isStringInStringList(tt.listInstantaneousTempoModerato,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.moderato)),this.tempoInBpm=n,this.tempoEnum=bt.moderato;return}if(tt.isStringInStringList(tt.listInstantaneousTempoAllegretto,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.allegretto)),this.tempoInBpm=n,this.tempoEnum=bt.allegretto;return}if(tt.isStringInStringList(tt.listInstantaneousTempoAllegroModerato,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.allegroModerato)),this.tempoInBpm=n,this.tempoEnum=bt.allegroModerato;return}if(tt.isStringInStringList(tt.listInstantaneousTempoAllegro,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.allegro)),this.tempoInBpm=n,this.tempoEnum=bt.allegro;return}if(tt.isStringInStringList(tt.listInstantaneousTempoVivace,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.vivace)),this.tempoInBpm=n,this.tempoEnum=bt.vivace;return}if(tt.isStringInStringList(tt.listInstantaneousTempoVivacissimo,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.vivacissimo)),this.tempoInBpm=n,this.tempoEnum=bt.vivacissimo;return}if(tt.isStringInStringList(tt.listInstantaneousTempoAllegrissimo,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.allegrissimo)),this.tempoInBpm=n,this.tempoEnum=bt.allegrissimo;return}if(tt.isStringInStringList(tt.listInstantaneousTempoPresto,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.presto)),this.tempoInBpm=n,this.tempoEnum=bt.presto;return}if(tt.isStringInStringList(tt.listInstantaneousTempoPrestissimo,this.label)){n===0&&(n=tt.getDefaultValueForTempoType(bt.prestissimo)),this.tempoInBpm=n,this.tempoEnum=bt.prestissimo;return}if(tt.isStringInStringList(tt.listInstantaneousTempoAddons,this.label)){this.tempoInBpm=0,this.tempoEnum=bt.addon;return}if(tt.isStringInStringList(tt.listInstantaneousTempoChangesGeneral,this.label)){this.tempoInBpm=0,this.tempoEnum=bt.changes;return}}};let qt=tt;qt.listInstantaneousTempoLarghissimo=["Larghissimo","Sehr breit","very, very slow"];qt.listInstantaneousTempoGrave=["Grave","Schwer","slow and solemn"];qt.listInstantaneousTempoLento=["Lento","Lent","Langsam","slowly"];qt.listInstantaneousTempoLargo=["Largo","Breit","broadly"];qt.listInstantaneousTempoLarghetto=["Larghetto","Etwas breit","rather broadly"];qt.listInstantaneousTempoAdagio=["Adagio","Langsam","Ruhig","slow and stately"];qt.listInstantaneousTempoAdagietto=["Adagietto","Ziemlich ruhig","Ziemlich langsam","rather slow"];qt.listInstantaneousTempoAndanteModerato=["Andante moderato"];qt.listInstantaneousTempoAndante=["Andante","Gehend","Schreitend","at a walking pace"];qt.listInstantaneousTempoAndantino=["Andantino"];qt.listInstantaneousTempoModerato=["Moderato","M\xE4\xDFig","Mod\uFFFDr\uFFFD","moderately"];qt.listInstantaneousTempoAllegretto=["Allegretto","fast"];qt.listInstantaneousTempoAllegroModerato=["Allegro moderato"];qt.listInstantaneousTempoAllegro=["Allegro","Rapide","Vite","Rasch","Schnell","Fr\uFFFDhlich"];qt.listInstantaneousTempoVivace=["Vivace","Lebhaft","Lebendig","lively and fast"];qt.listInstantaneousTempoVivacissimo=["Vivacissimo","Sehr lebhaft","Sehr lebendig"];qt.listInstantaneousTempoAllegrissimo=["Allegrissimo","very fast"];qt.listInstantaneousTempoPresto=["Presto","Sehr schnell","Geschwind"];qt.listInstantaneousTempoPrestissimo=["Prestissimo","\xE4u\xDFerst schnell"];qt.listInstantaneousTempoChangesGeneral=["tempo primo","a tempo","tempo i","rubato","doppio movimento"];qt.listInstantaneousTempoAddons=["assai","amoroso","cantabile","con brio","con dolore","con espressione","con fuoco","con moto","con spirito","spiritoso","espressivo","giocoso","giusto","grazioso","lesto","lugubre","maestoso","ma non troppo","marcato","molto","morendo","mosso","non tanto","piu","un poco","poco","quasi","risoluto","scherzando","sostenuto","teneramente","tempo giusto","tranquillo","sehr","lieblich","liebevoll","mit Leidenschaft","mit Liebe","amour\xF6s","gesanglich","mit Schwung","mit Feuer","mit Schmerz","mit Ausdruck","mit Bewegung","geistvoll","ausdrucksvoll","freudig","verspielt","angemessen","grazi\xF6s","mit Grazie","flink","beh\xE4nde","traurig","klagend","majest\xE4tisch","aber nicht zu sehr","markant","gem\xE4\xDFigt","viel","sehr","ersterbend","bewegt","nicht zu sehr","mehr","ein wenig","gleichsam","entschlossen","zupackend","heiter","nachdr\xFCcklich","getragen","gewichtig","zart","z\xE4rtlich","im angemessenen Zeitma\xDF","ruhig","ein wenig","alla marcia","ad libitum","alla breve"];var bt=(n=>(n[n.none=0]="none",n[n.larghissimo=1]="larghissimo",n[n.grave=2]="grave",n[n.lento=3]="lento",n[n.largo=4]="largo",n[n.larghetto=5]="larghetto",n[n.adagio=6]="adagio",n[n.adagietto=7]="adagietto",n[n.andanteModerato=8]="andanteModerato",n[n.andante=9]="andante",n[n.andantino=10]="andantino",n[n.moderato=11]="moderato",n[n.allegretto=12]="allegretto",n[n.allegroModerato=13]="allegroModerato",n[n.allegro=14]="allegro",n[n.vivace=15]="vivace",n[n.vivacissimo=16]="vivacissimo",n[n.allegrissimo=17]="allegrissimo",n[n.presto=18]="presto",n[n.prestissimo=19]="prestissimo",n[n.lastRealTempo=20]="lastRealTempo",n[n.addon=21]="addon",n[n.changes=22]="changes",n[n.metronomeMark=23]="metronomeMark",n))(bt||{});const X=class extends Ii{constructor(n,t,e){super(t),this.label=n,this.staffNumber=e,this.setMoodType()}static isInputStringMood(n){return n?X.isStringInStringList(X.listMoodAffettuoso,n)||X.isStringInStringList(X.listMoodAgitato,n)||X.isStringInStringList(X.listMoodAnimato,n)||X.isStringInStringList(X.listMoodAppassionato,n)||X.isStringInStringList(X.listMoodBrillante,n)||X.isStringInStringList(X.listMoodCantabile,n)||X.isStringInStringList(X.listMoodDolce,n)||X.isStringInStringList(X.listMoodEnergico,n)||X.isStringInStringList(X.listMoodEroico,n)||X.isStringInStringList(X.listMoodEspressivo,n)||X.isStringInStringList(X.listMoodFurioso,n)||X.isStringInStringList(X.listMoodGiocoso,n)||X.isStringInStringList(X.listMoodGioioso,n)||X.isStringInStringList(X.listMoodGrandioso,n)||X.isStringInStringList(X.listMoodGrazioso,n)||X.isStringInStringList(X.listMoodLacrimoso,n)||X.isStringInStringList(X.listMoodLeggiero,n)||X.isStringInStringList(X.listMoodMaestoso,n)||X.isStringInStringList(X.listMoodMalinconico,n)||X.isStringInStringList(X.listMoodMarcato,n)||X.isStringInStringList(X.listMoodMarziale,n)||X.isStringInStringList(X.listMoodMesto,n)||X.isStringInStringList(X.listMoodMorendo,n)||X.isStringInStringList(X.listMoodNobilmente,n)||X.isStringInStringList(X.listMoodPatetico,n)||X.isStringInStringList(X.listMoodPesante,n)||X.isStringInStringList(X.listMoodSaltando,n)||X.isStringInStringList(X.listMoodSautille,n)||X.isStringInStringList(X.listMoodScherzando,n)||X.isStringInStringList(X.listMoodSostenuto,n)||X.isStringInStringList(X.listMoodSpiccato,n)||X.isStringInStringList(X.listMoodTenerezza,n)||X.isStringInStringList(X.listMoodTranquillamente,n)||X.isStringInStringList(X.listMoodTrionfante,n):!1}get Label(){return this.label}set Label(n){this.label=n}get Mood(){return this.moodType}set Mood(n){this.moodType=n}get StaffNumber(){return this.staffNumber}set StaffNumber(n){this.staffNumber=n}get Placement(){return this.placement}set Placement(n){this.placement=n}setMoodType(){X.isStringInStringList(X.listMoodAffettuoso,this.label)?this.moodType=Gt.Affettuoso:X.isStringInStringList(X.listMoodAgitato,this.label)?this.moodType=Gt.Agitato:X.isStringInStringList(X.listMoodAnimato,this.label)?this.moodType=Gt.Animato:X.isStringInStringList(X.listMoodAppassionato,this.label)?this.moodType=Gt.Appassionato:X.isStringInStringList(X.listMoodBrillante,this.label)?this.moodType=Gt.Brillante:X.isStringInStringList(X.listMoodCantabile,this.label)?this.moodType=Gt.Cantabile:X.isStringInStringList(X.listMoodDolce,this.label)?this.moodType=Gt.Dolce:X.isStringInStringList(X.listMoodEnergico,this.label)?this.moodType=Gt.Energico:X.isStringInStringList(X.listMoodEroico,this.label)?this.moodType=Gt.Eroico:X.isStringInStringList(X.listMoodEspressivo,this.label)?this.moodType=Gt.Espressivo:X.isStringInStringList(X.listMoodFurioso,this.label)?this.moodType=Gt.Furioso:X.isStringInStringList(X.listMoodGiocoso,this.label)?this.moodType=Gt.Giocoso:X.isStringInStringList(X.listMoodGioioso,this.label)?this.moodType=Gt.Gioioso:X.isStringInStringList(X.listMoodGrandioso,this.label)?this.moodType=Gt.Grandioso:X.isStringInStringList(X.listMoodGrazioso,this.label)?this.moodType=Gt.Grazioso:X.isStringInStringList(X.listMoodLacrimoso,this.label)?this.moodType=Gt.Lacrimoso:X.isStringInStringList(X.listMoodLeggiero,this.label)?this.moodType=Gt.Leggiero:X.isStringInStringList(X.listMoodMaestoso,this.label)?this.moodType=Gt.Maestoso:X.isStringInStringList(X.listMoodMalinconico,this.label)?this.moodType=Gt.Malinconico:X.isStringInStringList(X.listMoodMarcato,this.label)?this.moodType=Gt.Marcato:X.isStringInStringList(X.listMoodMarziale,this.label)?this.moodType=Gt.Marziale:X.isStringInStringList(X.listMoodMesto,this.label)?this.moodType=Gt.Mesto:X.isStringInStringList(X.listMoodMorendo,this.label)?this.moodType=Gt.Morendo:X.isStringInStringList(X.listMoodNobilmente,this.label)?this.moodType=Gt.Nobilmente:X.isStringInStringList(X.listMoodPatetico,this.label)?this.moodType=Gt.Patetico:X.isStringInStringList(X.listMoodPesante,this.label)?this.moodType=Gt.Pesante:X.isStringInStringList(X.listMoodSaltando,this.label)?this.moodType=Gt.Saltando:X.isStringInStringList(X.listMoodSautille,this.label)?this.moodType=Gt.Sautille:X.isStringInStringList(X.listMoodScherzando,this.label)?this.moodType=Gt.Scherzando:X.isStringInStringList(X.listMoodSostenuto,this.label)?this.moodType=Gt.Sostenuto:X.isStringInStringList(X.listMoodSpiccato,this.label)?this.moodType=Gt.Spiccato:X.isStringInStringList(X.listMoodTenerezza,this.label)?this.moodType=Gt.Tenerezza:X.isStringInStringList(X.listMoodTranquillamente,this.label)?this.moodType=Gt.Tranquillamente:X.isStringInStringList(X.listMoodTrionfante,this.label)&&(this.moodType=Gt.Trionfante)}};let kt=X;kt.listMoodAffettuoso=["affettuoso"];kt.listMoodAgitato=["agitato"];kt.listMoodAppassionato=["appassionato"];kt.listMoodAnimato=["animato","lively"];kt.listMoodBrillante=["brillante"];kt.listMoodCantabile=["cantabile"];kt.listMoodDolce=["dolce"];kt.listMoodEnergico=["energico"];kt.listMoodEroico=["eroico"];kt.listMoodEspressivo=["espressivo"];kt.listMoodFurioso=["furioso"];kt.listMoodGiocoso=["giocoso"];kt.listMoodGioioso=["gioioso"];kt.listMoodLacrimoso=["lacrimoso"];kt.listMoodGrandioso=["grandioso"];kt.listMoodGrazioso=["grazioso"];kt.listMoodLeggiero=["leggiero"];kt.listMoodMaestoso=["maestoso"];kt.listMoodMalinconico=["malinconico"];kt.listMoodMarcato=["marcato"];kt.listMoodMarziale=["marziale"];kt.listMoodMesto=["mesto"];kt.listMoodMorendo=["morendo"];kt.listMoodNobilmente=["nobilmente"];kt.listMoodPatetico=["patetico"];kt.listMoodPesante=["pesante"];kt.listMoodSautille=["sautille"];kt.listMoodSaltando=["saltando"];kt.listMoodScherzando=["scherzando"];kt.listMoodSostenuto=["sostenuto"];kt.listMoodSpiccato=["spiccato"];kt.listMoodTenerezza=["tenerezza"];kt.listMoodTranquillamente=["tranquillamente"];kt.listMoodTrionfante=["trionfante"];var Gt=(n=>(n[n.Affettuoso=0]="Affettuoso",n[n.Agitato=1]="Agitato",n[n.Appassionato=2]="Appassionato",n[n.Animato=3]="Animato",n[n.Brillante=4]="Brillante",n[n.Cantabile=5]="Cantabile",n[n.Dolce=6]="Dolce",n[n.Energico=7]="Energico",n[n.Eroico=8]="Eroico",n[n.Espressivo=9]="Espressivo",n[n.Furioso=10]="Furioso",n[n.Giocoso=11]="Giocoso",n[n.Gioioso=12]="Gioioso",n[n.Lacrimoso=13]="Lacrimoso",n[n.Grandioso=14]="Grandioso",n[n.Grazioso=15]="Grazioso",n[n.Leggiero=16]="Leggiero",n[n.Maestoso=17]="Maestoso",n[n.Malinconico=18]="Malinconico",n[n.Marcato=19]="Marcato",n[n.Marziale=20]="Marziale",n[n.Mesto=21]="Mesto",n[n.Morendo=22]="Morendo",n[n.Nobilmente=23]="Nobilmente",n[n.Patetico=24]="Patetico",n[n.Pesante=25]="Pesante",n[n.Sautille=26]="Sautille",n[n.Saltando=27]="Saltando",n[n.Scherzando=28]="Scherzando",n[n.Sostenuto=29]="Sostenuto",n[n.Spiccato=30]="Spiccato",n[n.Tenerezza=31]="Tenerezza",n[n.Tranquillamente=32]="Tranquillamente",n[n.Trionfante=33]="Trionfante",n[n.Vivace=34]="Vivace",n))(Gt||{});class ms extends Ii{constructor(t,e,i,s){super(e),this.label=t,this.staffNumber=s,i===void 0&&(i=vt.LeftBottom),this.textAlignment=i}get Label(){return this.label}get Placement(){return this.placement}set Placement(t){this.placement=t}get StaffNumber(){return this.staffNumber}set StaffNumber(t){this.staffNumber=t}get TextAlignment(){return this.textAlignment}}class nu{constructor(t,e){this.unknownList=[],this.moodList=[],this.expressions=[],this.sourceMeasure=t,this.timestamp=e}get SourceMeasureParent(){return this.sourceMeasure}set SourceMeasureParent(t){this.sourceMeasure=t}get StaffNumber(){return this.staffNumber}set StaffNumber(t){this.staffNumber=t}get Timestamp(){return this.timestamp}set Timestamp(t){this.timestamp=t}get AbsoluteTimestamp(){return W.plus(this.timestamp,this.sourceMeasure.AbsoluteTimestamp)}get InstantaneousDynamic(){return this.instantaneousDynamic}set InstantaneousDynamic(t){this.instantaneousDynamic=t}get EndingContinuousDynamic(){return this.endingContinuousDynamic}set EndingContinuousDynamic(t){this.endingContinuousDynamic=t}get StartingContinuousDynamic(){return this.startingContinuousDynamic}set StartingContinuousDynamic(t){this.startingContinuousDynamic=t}get MoodList(){return this.moodList}get UnknownList(){return this.unknownList}get EntriesList(){return this.expressions}get OctaveShiftStart(){return this.octaveShiftStart}set OctaveShiftStart(t){this.octaveShiftStart=t}get OctaveShiftEnd(){return this.octaveShiftEnd}set OctaveShiftEnd(t){this.octaveShiftEnd=t}get CombinedExpressionsText(){return this.combinedExpressionsText}set CombinedExpressionsText(t){this.combinedExpressionsText=t}getPlacementOfFirstEntry(){let t=z.Above;return this.expressions.length>0&&(this.expressions[0].expression instanceof Ai?t=this.expressions[0].expression.Placement:this.expressions[0].expression instanceof ei?t=this.expressions[0].expression.Placement:this.expressions[0].expression instanceof kt?t=this.expressions[0].expression.Placement:this.expressions[0].expression instanceof ms&&(t=this.expressions[0].expression.Placement)),t}getFontstyleOfFirstEntry(){var e;let t=ue.Regular;return this.expressions.length>0&&(this.expressions[0].expression instanceof ei||this.expressions[0].expression instanceof kt?t=ue.Italic:this.expressions[0].expression instanceof ms&&(t=(e=this.expressions[0].expression.fontStyle)!=null?e:ue.Regular)),t}addExpression(t,e){t instanceof Ai?(this.instantaneousDynamic&&this.removeExpressionFromEntryList(this.InstantaneousDynamic),this.instantaneousDynamic=t,this.instantaneousDynamic.ParentMultiExpression=this):t instanceof ei?this.startingContinuousDynamic=t:t instanceof kt?this.moodList.push(t):t instanceof ms&&this.unknownList.push(t),this.addExpressionToEntryList(t,e)}CompareTo(t){return this.Timestamp.RealValue>t.Timestamp.RealValue?1:this.Timestamp.RealValue=us.allargando&&n<=us.ritenuto}get TempoType(){return this.tempoType}set TempoType(n){this.tempoType=n}get StartTempo(){return this.startTempo}set StartTempo(n){this.startTempo=n}get EndTempo(){return this.endTempo}set EndTempo(n){this.endTempo=n}get AbsoluteEndTimestamp(){return this.absoluteEndTimestamp}set AbsoluteEndTimestamp(n){this.absoluteEndTimestamp=n}get AbsoluteTimestamp(){return this.ParentMultiTempoExpression.AbsoluteTimestamp}getAbsoluteFloatTimestamp(){return this.ParentMultiTempoExpression.AbsoluteTimestamp.RealValue}getInterpolatedTempo(n){const t=W.plus(this.parentMultiTempoExpression.SourceMeasureParent.AbsoluteTimestamp,this.parentMultiTempoExpression.Timestamp);if(n.lt(t))return-1;if(this.absoluteEndTimestamp.lt(n))return-2;const e=W.minus(n,t).RealValue/W.minus(this.absoluteEndTimestamp,t).RealValue;return Math.max(0,Math.min(250,this.startTempo+(this.endTempo-this.startTempo)*e))}setTempoType(){_i.isStringInStringList(_i.listContinuousTempoFaster,this.label)?this.tempoType=us.accelerando:_i.isStringInStringList(_i.listContinuousTempoSlower,this.label)&&(this.tempoType=us.ritardando)}};let Ni=_i;Ni.listContinuousTempoFaster=["accelerando","piu mosso","poco piu","stretto"];Ni.listContinuousTempoSlower=["poco meno","meno mosso","piu lento","rallentando","ritardando","ritenuto","ritard.","ritard","riten.","riten"];var us=(n=>(n[n.accelerando=0]="accelerando",n[n.stretto=1]="stretto",n[n.stringendo=2]="stringendo",n[n.mosso=3]="mosso",n[n.piuMosso=4]="piuMosso",n[n.allargando=5]="allargando",n[n.calando=6]="calando",n[n.menoMosso=7]="menoMosso",n[n.rallentando=8]="rallentando",n[n.ritardando=9]="ritardando",n[n.ritard=10]="ritard",n[n.rit=11]="rit",n[n.ritenuto=12]="ritenuto",n[n.rubato=13]="rubato",n[n.precipitando=14]="precipitando",n))(us||{});class ou{constructor(t,e){this.expressions=[],this.sourceMeasure=t,this.timestamp=e}get Timestamp(){return this.timestamp}get AbsoluteTimestamp(){return W.plus(this.sourceMeasure.AbsoluteTimestamp,this.timestamp)}get SourceMeasureParent(){return this.sourceMeasure}set SourceMeasureParent(t){this.sourceMeasure=t}get InstantaneousTempo(){return this.instantaneousTempo}get ContinuousTempo(){return this.continuousTempo}get EntriesList(){return this.expressions}get CombinedExpressionsText(){return this.combinedExpressionsText}set CombinedExpressionsText(t){this.combinedExpressionsText=t}getPlacementOfFirstEntry(){let t=z.Above;return this.expressions.length>0&&(this.expressions[0].Expression instanceof qt?t=this.expressions[0].Expression.Placement:this.expressions[0].Expression instanceof Ni&&(t=this.expressions[0].Expression.Placement)),t}getFontstyleOfFirstEntry(){let t=ue.Regular;return this.expressions[0].Expression instanceof qt?t=ue.Bold:this.expressions[0].Expression instanceof Ni&&(t=ue.Italic),t}addExpression(t,e){if(this.checkIfAlreadyExists(t))return;t instanceof qt?this.instantaneousTempo=t:t instanceof Ni&&(this.continuousTempo=t);const i=new au;i.prefix=e,i.Expression=t,i.label=t.Label,this.expressions.push(i)}CompareTo(t){return this.Timestamp.RealValue>t.Timestamp.RealValue?1:this.Timestamp.RealValue0){if(this.rules.MaxSystemToDrawNumber===this.musicSystems.length)return this.finalizeCurrentSystem(this.measureList[this.measureList.length-1],!this.rules.StretchLastSystemLine,!1),this.musicSystems;this.finalizeCurrentAndCreateNewSystem(this.measureList[this.measureList.length-1],!this.rules.StretchLastSystemLine,!1)}return this.musicSystems}calculateSystemYLayout(){for(const t of this.musicSystems)this.optimizeDistanceBetweenStaffLines(t);this.calculateMusicSystemsRelativePositions()}setMeasureWidth(t,e,i,s){for(let r=0,o=t.length;r0&&(a.beginInstructionsWidth=i),s>0&&(a.endInstructionsWidth=s)}}finalizeCurrentAndCreateNewSystem(t,e=!1,i=!0,s=!1){this.finalizeCurrentSystem(t,e,i,s),this.currentSystemParams=new In,t!==void 0&&this.measureListIndex=1){const e=this.currentSystemParams.currentSystem.GraphicalMeasures[this.currentSystemParams.currentSystem.GraphicalMeasures.length-1];let i=0;const s=t[t.length-1];s.endLine===Et.DotsBoldBoldDots&&(s.endLine=Et.DotsThinBold,i=e[0].getLineWidth(Et.DotsBoldBoldDots)/2-e[0].getLineWidth(Et.DotsThinBold)),this.currentSystemParams.currentSystemFixWidth-=i;for(let r=0,o=e.length;r1){o=!0;break}}let a=0;for(let l=0;l=0&&this.measureList[m]){const b=(d=this.measureList[m][0])==null?void 0:d.parentSourceMeasure;(b==null?void 0:b.ImplicitMeasure)&&(b==null?void 0:b.RhythmPrinted)&&(p=!1)}p&&(e.addRhythmAtBegin(h),e.parentSourceMeasure.RhythmPrinted=h,f=!0)}return(c||u||f)&&(o+=e.beginInstructionsWidth,f&&(o+=this.rules.RhythmRightMargin)),o}addInstructionsAtMeasureEnd(t,e,i){if(!t||!t.Instructions||t.Instructions.length===0)return 0;for(let s=0,r=t.Instructions.length;s0&&(this.currentSystemParams.systemMeasures.push({beginLine:Et.None,endLine:Et.None}),this.currentSystemParams.currentWidth+=s,this.currentSystemParams.currentSystemFixWidth+=s)}addExtraInstructionMeasure(t,e,i){const s=this.currentSystemParams.currentSystem,r=Lt.symbolFactory.createExtraGraphicalMeasure(s.StaffLines[t]);e&&r.addKeyAtBegin(e,this.activeKeys[t],this.activeClefs[t]),i!==void 0&&i.PrintObject&&r.addRhythmAtBegin(i),r.PositionAndShape.BorderLeft=0,r.PositionAndShape.BorderTop=0,r.PositionAndShape.BorderBottom=this.rules.StaffHeight;const o=this.rules.MeasureLeftMargin+r.beginInstructionsWidth+this.rules.MeasureRightMargin;return r.PositionAndShape.BorderRight=o,s.StaffLines[t].Measures.push(r),o}addStaveMeasuresToSystem(t){if(t[0]){const e=[];for(let s=0;s1){const a=Math.min(this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures.length-1,t.measureListIndex+t.multipleRestMeasures-1);t=this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures[a]}}finally{}const e=this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures,i=e[this.measureListIndex];let s=!1;return i.allRests&&(s=(o=(r=e[this.measureListIndex+i.multipleRestMeasures-1])==null?void 0:r.endsWithLineRepetition)==null?void 0:o.call(r)),this.nextMeasureBeginsLineRepetition()&&this.thisMeasureEndsLineRepetition()?Et.DotsBoldBoldDots:this.thisMeasureEndsLineRepetition()||s?Et.DotsThinBold:this.nextMeasureHasKeyInstructionChange()||this.thisMeasureEndsWordRepetition()||this.nextMeasureBeginsWordRepetition()?Et.DoubleThin:t&&t.endingBarStyleEnum!==void 0?t.endingBarStyleEnum:Et.SingleThin}getLineWidth(t,e,i){let s=t.getLineWidth(e);return e===Et.DotsBoldBoldDots&&(s/=2),i&&e===Et.BoldThinDots&&(s+=this.rules.DistanceBetweenLastInstructionAndRepetitionBarline),s}previousMeasureEndsLineRepetition(){if(this.measureListIndex===0)return!1;for(let t=0,e=this.measureList[this.measureListIndex-1].length;t=this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures.length||!this.measureList[t])return!1;for(let e=0,i=this.measureList[t].length;e=this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures.length||t>this.measureList.length-1)return!1;for(let e=0,i=this.measureList[t].length;e1)for(let a=1;ar&&(r=c)}for(let a=0;athis.rules.PageHeight-this.rules.PageBottomMargin&&(s++,s<=4&&console.log(`warning: could not fit a single system on page ${t.PageNumber} and measure number ${i.GraphicalMeasures[0][0].MeasureNumber}. The PageFormat may be too small for this sheet." Will not give further warnings for all pages, only total.`))}else{const l=this.musicSystems[a-1],h=l.StaffLines[l.StaffLines.length-1],c=h.PositionAndShape;let u=this.findRequiredDistanceWithSkyBottomLine(l,i);u=Math.max(r,u),u+=this.rules.MinSkyBottomDistBetweenSystems,((o=window==null?void 0:window.appName)==null?void 0:o.toLocaleUpperCase())==="GYM"&&(u=u<16?16:u);const f=this.hasExpressionCounts(i);f.TempoCount>0&&this.rules.MetronomeMarksDrawn&&(u+=2),f.OtherCount>0&&this.rules.MetronomeMarksDrawn&&(u+=2),u=Math.max(u,this.rules.MinimumDistanceBetweenSystems+h.StaffHeight);const d=e+c.RelativePosition.y+u,p=d+i.PositionAndShape.BorderMarginBottom;if(!(this.rules.NewPageAtXMLNewPageAttribute&&l.breaksPage)&&p0&&console.log(`total amount of pages that couldn't fit a single music system: ${s} of ${t.PageNumber}`)}findRequiredDistanceWithSkyBottomLine(t,e){const i=t.StaffLines[t.StaffLines.length-1],s=e.StaffLines[0],r=i.BottomLine,o=s.SkyLine,a=i.PositionAndShape,l=s.PositionAndShape,h=1/this.rules.SamplingUnit;let c=0;for(let u=0;u=o.length)break;const p=Math.max(0,d-6),g=Math.min(o.length-1,d+6);let m=0;for(let b=p;b<=g;b++)m=Math.min(m,o[b]);const S=f-m;c=Math.max(S,c)}return c===0&&(c=a.BorderBottom-l.BorderTop),c}}class In{constructor(){this.systemMeasures=[],this.systemMeasureIndex=0,this.currentWidth=0,this.currentSystemFixWidth=0,this.currentSystemVarWidth=0,this.maxLabelLength=0}IsSystemStartMeasure(){return this.systemMeasureIndex===0}}class hu{constructor(t,e,i){this.getOpenOctaveShift=t,this.getAbsoluteStartTimestamp=e,this.getAbsoluteEndTimestamp=i}}class cu{constructor(){this.keySignatureNoteAlterationsDict=new Ye,this.currentAlterationsComparedToKeyInstructionList=[],this.currentInMeasureNoteAlterationsDict=new Ye}get ActiveKeyInstruction(){return this.activeKeyInstruction}set ActiveKeyInstruction(t){this.activeKeyInstruction=t,this.reactOnKeyInstructionChange()}doCalculationsAtEndOfMeasure(){this.currentInMeasureNoteAlterationsDict.clear(),this.currentAlterationsComparedToKeyInstructionList.clear();for(const t of this.keySignatureNoteAlterationsDict.keys())this.currentInMeasureNoteAlterationsDict.setValue(t,this.keySignatureNoteAlterationsDict.getValue(t))}checkAccidental(t,e){if(!e)return;const i=e.FundamentalNote+e.Octave*12,s=this.currentAlterationsComparedToKeyInstructionList.indexOf(i)>=0;if(this.currentInMeasureNoteAlterationsDict.containsKey(i)){if(s&&this.currentAlterationsComparedToKeyInstructionList.splice(this.currentAlterationsComparedToKeyInstructionList.indexOf(i),1),this.currentInMeasureNoteAlterationsDict.getValue(i)!==e.AccidentalHalfTones){this.keySignatureNoteAlterationsDict.containsKey(i)&&this.keySignatureNoteAlterationsDict.getValue(i)!==e.AccidentalHalfTones?(this.currentAlterationsComparedToKeyInstructionList.push(i),this.currentInMeasureNoteAlterationsDict.setValue(i,e.AccidentalHalfTones)):e.Accidental!==yt.NONE&&this.currentInMeasureNoteAlterationsDict.remove(i);const r=this.currentInMeasureNoteAlterationsDict.getValue(i);if(e.Accidental===yt.NONE&&(Math.abs(r)===.5?e=new Kt(e.FundamentalNote,e.Octave,yt.NONE):e=new Kt(e.FundamentalNote,e.Octave,yt.NATURAL)),this.isAlterAmbiguousAccidental(e.Accidental)&&!e.AccidentalXml)return;Lt.symbolFactory.addGraphicalAccidental(t,e)}}else if(e.Accidental!==yt.NONE){if(s||this.currentAlterationsComparedToKeyInstructionList.push(i),this.currentInMeasureNoteAlterationsDict.setValue(i,e.AccidentalHalfTones),this.isAlterAmbiguousAccidental(e.Accidental)&&!e.AccidentalXml)return;Lt.symbolFactory.addGraphicalAccidental(t,e)}else s&&(e=new Kt(e.FundamentalNote,e.Octave,yt.NATURAL),this.currentAlterationsComparedToKeyInstructionList.splice(this.currentAlterationsComparedToKeyInstructionList.indexOf(i),1),Lt.symbolFactory.addGraphicalAccidental(t,e))}isAlterAmbiguousAccidental(t){return t===yt.SLASHFLAT||t===yt.QUARTERTONEFLAT}reactOnKeyInstructionChange(){const t=this.activeKeyInstruction.AlteratedNotes;let e;this.activeKeyInstruction.Key>0?e=yt.SHARP:e=yt.FLAT,this.keySignatureNoteAlterationsDict.clear(),this.currentAlterationsComparedToKeyInstructionList.length=0;for(let i=-9;i<9;i++)for(let s=0;s0?(i=h-1,t.push({startIndex:e,endIndex:i}),e=h):f.HasEndLine&&this.rules.NewPartAndSystemAfterFinalBarline&&(i=h,t.push({startIndex:e,endIndex:i}),e=h+1)}ep&&x%2===0?(r.push(x),y=E,x=1):x++:y>p?(r.push(x),y=E,x=1):x++,E>p?P=w+1:P=Math.ceil(P),S===P?b+=1:(s.push(b),S=P,b=1)}s.push(b),r.push(x),r=r.filter(Boolean),console.log(r,s)}return this.buildPreparedMusicSystems(r)}buildPreparedMusicSystems(t){let e=!1;this.currentSystemParams=new In,this.currentSystemParams.currentSystem=this.initMusicSystem();for(let i=0,s=this.measureList.length;i0&&this.rules.RenderMultipleRestMeasures){u.isReducedToMultiRest=!0,u.multipleRestMeasureNumber=1;const d=u.multipleRestMeasures-1;h+=d;for(let p=1;p<=d;p++){const g=t.SourceMeasures[u.MeasureNumber-1+p];g.multipleRestMeasureNumber=p+1,g.isReducedToMultiRest=!0,e.push([void 0])}}}if(this.rules.AutoGenerateMutipleRestMeasuresFromRestMeasures&&this.rules.RenderMultipleRestMeasures){let h,c=0;for(let u=0,f=t.SourceMeasures.length;u0){h.isReducedToMultiRest=!0,h.multipleRestMeasureNumber=1,c++,d.multipleRestMeasureNumber=c,d.isReducedToMultiRest=!0;for(let p=0;p1){h.multipleRestMeasures=c;const p=this.createGraphicalMeasuresForSourceMeasure(h,i,r,a,s);e[h.measureListIndex]=p,c=0,h=void 0}else c=0,h=void 0}if(c>1){h.multipleRestMeasures=c,h.isReducedToMultiRest=!0;const u=this.createGraphicalMeasuresForSourceMeasure(h,i,r,a,s);e[h.measureListIndex]=u,c=0,h=void 0}}const l=s.map(h=>h.ClefType===Pt.percussion);this.handleStaffEntries(l),this.calculateVerticalContainersList(),this.setIndicesToVerticalGraphicalContainers()}calculate(){this.musicSystems=[],this.clearSystemsAndMeasures(),this.clearRecreatedObjects(),this.createGraphicalTies(),this.calculateSheetLabelBoundingBoxes(),this.calculateXLayout(this.graphicalMusicSheet,this.maxInstrNameLabelLength()),this.graphicalMusicSheet.MusicPages.length=0,this.calculateMusicSystems(),La.transformRelativeToAbsolutePosition(this.graphicalMusicSheet)}calculateXLayout(t,e){let i=0;const s=this.rules.MaxInstructionsConstValue;if(this.graphicalMusicSheet.MeasureList.length>0){let r=this.graphicalMusicSheet.MeasureList[0],o=this.calculateMeasureXLayout(r);o=this.calculateMeasureWidthFromStaffEntries(r,o),Lt.setMeasuresMinStaffEntriesWidth(r,o),i=o*1.2+e+s;for(let a=1;a0)return;const o=e.Measures[r];(o.MeasureNumber===0||o.MeasureNumber===1)&&(i=o.MeasureNumber),o!==e.Measures[0]&&this.rules.MeasureNumberLabelXOffset?s=this.rules.MeasureNumberLabelXOffset:s=0;const a=this.rules.UseXMLMeasureNumbers&&o.MeasureNumber===1&&o.parentSourceMeasure.getPrintedMeasureNumber()!==1;((o.MeasureNumber===i||o.MeasureNumber>=i+this.rules.MeasureNumberLabelOffset)&&!o.parentSourceMeasure.ImplicitMeasure||a)&&((o.MeasureNumber!==1||o.MeasureNumber===1&&o!==e.Measures[0]||a)&&this.calculateSingleMeasureNumberPlacement(o,e,t,s),i=o.MeasureNumber)}}calculateSingleMeasureNumberPlacement(t,e,i,s=0){const r=t.parentSourceMeasure.getPrintedMeasureNumber().toString(),o=new jt(r),a=new Se(o,this.rules.MeasureNumberLabelHeight,vt.LeftBottom,this.rules),l=e.SkyBottomLineCalculator;a.setLabelPositionAndShapeBorders(),a.PositionAndShape.Parent=i.PositionAndShape;const h=e.PositionAndShape.RelativePosition.x+t.PositionAndShape.RelativePosition.x-a.PositionAndShape.BorderMarginLeft+s;let c,u=h,f=h-a.PositionAndShape.BorderLeft+a.PositionAndShape.BorderRight;u-=e.PositionAndShape.RelativePosition.x,f-=e.PositionAndShape.RelativePosition.x;const d=u+.5,p=f-.5,g=l.getSkyLineMinInRange(d,p);if(t===e.Measures[0]){let m=0;if(i.GroupBrackets.length>0)for(const S of i.GroupBrackets)m=Math.min(m,S.PositionAndShape.BorderTop);c=Math.min(g,m)}else c=g;c=Math.min(0,c),a.PositionAndShape.RelativePosition=new O(h,c),i.MeasureNumberLabels.push(a)}calculateMeasureNumberSkyline(t){const e=t.StaffLines[0];for(const i of t.MeasureNumberLabels){let s=i.PositionAndShape.RelativePosition.x,r=s-i.PositionAndShape.BorderLeft+i.PositionAndShape.BorderRight;s-=e.PositionAndShape.RelativePosition.x,r-=e.PositionAndShape.RelativePosition.x,e.SkyBottomLineCalculator.updateSkyLineInRange(s,r,i.PositionAndShape.RelativePosition.y+i.PositionAndShape.BorderMarginTop)}}layoutGraphicalTie(t,e,i){throw new Error(this.abstractNotImplementedErrorMessage)}calculateSingleStaffLineLyricsPosition(t,e){let i=0,s=this.rules.StaffHeight;const r=[],o=t.SkyBottomLineCalculator;let a=t.Measures.length;for(let h=0;h0){r.push(p),i=Math.max(i,p.LyricsEntries.length);const g=p.PositionAndShape.RelativePosition.x+u.x;let m=Number.MAX_VALUE,S=Number.MIN_VALUE;for(let y=0;y0){const h=t.PositionAndShape.Size.width;let c=r[0].PositionAndShape.RelativePosition.x+r[0].PositionAndShape.BorderMarginLeft+r[0].parentMeasure.PositionAndShape.RelativePosition.x;c=c>h?h:c,o.updateBottomLineInRange(c,h,l)}return r}calculateLyricsExtendsAndDashes(t){for(let e=0,i=t.length;e0||t.UnknownList.length>0){let l="";for(let d=0,p=t.EntriesList.length;dt.length-1&&(j.debug("minimum measure to draw index out of range. resetting min measure index to limit."),this.rules.MinMeasureToDrawIndex=t.length-1);const e=[];for(let o=this.rules.MinMeasureToDrawIndex,a=t.length;o0)&&(s=i.getSkyLineMinInRange(u,f));let d=0;a===0?(d+=this.rules.ChordSymbolYOffset,d+=.1):d+=this.rules.ChordSymbolYPadding,d*=-1;const p=l.GraphicalLabel;p.PositionAndShape.RelativePosition.y=s+d,p.setLabelPositionAndShapeBorders(),p.PositionAndShape.calculateBoundingBox(),i.updateSkyLineInRange(u,f,s+p.PositionAndShape.BorderMarginTop)}}}}calculateAlignedChordSymbolsOffset(t,e){let i=Number.MAX_SAFE_INTEGER;for(const s of t)for(const r of s.graphicalChordContainers){const o=s.PositionAndShape,a=r.PositionAndShape,l=a.BorderMarginLeft+o.AbsolutePosition.x,h=a.BorderMarginRight+o.AbsolutePosition.x;i=Math.min(i,e.getSkyLineMinInRange(l,h))}return i}layoutMeasureWithWholeRest(t,e,i){}layoutBeams(t){}layoutArticulationMarks(t,e,i){}layoutOrnament(t,e,i){}calculateRestNotePlacementWithinGraphicalBeam(t,e,i,s,r){}calculateTupletNumbers(){}calculateSlurs(){}calculateDynamicExpressionsForMultiExpression(t,e,i){}calculateGraphicalVerbalContinuousDynamic(t,e){const i=t.Label,s=e.x+i.PositionAndShape.BorderMarginLeft,r=e.x+i.PositionAndShape.BorderMarginRight,o=t.ContinuousDynamic.Placement,l=t.ParentStaffLine.SkyBottomLineCalculator;let h;o===z.Below?(h=l.getBottomLineMaxInRange(s,r),i.PositionAndShape.RelativePosition=new O(e.x,h-i.PositionAndShape.BorderMarginTop)):(h=l.getSkyLineMinInRange(s,r),i.PositionAndShape.RelativePosition=new O(e.x,h-i.PositionAndShape.BorderMarginBottom))}calculateGraphicalContinuousDynamic(t,e){var v,G,et;const i=t.ParentStaffLine.ParentStaff.idInMusicSheet,s=this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(t.ContinuousDynamic.EndMultiExpression.SourceMeasureParent,i);if(!s){j.warn("MusicSheetCalculator.calculateGraphicalContinuousDynamic: No endMeasure found");return}t.EndMeasure=s;const r=t.ParentStaffLine,o=s.ParentStaffLine,a=o&&r===o;let l=!1;o?l=o==null?void 0:o.isPartOfMultiStaffInstrument():r&&(l=r==null?void 0:r.isPartOfMultiStaffInstrument());const h=W.createFromFraction(t.ContinuousDynamic.EndMultiExpression.AbsoluteTimestamp),c=this.graphicalMusicSheet.GetVerticalContainerFromTimestamp(h),u=c.getFirstNonNullStaffEntry().parentMeasure,f=u.PositionAndShape.AbsolutePosition.x+u.PositionAndShape.BorderRight;let d=new W(0,0,0);for(const H of c.StaffEntries){const nt=(v=H==null?void 0:H.sourceStaffEntry)==null?void 0:v.calculateMaxNoteLength();nt!=null&&nt.gt(d)&&(d=nt)}const p=this.getRelativePositionInStaffLineFromTimestamp(h,i,o,l,0),g=W.plus(h,d),m=this.getRelativePositionInStaffLineFromTimestamp(g,i,o,l,0);m.x>p.x&&m.xy){const lt=b.StaffLines[H].PositionAndShape.RelativePosition.y-r.PositionAndShape.RelativePosition.y-this.rules.StaffHeight;L=this.rules.StaffHeight+lt/2}else L=this.rules.WedgePlacementBelowY;L-=this.rules.WedgeOpeningLength/2,a||(k=L);let nt=x.getBottomLineMaxInRange(C,I);if(nt>L&&(L=nt),yk&&(k=nt),k+=this.rules.WedgeOpeningLength/2,k+=this.rules.WedgeVerticalMargin),L+=this.rules.WedgeOpeningLength/2,L+=this.rules.WedgeVerticalMargin}else if(w===z.Above){if(r.ParentStaff.ParentInstrument.Staves.length===1)L=this.rules.WedgePlacementAboveY;else{let nt=0;y>0&&(nt=y-1);const K=b.StaffLines[nt];L=-(r.PositionAndShape.RelativePosition.y-K.PositionAndShape.RelativePosition.y-this.rules.StaffHeight)/2}L+=this.rules.WedgeOpeningLength/2,a||(k=L);let H=x.getSkyLineMinInRange(C,I);if(H1&&y>0){const nt=r.findClosestStaffEntry(C),K=r.findClosestStaffEntry(I);nt&&K&&nt.parentVerticalContainer}a||(H=o.SkyBottomLineCalculator.getSkyLineMinInRange(P,F),H-u/2?l=-u/2:l=h-t.PositionAndShape.BorderMarginBottom}else l=h-t.PositionAndShape.BorderMarginBottom;t.PositionAndShape.RelativePosition=new O(e.x,l)}else if(t.Placement===z.Below){const h=a.getBottomLineMaxInRange(r,o),c=s.ParentStaff.ParentInstrument.Staves[s.ParentStaff.ParentInstrument.Staves.length-1];if(s.isPartOfMultiStaffInstrument()&&s.ParentStaff!==c){const f=s.ParentMusicSystem.StaffLines[s.ParentMusicSystem.StaffLines.indexOf(s)+1].PositionAndShape.RelativePosition.y-s.PositionAndShape.RelativePosition.y-this.rules.StaffHeight,d=t.PositionAndShape.BorderMarginBottom;h+dt.PositionAndShape.Size.width&&(f=t.PositionAndShape.Size.width-this.rules.MeasureRightMargin,u=f-h.PositionAndShape.MarginSize.width,e.x=u-h.PositionAndShape.BorderMarginLeft);let d;const p=t.SkyBottomLineCalculator;return r===z.Below?d=p.getBottomLineMaxInRange(u,f):d=p.getSkyLineMinInRange(u,f),h.PositionAndShape.RelativePosition=new O(e.x,d),r===z.Below?p.updateBottomLineInRange(u,f,h.PositionAndShape.BorderMarginBottom+d):p.updateSkyLineInRange(u,f,h.PositionAndShape.BorderMarginTop+d),h}calculateTempoExpressionsForMultiTempoExpression(t,e,i,s){mr={};const r=W.plus(t.AbsoluteTimestamp,e.Timestamp),o=this.graphicalMusicSheet.MeasureList[i];let a=new O;if(e.ContinuousTempo||e.InstantaneousTempo){if(this.rules.MinMeasureToDrawIndex>0||!o[0])return;let l=o[0].ParentStaffLine,h=o[0].PositionAndShape.RelativePosition.x,c=0;for(let u=0;u0){l=o[u].ParentStaffLine,h=o[u].PositionAndShape.RelativePosition.x,c=u;break}if(a=this.getRelativePositionInStaffLineFromTimestamp(r,c,l,l.isPartOfMultiStaffInstrument(),h),e.EntriesList.length>0&&e.EntriesList[0].Expression instanceof qt){const u=e.EntriesList[0].Expression;if(u.Placement=z.Above,l.Measures[0].staffEntries.length>0&&Math.abs(a.x-l.Measures[0].staffEntries[0].PositionAndShape.RelativePosition.x)===0&&l.ParentMusicSystem===this.musicSystems[0]){const f=l.Measures[0].FirstInstructionStaffEntry;if(f){const d=f.GraphicalInstructions.last();a.x=d.PositionAndShape.RelativePosition.x}this.rules.CompactMode&&(a.x=l.PositionAndShape.RelativePosition.x+l.Measures[0].PositionAndShape.RelativePosition.x)}}for(const u of e.EntriesList){let f=vt.CenterBottom;this.rules.CompactMode&&(f=vt.LeftBottom);const d=this.calculateLabel(l,a,u.label,e.getFontstyleOfFirstEntry(),u.Expression.Placement,this.rules.UnknownTextHeight,f);if(u.Expression instanceof qt){for(const g of l.AbstractExpressions)g instanceof Tr&&(g.SourceExpression.Label,u.Expression.Label);new Tr(u.Expression,d).ParentStaffLine||j.warn("Adding staffline didn't work"),u.Expression.Enum===bt.metronomeMark&&(mr[i]=u.Expression)}else u.Expression instanceof Ni;if(s===t.TempoExpressions.length-1)for(const p of Object.values(mr))this.createMetronomeMark(p,i)}}}createMetronomeMark(t,e){throw new Error(this.abstractNotImplementedErrorMessage)}graphicalMeasureCreatedCalculations(t){}clearSystemsAndMeasures(){for(let t=0,e=this.graphicalMusicSheet.MusicPages.length;t-1&&f.PositionAndShape.ChildElements.splice(d,1),f.FirstInstructionStaffEntry=void 0,f.beginInstructionsWidth=0}if(f.LastInstructionStaffEntry){const d=f.PositionAndShape.ChildElements.indexOf(f.LastInstructionStaffEntry.PositionAndShape);d>-1&&f.PositionAndShape.ChildElements.splice(d,1),f.LastInstructionStaffEntry=void 0,f.endInstructionsWidth=0}}h.Measures=[],h.PositionAndShape.ChildElements=[]}o.StaffLines.length=0,o.PositionAndShape.ChildElements=[]}i.MusicSystems=[],i.PositionAndShape.ChildElements=[]}this.graphicalMusicSheet.MusicPages=[]}handleVoiceEntry(t,e,i,s,r,o,a,l,h,c=void 0,u=void 0){t.StemDirectionXml!==Ft.Undefined&&this.rules.SetWantedStemDirectionByXml&&t.StemDirectionXml!==void 0?t.WantedStemDirection=t.StemDirectionXml:this.calculateStemDirectionFromVoices(t);const f=e.findOrCreateGraphicalVoiceEntry(t);f.octaveShiftValue=l;const d=e.tabStaffEntry;let p;d&&(p=d.findOrCreateGraphicalVoiceEntry(t));for(let g=0,m=t.Notes.length;g-1)continue;let b;if(t.IsGrace?b=Lt.symbolFactory.createGraceNote(S,f,r,this.rules,l):(b=Lt.symbolFactory.createNote(S,f,r,l,this.rules,void 0),Lt.stafflineNoteCalculator.trackNote(b)),S.Pitch&&this.checkNoteForAccidental(b,i,r,l),this.resetYPositionForLeadSheet(b.PositionAndShape),e.addGraphicalNoteToListAtCorrectYPosition(f,b),b.PositionAndShape.calculateBoundingBox(),this.leadSheet||(S.NoteBeam!==void 0&&S.PrintObject&&this.handleBeam(b,S.NoteBeam,a),S.NoteTuplet!==void 0&&S.PrintObject&&this.handleTuplet(b,S.NoteTuplet,o)),p){const y=Lt.symbolFactory.createNote(S,p,r,l,this.rules,void 0);d.addGraphicalNoteToListAtCorrectYPosition(p,y),y.PositionAndShape.calculateBoundingBox(),this.leadSheet||S.NoteTuplet&&this.handleTuplet(y,S.NoteTuplet,o)}}return t.Articulations.length>0&&this.handleVoiceEntryArticulations(t.Articulations,t,e),t.TechnicalInstructions.length>0&&this.handleVoiceEntryTechnicalInstructions(t.TechnicalInstructions,t,e),t.LyricsEntries.size()>0&&this.handleVoiceEntryLyrics(t,e,s),t.OrnamentContainer&&this.handleVoiceEntryOrnaments(t.OrnamentContainer,t,e),l}resetYPositionForLeadSheet(t){this.leadSheet&&(t.RelativePosition=new O(t.RelativePosition.x,0))}layoutVoiceEntries(t,e){if(t.PositionAndShape.RelativePosition=new O(0,0),!this.leadSheet)for(const i of t.graphicalVoiceEntries){const s=i.notes;if(s.length===0)continue;const r=s[0].sourceNote.ParentVoiceEntry,o=s[0].sourceNote.Pitch!==void 0;this.layoutVoiceEntry(r,s,t,o)}}maxInstrNameLabelLength(){var e;let t=0;for(const i of this.graphicalMusicSheet.ParentMusicSheet.Instruments)if(((e=i.NameLabel)==null?void 0:e.print)&&i.Voices.length>0&&i.Voices[0].Visible){let s=i.NameLabel;this.rules.RenderPartNames||(s=new jt("",s.textAlignment,s.font));const r=new Se(s,this.rules.InstrumentLabelTextHeight,vt.LeftCenter,this.rules);r.setLabelPositionAndShapeBorders(),t=Math.max(t,r.PositionAndShape.MarginSize.width)}return this.rules.RenderPartNames?t:0}calculateSheetLabelBoundingBoxes(){var s;const t=this.graphicalMusicSheet.ParentMusicSheet,e=this.rules.DefaultColorTitle;if(t.Title!==void 0&&this.rules.RenderTitle){const r=new Se(t.Title,this.rules.SheetTitleHeight,vt.CenterBottom,this.rules);r.Label.IsCreditLabel=!0,r.Label.colorDefault=e,this.graphicalMusicSheet.Title=r,r.setLabelPositionAndShapeBorders()}else this.rules.RenderTitle||(this.graphicalMusicSheet.Title=void 0);if(t.Subtitle!==void 0&&this.rules.RenderSubtitle){const r=new Se(t.Subtitle,this.rules.SheetSubtitleHeight,vt.CenterCenter,this.rules);r.Label.IsCreditLabel=!0,r.Label.colorDefault=e,this.graphicalMusicSheet.Subtitle=r,r.setLabelPositionAndShapeBorders()}else this.rules.RenderSubtitle||(this.graphicalMusicSheet.Subtitle=void 0);if(t.Composer!==void 0&&this.rules.RenderComposer){const r=new Se(t.Composer,this.rules.SheetComposerHeight,vt.RightCenter,this.rules);r.Label.IsCreditLabel=!0,r.Label.colorDefault=e,this.graphicalMusicSheet.Composer=r,r.setLabelPositionAndShapeBorders()}else this.rules.RenderComposer||(this.graphicalMusicSheet.Composer=void 0);if(t.Lyricist!==void 0&&this.rules.RenderLyricist){const r=new Se(t.Lyricist,this.rules.SheetAuthorHeight,vt.LeftCenter,this.rules);r.Label.IsCreditLabel=!0,r.Label.colorDefault=e,this.graphicalMusicSheet.Lyricist=r,r.setLabelPositionAndShapeBorders()}else this.rules.RenderLyricist||(this.graphicalMusicSheet.Lyricist=void 0);const i=(s=this.graphicalMusicSheet.musicSheet.sourceMeasures)==null?void 0:s[0];if(i&&i.FirstInstructionsStaffEntries.length>0){const r=i.FirstInstructionsStaffEntries[0];let o,a;for(let l=0,h=r.Instructions.length;l0&&c.graphicalVoiceEntries[0].notes.length===1){const u=c.graphicalVoiceEntries[0].notes[0];!u.sourceNote.Pitch&&new W(1,2).lt(u.sourceNote.Length)&&this.layoutMeasureWithWholeRest(u,c,h)}}}}}}optimizeRestNotePlacement(t,e){if(t.graphicalVoiceEntries.length===0)return;const i=t.graphicalVoiceEntries[0].notes;if(i.length===0)return;const s=i[0],r=s.sourceNote.isRest();if(t.graphicalVoiceEntries.length===2){let o=!1;const a=t.graphicalVoiceEntries[1].notes;a.length>0&&(o=a[0].sourceNote.isRest()),r&&o?this.calculateTwoRestNotesPlacementWithCollisionDetection(t):(r||o)&&this.calculateRestNotePlacementWithCollisionDetectionFromGraphicalNote(t)}else if(r&&t!==e.staffEntries[0]&&t!==e.staffEntries[e.staffEntries.length-1]){const o=e.staffEntries.indexOf(t),a=e.staffEntries[o-1],l=e.staffEntries[o+1];if(a.graphicalVoiceEntries.length===1){const h=a.graphicalVoiceEntries[0].notes[0];if(h.sourceNote.NoteBeam!==void 0&&l.graphicalVoiceEntries.length===1){const c=l.graphicalVoiceEntries[0].notes[0];c.sourceNote.NoteBeam!==void 0&&h.sourceNote.NoteBeam===c.sourceNote.NoteBeam&&(this.calculateRestNotePlacementWithinGraphicalBeam(t,s,h,l,c),t.PositionAndShape.calculateBoundingBox())}}}}getRelativePositionInStaffLineFromTimestamp(t,e,i,s,r=0){let o=new O,a,l;const h=this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers.length,c=this.graphicalMusicSheet.GetInterpolatedIndexInVerticalContainers(t),u=Math.min(Math.floor(c),h-1),f=Math.min(Math.ceil(c),h-1);if(u<0||e<0)return o;if(a=this.getFirstLeftNotNullStaffEntryFromContainer(u,e,s),l=this.getFirstRightNotNullStaffEntryFromContainer(f,e,s),a&&l){let d=a.parentMeasure.PositionAndShape.RelativePosition.x;r>0&&(d=r);let p=a.PositionAndShape.RelativePosition.x+d,g=l.PositionAndShape.RelativePosition.x+l.parentMeasure.PositionAndShape.RelativePosition.x;r>0&&(g=l.PositionAndShape.RelativePosition.x+d);let m=0;if(a!==l){const S=a.getAbsoluteTimestamp(),b=l.getAbsoluteTimestamp();m=W.minus(t,S).RealValue/W.minus(b,S).RealValue}a.parentMeasure.ParentStaffLine!==l.parentMeasure.ParentStaffLine&&(a.parentMeasure.ParentStaffLine===i?g=i.PositionAndShape.Size.width:p=i.PositionAndShape.RelativePosition.x),o=new O(p+(g-p)*m,0)}return o}getRelativeXPositionFromTimestamp(t){const e=this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers.length,i=this.graphicalMusicSheet.GetInterpolatedIndexInVerticalContainers(t),s=Math.max(0,Math.min(Math.round(i),e-1)),r=this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers[s].getFirstNonNullStaffEntry();return r.PositionAndShape.RelativePosition.x+r.parentMeasure.PositionAndShape.RelativePosition.x}calculatePageLabels(t){var o;this.rules.RenderSingleHorizontalStaffline&&(t.PositionAndShape.BorderRight=t.PositionAndShape.Size.width,t.PositionAndShape.calculateBoundingBox(),this.graphicalMusicSheet.ParentMusicSheet.pageWidth=t.PositionAndShape.Size.width);let e=10;if(t.MusicSystems.length>0){const a=t.MusicSystems[0];e=a.PositionAndShape.RelativePosition.y+a.PositionAndShape.BorderTop}if(this.graphicalMusicSheet.Title){const a=this.graphicalMusicSheet.Title;a.PositionAndShape.Parent=t.PositionAndShape;const l=new O;l.x=this.graphicalMusicSheet.ParentMusicSheet.pageWidth/2,l.y=this.rules.TitleTopDistance+this.rules.SheetTitleHeight,a.PositionAndShape.RelativePosition=l,t.Labels.push(a)}if(this.graphicalMusicSheet.Subtitle){const a=this.graphicalMusicSheet.Subtitle;a.PositionAndShape.Parent=t.PositionAndShape;const l=new O;l.x=this.graphicalMusicSheet.ParentMusicSheet.pageWidth/2,l.y=this.rules.TitleTopDistance+this.rules.SheetTitleHeight+this.rules.SheetMinimumDistanceBetweenTitleAndSubtitle,a.PositionAndShape.RelativePosition=l,t.Labels.push(a)}const i=this.graphicalMusicSheet.Composer;let s;if(i){i.PositionAndShape.Parent=t.PositionAndShape,i.setLabelPositionAndShapeBorders();const a=new O;a.x=this.graphicalMusicSheet.ParentMusicSheet.pageWidth-this.rules.PageRightMargin,a.y=e,a.y-=this.rules.SystemComposerDistance;const l=(o=i.TextLines)==null?void 0:o.length;l>1&&(a.y-=i.PositionAndShape.BorderBottom*(l-1)/l),s=a.y,i.PositionAndShape.RelativePosition=a,t.Labels.push(i)}const r=this.graphicalMusicSheet.Lyricist;if(r){r.PositionAndShape.Parent=t.PositionAndShape,r.setLabelPositionAndShapeBorders();const a=new O;a.x=this.rules.PageLeftMargin,a.y=e,a.y+=r.PositionAndShape.BorderBottom,a.y=Math.min(a.y,s!=null?s:Number.MAX_SAFE_INTEGER),r.PositionAndShape.RelativePosition=a,t.Labels.push(r)}}createGraphicalTies(){for(let t=0;t=0&&this.staffEntriesWithGraphicalTies.push(r)}r=a}}setTieDirections(t){if(!t)return;const e=t.ties;if(e.length>1){let i;for(const s of e){const r=s.Notes[0];(!i||r.Pitch.getHalfTone()>i.Pitch.getHalfTone())&&(i=r)}for(const s of e)s.TieDirection===z.NotYetDefined&&(s.Notes[0]===i?s.TieDirection=z.Above:s.TieDirection=z.Below)}}createAccidentalCalculators(){const t=[],e=this.graphicalMusicSheet.ParentMusicSheet.getFirstSourceMeasure();if(e)for(let i=0;i1)return;u=Lt.symbolFactory.createGraphicalMeasure(t,c)}if(u.hasError=t.getErrorInMeasure(l),t.FirstInstructionsStaffEntries[l])for(let y=0,x=t.FirstInstructionsStaffEntries[l].Instructions.length;y0){const C=x.Instructions[0];Lt.symbolFactory.createInStaffClef(w,C)}this.rules.RenderChordSymbols&&((b=x.ChordContainers)==null?void 0:b.length)>0&&(x.ParentStaff.ParentInstrument.HasChordSymbols=!0,Lt.symbolFactory.createChordSymbols(x,w,s.ActiveKeyInstruction,this.graphicalMusicSheet.ParentMusicSheet.Transpose))}}if(s.doCalculationsAtEndOfMeasure(),t.LastInstructionsStaffEntries[l]){const y=t.LastInstructionsStaffEntries[l];for(let x=0,w=y.Instructions.length;x=1&&u.staffEntries.length===0){const y=new we(new yn(u.parentSourceMeasure,u.parentSourceMeasure.AbsoluteTimestamp,u.parentSourceMeasure.CompleteNumberOfStaves),c),x=new ir(new W(0,1),c.Voices[0],y),w=new Cn(x,y,W.createFromFraction(t.Duration),void 0,t);w.PrintObject=this.rules.FillEmptyMeasuresWithWholeRest===_o.YesVisible,x.addNote(w);const T=Lt.symbolFactory.createStaffEntry(y,u);u.addGraphicalStaffEntry(T),T.relInMeasureTimestamp=x.Timestamp;const E=Lt.symbolFactory.createVoiceEntry(x,T);T.graphicalVoiceEntries.push(E);const C=Lt.symbolFactory.createNote(w,E,new Wt,oe.NONE,void 0);Lt.stafflineNoteCalculator.trackNote(C),E.notes.push(C)}u.hasOnlyRests=!0;for(const y of u.staffEntries)if(u.hasOnlyRests=y.hasOnlyRests(),!u.hasOnlyRests)break;return u}checkNoteForAccidental(t,e,i,s){let r=t.sourceNote.Pitch;const o=t.parentVoiceEntry.parentStaffEntry.parentMeasure.getTransposedHalftones();o!==0&&t.sourceNote.ParentStaffEntry.ParentStaff.ParentInstrument.MidiInstrumentId!==st.Percussion&&(r=t.Transpose(e.ActiveKeyInstruction,i,o,s),t.sourceNote.TransposedPitch=r),t.sourceNote.halfTone=r.getHalfTone(),e.checkAccidental(t,r)}handleStaffEntries(t){for(let e=0,i=this.graphicalMusicSheet.MeasureList.length;e0&&l.graphicalVoiceEntries[0].notes.length>0&&(this.layoutVoiceEntries(l,r),this.layoutStaffEntry(l));this.graphicalMeasureCreatedCalculations(a)}}}}calculateSkyBottomLines(){for(const t of this.musicSystems)for(const e of t.StaffLines)e.SkyBottomLineCalculator.calculateLines()}calculateExpressionAlignements(){}calculateStaffEntryArticulationMarks(){for(let t=0,e=this.musicSystems.length;t0&&this.layoutArticulationMarks(g.Articulations,g,f)}}}}}}calculateOrnaments(){for(let t=0,e=this.musicSystems.length;t0&&s.LyricVersesNumbers.sort()}for(let e=0,i=this.musicSystems.length;e=0&&(s=e.GraphicalLyricsEntries[i+1]),!s)return;const r=t.StaffEntryParent.parentMeasure.ParentStaffLine,o=s.StaffEntryParent.parentMeasure.ParentStaffLine,a=t.StaffEntryParent,l=s.StaffEntryParent;if(t.StaffEntryParent.parentMeasure.ParentStaffLine===s.StaffEntryParent.parentMeasure.ParentStaffLine){const h=a.parentMeasure.PositionAndShape.RelativePosition.x+a.PositionAndShape.RelativePosition.x+t.GraphicalLabel.PositionAndShape.RelativePosition.x+t.GraphicalLabel.PositionAndShape.BorderMarginRight,c=l.parentMeasure.PositionAndShape.RelativePosition.x+l.PositionAndShape.RelativePosition.x+t.GraphicalLabel.PositionAndShape.RelativePosition.x+s.GraphicalLabel.PositionAndShape.BorderMarginLeft,u=t.GraphicalLabel.PositionAndShape.RelativePosition.y;let f=1;c-h>this.rules.MinimumDistanceBetweenDashes*3&&(f=Math.floor((c-h)/this.rules.MinimumDistanceBetweenDashes)-1),f===1?this.calculateSingleDashForLyricWord(r,h,c,u):this.calculateDashes(r,h,c,u)}else{const h=a.parentMeasure.PositionAndShape.RelativePosition.x+a.PositionAndShape.RelativePosition.x+t.GraphicalLabel.PositionAndShape.BorderMarginRight,c=r.Measures[r.Measures.length-1],u=c.PositionAndShape.RelativePosition.x+c.PositionAndShape.Size.width;let f=t.GraphicalLabel.PositionAndShape.RelativePosition.y;if(this.calculateDashes(r,h,u,f),o&&o.Measures[0]&&l.parentMeasure.ParentStaffLine&&!(l===l.parentMeasure.staffEntries[0]&&l.parentMeasure===l.parentMeasure.ParentStaffLine.Measures[0])){const d=o.Measures[0].staffEntries[0].PositionAndShape.RelativePosition.x,p=l.parentMeasure.PositionAndShape.RelativePosition.x+l.PositionAndShape.RelativePosition.x+s.GraphicalLabel.PositionAndShape.BorderMarginLeft;f=s.GraphicalLabel.PositionAndShape.RelativePosition.y,this.calculateDashes(o,d,p,f)}}}calculateDashes(t,e,i,s){let r=i-e;if(re;)r=this.calculateRightAndLeftDashesForLyricWord(t,e,i,s),e+=a,i-=a,l++;r>a*2&&this.calculateSingleDashForLyricWord(t,e,i,s)}}calculateSingleDashForLyricWord(t,e,i,s){const r=new jt("-"),o=new Se(r,this.rules.LyricsHeight,vt.CenterBottom,this.rules);o.setLabelPositionAndShapeBorders(),t.LyricsDashes.push(o),this.staffLinesWithLyricWords.indexOf(t)===-1&&this.staffLinesWithLyricWords.push(t),o.PositionAndShape.Parent=t.PositionAndShape;const a=new O(e+(i-e)/2,s);o.PositionAndShape.RelativePosition=a}calculateLyricExtend(t){let e=t.GraphicalLabel.PositionAndShape.RelativePosition.y;const i=t.StaffEntryParent,s=i.parentMeasure.ParentStaffLine;let r,o;const a=i.parentMeasure.ParentStaff.idInMusicSheet;for(let l=i.parentVerticalContainer.Index+1;l0)break;r=h,o=r.parentMeasure.ParentStaffLine,o||(o=i.parentMeasure.ParentStaffLine)}}if(!(!r||!o))if(s===o&&r.parentMeasure.ParentStaffLine){const l=i.parentMeasure.PositionAndShape.RelativePosition.x+i.PositionAndShape.RelativePosition.x+t.GraphicalLabel.PositionAndShape.BorderMarginRight,h=r.parentMeasure.PositionAndShape.RelativePosition.x+r.PositionAndShape.RelativePosition.x+r.PositionAndShape.BorderMarginRight;e-=t.GraphicalLabel.PositionAndShape.Size.height/4,this.calculateSingleLyricWordWithUnderscore(s,l,h,e)}else{const l=s.Measures[s.Measures.length-1].PositionAndShape,h=i.parentMeasure.PositionAndShape.RelativePosition.x+i.PositionAndShape.RelativePosition.x+t.GraphicalLabel.PositionAndShape.BorderMarginRight,c=l.RelativePosition.x+l.Size.width;if(e-=t.GraphicalLabel.PositionAndShape.Size.height/4,this.calculateSingleLyricWordWithUnderscore(s,h,c,e),!r)return;if(r.parentMeasure.ParentStaffLine&&r.parentMeasure.staffEntries&&!(r===r.parentMeasure.staffEntries[0]&&r.parentMeasure===r.parentMeasure.ParentStaffLine.Measures[0])){const u=o.Measures[0].staffEntries[0].PositionAndShape.RelativePosition.x,f=r.parentMeasure.PositionAndShape.RelativePosition.x+r.PositionAndShape.RelativePosition.x+r.PositionAndShape.BorderMarginRight;this.calculateSingleLyricWordWithUnderscore(o,u,f,e)}}}calculateSingleLyricWordWithUnderscore(t,e,i,s){const r=new O(e,s),o=new O(i,s),a=new ci(r,o,this.rules.LyricUnderscoreLineWidth);t.LyricLines.push(a),this.staffLinesWithLyricWords.indexOf(t)===-1&&this.staffLinesWithLyricWords.push(t)}calculateRightAndLeftDashesForLyricWord(t,e,i,s){const r=new jt("-"),o=new Se(r,this.rules.LyricsHeight,vt.CenterBottom,this.rules);o.setLabelPositionAndShapeBorders(),t.LyricsDashes.push(o),this.staffLinesWithLyricWords.indexOf(t)===-1&&this.staffLinesWithLyricWords.push(t),o.PositionAndShape.Parent=t.PositionAndShape;const a=new O(e,s);o.PositionAndShape.RelativePosition=a;const l=new jt("-"),h=new Se(l,this.rules.LyricsHeight,vt.CenterBottom,this.rules);h.setLabelPositionAndShapeBorders(),t.LyricsDashes.push(h),h.PositionAndShape.Parent=t.PositionAndShape;const c=new O(i,s);return h.PositionAndShape.RelativePosition=c,h.PositionAndShape.RelativePosition.x-o.PositionAndShape.RelativePosition.x}calculateDynamicExpressions(){const t=Math.min(this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures.length-1,this.rules.MaxMeasureToDrawIndex),e=Math.min(this.rules.MinMeasureToDrawIndex,this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures.length);for(let i=e;i<=t;i++){const s=this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures[i];this.dynamicExpressionMap.clear();for(let r=0;r=0;o--)if((r=this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers[o])!=null&&r.StaffEntries[e])return this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers[o].StaffEntries[e]}getFirstRightNotNullStaffEntryFromContainer(t,e,i){var s,r;if((s=this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers[t])!=null&&s.StaffEntries[e])return this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers[t].StaffEntries[e];for(let o=t+1;o0||e.StaffLinkedExpressions[i][s].UnknownList.length>0)&&this.calculateMoodAndUnknownExpression(e.StaffLinkedExpressions[i][s],t,i)}}calculateStemDirectionFromVoices(t){if(t.ParentSourceStaffEntry.Link!==void 0)if(t===t.ParentSourceStaffEntry.VoiceEntries[0]){t.WantedStemDirection=Ft.Up;return}else{t.WantedStemDirection=Ft.Down;return}else t.ParentVoice instanceof bs?t.WantedStemDirection=Ft.Down:t.ParentSourceStaffEntry.VoiceEntries.length>1&&(t.WantedStemDirection=Ft.Up)}setBeamNotesWantedStemDirections(t){if(!(t.Notes.length>0))return;const e=t.Notes[0].NoteBeam;if(e){for(const i of e.Notes)if(i.ParentVoiceEntry.WantedStemDirection!==Ft.Undefined&&i.ParentVoiceEntry.ParentSourceStaffEntry.ParentStaff.Id===t.ParentSourceStaffEntry.ParentStaff.Id){t.WantedStemDirection=i.ParentVoiceEntry.WantedStemDirection;break}}}}class Ka{constructor(t,e,i,s,r){this.rootPitch=t,this.chordKind=e,this.bassPitch=i,this.degrees=s,this.rules=r}get RootPitch(){return this.rootPitch}get ChordKind(){return this.chordKind}get BassPitch(){return this.bassPitch}get ChordDegrees(){return this.degrees}static calculateChordText(t,e,i){let s=t.RootPitch;if(Lt.transposeCalculator&&(s=Lt.transposeCalculator.transposePitch(t.RootPitch,i,e)),t.ChordKind===Jt.none)return t.getTextFromChordKindEnum(t.ChordKind);let r=Kt.getNoteEnumString(s.FundamentalNote);s.Accidental!==yt.NONE&&(r+=this.getTextForAccidental(s.Accidental));const o={adds:[],alts:[],subs:[]};for(const c of t.ChordDegrees)if(c){let u="";switch(c.alteration!==yt.NONE&&(u+=this.getTextForAccidental(c.alteration)),u+=c.value,c.text){case zs.add:o.adds.push(u);break;case zs.alter:o.alts.push(u);break;case zs.subtract:o.subs.push(u);break}}let a=t.getTextFromChordKindEnum(t.ChordKind);const l=["adds","alts","subs"],h=t.rules.CustomChords;for(const c of h){if(c.chordKind!==t.chordKind)continue;let u=!0;for(const f of l){for(const d of c.degrees[f]||[])if(o[f].indexOf(d)<0){u=!1;break}if(!u)break}if(u){for(const f of l)for(const d of c.degrees[f]||[])o[f].splice(o[f].indexOf(d),1);a=c.alternateName}}if(r+=a,o.adds.length>0&&(r+="("+o.adds.join(",")+")"),o.alts.length>0&&(r+="(alt "+o.alts.join(",")+")"),o.subs.length>0&&(r+="(omit "+o.subs.join(",")+")"),t.BassPitch){let c=t.BassPitch;Lt.transposeCalculator&&(c=Lt.transposeCalculator.transposePitch(t.BassPitch,i,e)),r+="/",r+=Kt.getNoteEnumString(c.FundamentalNote),r+=this.getTextForAccidental(c.Accidental)}return r}static getTextForAccidental(t){let e="";switch(t){case yt.DOUBLEFLAT:e+="bb";break;case yt.FLAT:e+="b";break;case yt.SHARP:e+="#";break;case yt.DOUBLESHARP:e+="x";break}return e}getTextFromChordKindEnum(t){var e;return(e=this.rules.ChordSymbolLabelTexts.getValue(t))!=null?e:""}}class fu{constructor(t,e,i){this.value=t,this.alteration=e,this.text=i}}class kn{constructor(t,e,i){this.alternateName=t,this.chordKind=e,this.degrees=i}static createCustomChord(t,e,i){return new kn(t,e,i)}static renameCustomChord(t,e,i){for(const s of i)s.alternateName===t&&(s.alternateName=e)}}var zs=(n=>(n[n.add=0]="add",n[n.alter=1]="alter",n[n.subtract=2]="subtract",n))(zs||{}),Jt=(n=>(n[n.major=0]="major",n[n.minor=1]="minor",n[n.augmented=2]="augmented",n[n.diminished=3]="diminished",n[n.dominant=4]="dominant",n[n.majorseventh=5]="majorseventh",n[n.minorseventh=6]="minorseventh",n[n.diminishedseventh=7]="diminishedseventh",n[n.augmentedseventh=8]="augmentedseventh",n[n.halfdiminished=9]="halfdiminished",n[n.majorminor=10]="majorminor",n[n.majorsixth=11]="majorsixth",n[n.minorsixth=12]="minorsixth",n[n.dominantninth=13]="dominantninth",n[n.majorninth=14]="majorninth",n[n.minorninth=15]="minorninth",n[n.dominant11th=16]="dominant11th",n[n.major11th=17]="major11th",n[n.minor11th=18]="minor11th",n[n.dominant13th=19]="dominant13th",n[n.major13th=20]="major13th",n[n.minor13th=21]="minor13th",n[n.suspendedsecond=22]="suspendedsecond",n[n.suspendedfourth=23]="suspendedfourth",n[n.Neapolitan=24]="Neapolitan",n[n.Italian=25]="Italian",n[n.French=26]="French",n[n.German=27]="German",n[n.pedal=28]="pedal",n[n.power=29]="power",n[n.Tristan=30]="Tristan",n[n.none=31]="none",n))(Jt||{});class qa extends Pe{constructor(t,e,i,s=void 0){super(),this.DrawnAccidental=yt.NONE,this.lineShift=0,this.sourceNote=t,this.parentVoiceEntry=e,this.PositionAndShape=new le(this,e.PositionAndShape),s?this.graphicalNoteLength=s:this.graphicalNoteLength=t.Length,this.numberOfDots=this.calculateNumberOfNeededDots(this.graphicalNoteLength),this.rules=i,this.rules.addGraphicalNoteToNoteMap(t,this)}Transpose(t,e,i,s){let r=this.sourceNote.Pitch;return Lt.transposeCalculator&&(r=Lt.transposeCalculator.transposePitch(this.sourceNote.Pitch,t,i)),r}calculateNumberOfNeededDots(t){return!this.sourceNote||!this.sourceNote.NoteTuplet?t.calculateNumberOfNeededDots():0}get ParentMusicPage(){return this.parentVoiceEntry.parentStaffEntry.parentMeasure.ParentMusicSystem.Parent}static FromNote(t,e){return e.NoteToGraphicalNoteMap.getValue(t.NoteToGraphicalNoteObjectId)}}const Je=class{constructor(){this.DYSlursStartingAtSameStaffEntryYOffset=0,this.DYMinNoteWidth=0,this.DYWorkId=0,this.DYWorkSpecial=!1,this.DYContainerId="osmdCanvasPage",this.DYSVGContainerId="osmdSvgPage",this.DYMusicScoreType="staff",this.NoteDistances=[1,1,1.3,1.6,2,2.5,3,4],this.NoteDistancesScalingFactors=[1,2,4,8,16,32,64,128],this.DurationDistanceDict={},this.DurationScalingDistanceDict={},this.NoteToGraphicalNoteMapObjectCount=0,this.PlayAlreadyStartedNotesFromCursorPosition=!1,this.PlaybackSkipNotesSafetyInterval=.02,this.UseDefaultVoiceInteractionListener=!0,this.loadDefaultValues()}loadDefaultValues(){this.SamplingUnit=Je.unit*3,this.MpatMode=!0,this.SheetTitleHeight=4,this.SheetSubtitleHeight=2,this.SheetMinimumDistanceBetweenTitleAndSubtitle=1,this.SheetComposerHeight=2,this.SheetAuthorHeight=2,this.CompactMode=!1,this.PagePlacementEnum=Ea.Down,this.PageHeight=100001,this.PageTopMargin=5,this.PageTopMarginNarrow=0,this.PageBottomMargin=5,this.PageLeftMargin=5,this.PageRightMargin=5,this.TitleTopDistance=5,this.TitleBottomDistance=1,this.StaffDistance=7,this.BetweenStaffDistance=5,this.MinimumStaffLineDistance=4,this.MinSkyBottomDistBetweenStaves=1,this.StaffHeight=4,this.TabStaffInterlineHeight=1.1111,this.BetweenStaffLinesDistance=Je.unit,this.SystemLeftMargin=0,this.SystemRightMargin=0,this.SystemLabelsRightMargin=2,this.SystemComposerDistance=2,this.InstrumentLabelTextHeight=2,this.MinimumDistanceBetweenSystems=7,this.MinSkyBottomDistBetweenSystems=5,this.LastSystemMaxScalingFactor=1.4,this.AutoBeamNotes=!1,this.AutoBeamOptions={beam_middle_rests_only:!1,beam_rests:!1,maintain_stem_directions:!1},this.AutoBeamTabs=!1,this.BeamWidth=Je.unit/2,this.BeamSpaceWidth=Je.unit/3,this.BeamForwardLength=1.25*Je.unit,this.FlatBeams=!1,this.FlatBeamOffset=20,this.FlatBeamOffsetPerBeam=10,this.ClefLeftMargin=.5,this.ClefRightMargin=.75,this.PercussionOneLineCutoff=3,this.PercussionForceVoicesOneLineCutoff=1,this.PercussionUseXMLDisplayStep=!0,this.PercussionXMLDisplayStepNoteValueShift=0,this.PercussionOneLineXMLDisplayStepOctaveOffset=0,this.BetweenKeySymbolsDistance=.2,this.KeyRightMargin=.75,this.RhythmRightMargin=1.25,this.ShowRhythmAgainAfterPartEndOrFinalBarline=!0,this.NewPartAndSystemAfterFinalBarline=!1,this.InStaffClefScalingFactor=.8,this.DistanceBetweenNaturalAndSymbolWhenCancelling=.4,this.NoteHelperLinesOffset=.25,this.MeasureLeftMargin=.7,this.MeasureRightMargin=0,this.DistanceBetweenLastInstructionAndRepetitionBarline=1,this.ArpeggioDistance=.6,this.StaccatoShorteningFactor=2,this.IdealStemLength=3,this.StemNoteHeadBorderYOffset=.2,this.StemMargin=.2,this.StemMinLength=2.5,this.StemMaxLength=4.5,this.BeamSlopeMaxAngle=10,this.StemMinAllowedDistanceBetweenNoteHeadAndBeamLine=1,this.SetWantedStemDirectionByXml=!0,this.GraceNoteScalingFactor=.6,this.GraceNoteXOffset=.2,this.WedgeOpeningLength=1.2,this.WedgeMeasureEndOpeningLength=.75,this.WedgeMeasureBeginOpeningLength=.75,this.WedgePlacementAboveY=-1.5,this.WedgePlacementBelowY=1.5,this.WedgeHorizontalMargin=.6,this.WedgeVerticalMargin=.5,this.DistanceOffsetBetweenTwoHorizontallyCrossedWedges=.3,this.WedgeMinLength=2,this.WedgeEndDistanceBetweenTimestampsFactor=1.75,this.DistanceBetweenAdjacentDynamics=.75,this.TempoChangeMeasureValidity=4,this.TempoContinousFactor=.7,this.StaccatoScalingFactor=.8,this.BetweenDotsDistance=.8,this.OrnamentAccidentalScalingFactor=.65,this.ChordSymbolTextHeight=2,this.ChordSymbolTextAlignment=vt.LeftBottom,this.ChordSymbolRelativeXOffset=-1,this.ChordSymbolXSpacing=1,this.ChordOverlapAllowedIntoNextMeasure=0,this.ChordSymbolYOffset=.1,this.ChordSymbolYPadding=0,this.ChordSymbolYAlignment=!0,this.ChordSymbolYAlignmentScope="staffline",this.ChordSymbolLabelTexts=new Ye,this.resetChordSymbolLabelTexts(this.ChordSymbolLabelTexts),this.CustomChords=[],this.resetChordNames(),this.RepetitionSymbolsYOffset=0,this.RehearsalMarkXOffsetDefault=10,this.RehearsalMarkXOffset=0,this.RehearsalMarkXOffsetSystemStartMeasure=-20,this.RehearsalMarkYOffsetDefault=-15,this.RehearsalMarkYOffset=0,this.RehearsalMarkFontSize=10,this.MeasureNumberLabelHeight=1.5*Je.unit,this.MeasureNumberLabelOffset=2,this.MeasureNumberLabelXOffset=-.5,this.TupletsRatioed=!1,this.TupletsBracketed=!1,this.TripletsBracketed=!1,this.TupletNumberLabelHeight=1.5*Je.unit,this.TupletNumberYOffset=.5,this.LabelMarginBorderFactor=.1,this.TupletVerticalLineLength=.5,this.TupletNumbersInTabs=!1,this.SlurPlacementFromXML=!0,this.BezierCurveStepSize=1e3,this.calculateCurveParametersArrays(),this.TieGhostObjectWidth=.75,this.TieYPositionOffsetFactor=.3,this.MinimumNeededXspaceForTieGhostObject=1,this.TieHeightMinimum=.28,this.TieHeightMaximum=1.2,this.TieHeightInterpolationK=.0288,this.TieHeightInterpolationD=.136,this.SlurNoteHeadYOffset=.5,this.SlurStemXOffset=.3,this.SlurSlopeMaxAngle=15,this.SlurTangentMinAngle=30,this.SlurTangentMaxAngle=80,this.SlurHeightFactor=1,this.SlurHeightFlattenLongSlursFactorByWidth=.24,this.SlurHeightFlattenLongSlursFactorByAngle=.36,this.SlurHeightFlattenLongSlursCutoffAngle=47,this.SlurHeightFlattenLongSlursCutoffWidth=16,this.SlursStartingAtSameStaffEntryYOffset=.8,this.SlurMaximumYControlPointDistance=void 0,this.RepetitionEndingLabelHeight=2,this.RepetitionEndingLabelXOffset=.5,this.RepetitionEndingLabelYOffset=.3,this.RepetitionEndingLineYLowerOffset=.5,this.RepetitionEndingLineYUpperOffset=.3,this.VoltaOffset=2.5,this.LyricsAlignmentStandard=vt.LeftBottom,this.LyricsHeight=2,this.LyricsYOffsetToStaffHeight=0,this.VerticalBetweenLyricsDistance=.5,this.HorizontalBetweenLyricsDistance=.2,this.BetweenSyllableMaximumDistance=10,this.BetweenSyllableMinimumDistance=.5,this.LyricOverlapAllowedIntoNextMeasure=3.4,this.MinimumDistanceBetweenDashes=10,this.MaximumLyricsElongationFactor=2.5,this.InstantaneousTempoTextHeight=2.3,this.ContinuousDynamicTextHeight=2.3,this.MoodTextHeight=2.3,this.UnknownTextHeight=2,this.ContinuousTempoTextHeight=2.3,this.DynamicExpressionMaxDistance=2,this.DynamicExpressionSpacer=.5,this.VexFlowDefaultNotationFontScale=39,this.VexFlowDefaultTabFontScale=39,this.TremoloStrokeScale=1,this.TremoloYSpacingScale=1,this.StemWidth=.15,this.StaffLineWidth=.1,this.StaffLineColor=void 0,this.LedgerLineWidth=1,this.LedgerLineStrokeStyle=void 0,this.LedgerLineColorDefault="#000000",this.WedgeLineWidth=.12,this.TupletLineWidth=.12,this.LyricUnderscoreLineWidth=.12,this.SystemThinLineWidth=.12,this.SystemBoldLineWidth=Je.unit/2,this.SystemRepetitionEndingLineWidth=.12,this.SystemDotWidth=Je.unit/2,this.DistanceBetweenVerticalSystemLines=.35,this.DistanceBetweenDotAndLine=.7,this.RepeatEndStartPadding=2,this.OctaveShiftLineWidth=.12,this.OctaveShiftVerticalLineLength=Je.unit,this.GraceLineWidth=this.StaffLineWidth*this.GraceNoteScalingFactor,this.MultipleRestMeasureDefaultWidth=4,this.MinimumCrossedBeamDifferenceMargin=1e-4,this.SheetMaximumWidth=32767,this.VoiceSpacingMultiplierVexflow=.85,this.VoiceSpacingAddendVexflow=3,this.PickupMeasureWidthMultiplier=1,this.DisplacedNoteMargin=.1,this.MinNoteDistance=2,this.SubMeasureXSpacingThreshold=35,this.MeasureDynamicsMaxScalingFactor=2.5,this.WholeRestXShiftVexflow=-1.5,this.MetronomeMarksDrawn=!0,this.MetronomeMarkXShift=-6,this.MetronomeMarkYShift=-.5,this.SoftmaxFactorVexFlow=15,this.StaggerSameWholeNotes=!0,this.AlignRests=Hs.Never,this.RestCollisionYPadding=0,this.FillEmptyMeasuresWithWholeRest=_o.No,this.ArpeggiosGoAcrossVoices=!1,this.RenderArpeggios=!0,this.RenderSlurs=!0,this.ColoringMode=Ci.XML,this.ColoringEnabled=!0,this.ColorStemsLikeNoteheads=!1,this.ColorBeams=!0,this.ColorFlags=!0,this.applyDefaultColorMusic("#000000"),this.DefaultColorCursor="#33e02f",this.DefaultFontFamily="Times New Roman",this.DefaultFontStyle=ue.Regular,this.DefaultVexFlowNoteFont="gonville",this.MaxMeasureToDrawIndex=Number.MAX_VALUE,this.MinMeasureToDrawIndex=0,this.MaxSystemToDrawNumber=Number.MAX_VALUE,this.MaxPageToDrawNumber=Number.MAX_VALUE,this.RenderComposer=!0,this.RenderTitle=!0,this.RenderSubtitle=!0,this.RenderLyricist=!0,this.RenderPartNames=!0,this.RenderPartAbbreviations=!0,this.RenderFingerings=!0,this.RenderMeasureNumbers=!0,this.RenderMeasureNumbersOnlyAtSystemStart=!1,this.UseXMLMeasureNumbers=!0,this.RenderLyrics=!0,this.RenderChordSymbols=!0,this.RenderMultipleRestMeasures=!0,this.AutoGenerateMutipleRestMeasuresFromRestMeasures=!0,this.RenderRehearsalMarks=!0,this.RenderClefsAtBeginningOfStaffline=!0,this.RenderKeySignatures=!0,this.RenderTimeSignatures=!0,this.ArticulationPlacementFromXML=!0,this.FingeringPosition=z.AboveOrBelow,this.FingeringPositionFromXML=!0,this.FingeringPositionGrace=z.Left,this.FingeringInsideStafflines=!1,this.FingeringLabelFontHeight=1.7,this.FingeringOffsetX=0,this.FingeringOffsetY=0,this.FingeringPaddingY=-.2,this.FingeringTextSize=1.5,this.RenderStringNumbersClassical=!0,this.StringNumberOffsetY=0,this.NewSystemAtXMLNewSystemAttribute=!1,this.NewPageAtXMLNewPageAttribute=!1,this.RestoreCursorAfterRerender=!0,this.StretchLastSystemLine=!1,Je.FixStafflineBoundingBox=!1,this.PageFormat=Ce.UndefinedPageFormat,this.PageBackgroundColor=void 0,this.PerformanceMode=!1,this.RenderSingleHorizontalStaffline=!1,this.SpacingBetweenTextLines=0,this.NoteToGraphicalNoteMap=new Ye,this.NoteToGraphicalNoteMapObjectCount=0;try{this.MaxInstructionsConstValue=this.ClefLeftMargin+this.ClefRightMargin+this.KeyRightMargin+this.RhythmRightMargin+11}catch(n){j.info("EngravingRules()",n)}this.MpatMode&&(this.NewPartAndSystemAfterFinalBarline=!0)}applyDefaultColorMusic(n){this.DefaultColorMusic=n,this.DefaultColorNotehead=this.DefaultColorMusic,this.DefaultColorRest=this.DefaultColorNotehead,this.DefaultColorStem=this.DefaultColorNotehead,this.DefaultColorLabel=this.DefaultColorNotehead,this.DefaultColorTitle=this.DefaultColorNotehead,this.LedgerLineColorDefault=this.DefaultColorNotehead}addGraphicalNoteToNoteMap(n,t){n.NoteToGraphicalNoteObjectId=this.NoteToGraphicalNoteMapObjectCount,this.NoteToGraphicalNoteMap.setValue(n.NoteToGraphicalNoteObjectId,t),this.NoteToGraphicalNoteMapObjectCount++}GNote(n){return qa.FromNote(n,this)}clearMusicSheetObjects(){this.NoteToGraphicalNoteMap=new Ye,this.NoteToGraphicalNoteMapObjectCount=0}setChordSymbolLabelText(n,t){this.ChordSymbolLabelTexts.setValue(n,t)}resetChordSymbolLabelTexts(n){return n.setValue(Jt.minor,"m"),n.setValue(Jt.augmented,"aug"),n.setValue(Jt.diminished,"dim"),n.setValue(Jt.dominant,"7"),n.setValue(Jt.majorseventh,"maj7"),n.setValue(Jt.minorseventh,"m7"),n.setValue(Jt.diminishedseventh,"dim7"),n.setValue(Jt.augmentedseventh,"aug7"),n.setValue(Jt.halfdiminished,"m7b5"),n.setValue(Jt.majorminor,"m(maj7)"),n.setValue(Jt.majorsixth,"maj6"),n.setValue(Jt.minorsixth,"m6"),n.setValue(Jt.dominantninth,"9"),n.setValue(Jt.majorninth,"maj9"),n.setValue(Jt.minorninth,"m9"),n.setValue(Jt.dominant11th,"11"),n.setValue(Jt.major11th,"maj11"),n.setValue(Jt.minor11th,"m11"),n.setValue(Jt.dominant13th,"13"),n.setValue(Jt.major13th,"maj13"),n.setValue(Jt.minor13th,"m13"),n.setValue(Jt.suspendedsecond,"sus2"),n.setValue(Jt.suspendedfourth,"sus4"),n.setValue(Jt.power,"5"),n.setValue(Jt.none,"N.C."),n}addChordName(n,t,e,i,s){if(Jt[t]!==void 0){const r={adds:e,alts:i,subs:s};this.CustomChords.push(kn.createCustomChord(n,Jt[t],r))}}renameChord(n,t){kn.renameCustomChord(n,t,this.CustomChords)}resetChordNames(){this.addChordName("alt","major",["#5","b9","#9"],["b5"],[]),this.addChordName("7alt","dominant",["#5","b9","#9"],["b5"],[]),this.addChordName("7sus4","dominant",["4"],[],["3"]),this.addChordName("7sus4","suspendedfourth",["7"],[],[]),this.addChordName("9sus4","dominantninth",["4"],[],["3"]),this.addChordName("9sus4","suspendedfourth",["9"],[],[]),this.addChordName("11sus4","dominant11th",["4"],[],["3"]),this.addChordName("11sus4","suspendedfourth",["11"],[],[]),this.addChordName("13sus4","dominant13th",["4"],[],["3"]),this.addChordName("13sus4","suspendedfourth",["13"],[],[]),this.addChordName("7sus2","dominant",["2"],[],["3"]),this.addChordName("7sus2","suspendedsecond",["7"],[],[]),this.addChordName("m7b5","minorseventh",[],["b5"],[]),this.addChordName("9sus2","dominantninth",["2"],[],["3"]),this.addChordName("9sus2","suspendedsecond",["9"],[],[]),this.addChordName("11sus2","dominant11th",["2"],[],["3"]),this.addChordName("11sus2","suspendedsecond",["11"],[],[]),this.addChordName("13sus2","dominant13th",["2"],[],["3"]),this.addChordName("13sus2","suspendedsecond",["13"],[],[]),this.addChordName("m(maj9)","majorminor",["9"],[],[]),this.addChordName("m(maj11)","majorminor",["11"],[],[]),this.addChordName("m(maj13)","majorminor",["13"],[],[]),this.addChordName("69","majorsixth",["9"],[],[]),this.addChordName("mi69","minorsixth",["9"],[],[])}calculateCurveParametersArrays(){this.TPower3=new Array(this.BezierCurveStepSize),this.OneMinusTPower3=new Array(this.BezierCurveStepSize),this.FactorOne=new Array(this.BezierCurveStepSize),this.FactorTwo=new Array(this.BezierCurveStepSize);for(let n=0;n(n[n.XML=0]="XML",n[n.AutoColoring=1]="AutoColoring",n[n.CustomColorSet=2]="CustomColorSet",n))(Ci||{}),vo=(n=>(n.allon="allon",n.compact="compact",n.compacttight="compacttight",n.default="default",n.leadsheet="leadsheet",n.preview="preview",n.thumbnail="thumbnail",n))(vo||{});class Ja{constructor(t="default"){this.rules=new Ui,this.drawCursors=!0,this.drawTitle=!0,this.drawSubtitle=!0,this.drawLyricist=!0,this.drawComposer=!0,this.drawCredits=!0,this.drawPartNames=!0,this.fingeringPosition=z.Left,this.drawHiddenNotes=!1,this.DrawingParametersEnum=t}set DrawingParametersEnum(t){switch(this.drawingParametersEnum=t,t){case"allon":this.setForAllOn();break;case"thumbnail":this.setForThumbnail();break;case"leadsheet":this.setForLeadsheet();break;case"compact":this.setForCompactMode();break;case"compacttight":this.setForCompactTightMode();break;case"default":default:this.setForDefault()}}get DrawingParametersEnum(){return this.drawingParametersEnum}setForAllOn(){this.drawHighlights=!0,this.drawErrors=!0,this.drawSelectionStartSymbol=!0,this.drawSelectionEndSymbol=!0,this.drawCursors=!0,this.drawActivitySymbols=!0,this.drawScrollIndicator=!0,this.drawAnnotations=!0,this.drawComments=!0,this.drawMarkedAreas=!0,this.DrawTitle=!0,this.DrawSubtitle=!0,this.DrawComposer=!0,this.DrawLyricist=!0,this.drawCredits=!0,this.DrawPartNames=!0,this.drawHiddenNotes=!0,this.rules.CompactMode=!1}setForDefault(){this.rules.loadDefaultValues(),this.setForAllOn(),this.drawHiddenNotes=!1}setForThumbnail(){this.drawHighlights=!1,this.drawErrors=!1,this.drawSelectionStartSymbol=!1,this.drawSelectionStartSymbol=!1,this.drawCursors=!1,this.drawActivitySymbols=!1,this.drawScrollIndicator=!1,this.drawAnnotations=!0,this.drawComments=!0,this.drawMarkedAreas=!0,this.drawHiddenNotes=!1}setForCompactMode(){this.rules.CompactMode=!0,this.DrawCredits=!1,this.drawHiddenNotes=!1}setForCompactTightMode(){this.setForCompactMode(),this.DrawPartNames=!1,this.rules.VoiceSpacingMultiplierVexflow=.65,this.rules.VoiceSpacingAddendVexflow=2,this.rules.MinSkyBottomDistBetweenStaves=1,this.rules.MinSkyBottomDistBetweenSystems=1,this.rules.BetweenStaffDistance=2.5,this.rules.StaffDistance=3.5,this.rules.MinimumDistanceBetweenSystems=1,this.rules.PageBottomMargin=0,this.rules.PageLeftMargin=2,this.rules.PageRightMargin=2}setForLeadsheet(){this.drawHighlights=!1,this.drawErrors=!1,this.drawSelectionStartSymbol=!0,this.drawSelectionEndSymbol=!0,this.drawCursors=!0,this.drawActivitySymbols=!1,this.drawScrollIndicator=!0,this.drawAnnotations=!0,this.drawComments=!0,this.drawMarkedAreas=!0}get DrawCredits(){return this.drawCredits}set DrawCredits(t){this.drawCredits=t,this.DrawComposer=t,this.DrawTitle=t,this.DrawSubtitle=t,this.DrawLyricist=t}get DrawTitle(){return this.drawTitle}set DrawTitle(t){this.drawTitle=t,this.rules.RenderTitle=t,t||(this.DrawSubtitle=!1)}get DrawSubtitle(){return this.drawSubtitle}set DrawSubtitle(t){this.drawSubtitle=t,this.rules.RenderSubtitle=t,t&&(this.DrawTitle=!0)}get DrawComposer(){return this.drawComposer}set DrawComposer(t){this.drawComposer=t,this.rules.RenderComposer=t}get DrawLyricist(){return this.drawLyricist}set DrawLyricist(t){this.drawLyricist=t,this.rules.RenderLyricist=t}get DrawPartNames(){return this.drawPartNames}set DrawPartNames(t){this.drawPartNames=t,this.rules.RenderPartNames=t,this.rules.RenderPartNames||(this.rules.RenderPartAbbreviations=!1)}get FingeringPosition(){return this.fingeringPosition}set FingeringPosition(t){this.fingeringPosition=t,this.rules.FingeringPosition=t}get Rules(){return this.rules}set Rules(t){this.rules=t}}var Hs=(n=>(n[n.Never=0]="Never",n[n.Always=1]="Always",n[n.Auto=2]="Auto",n))(Hs||{}),_o=(n=>(n[n.No=0]="No",n[n.YesVisible=1]="YesVisible",n[n.YesInvisible=2]="YesInvisible",n))(_o||{}),$i=(n=>(n[n.SVG=0]="SVG",n[n.Canvas=1]="Canvas",n))($i||{});class ea{static OSMDOptionsStandard(){return{autoResize:!0,backend:"svg",drawingParameters:vo.default}}static BackendTypeFromString(t){return t&&t.toLowerCase()==="canvas"?1:0}}class Ks{constructor(t){if(this.hasAttributes=!1,!t)throw new Error("IXmlElement: expected Element, got undefined");this.elem=t,this.name=t.nodeName.toLowerCase(),t.hasAttributes()&&(this.hasAttributes=!0,this.firstAttribute=t.attributes[0]),this.hasElements=t.hasChildNodes(),t.childNodes.length===1&&t.childNodes[0].nodeType===Node.TEXT_NODE?this.value=t.childNodes[0].nodeValue:this.value=""}attribute(t){return this.elem.attributes.getNamedItem(t)}attributes(){if(!this.attrs){const t=this.elem.attributes,e=[];for(let i=0;i0?this.Voices[0].Visible:!1}set Visible(t){for(let e=0,i=this.Voices.length;e-1&&this.parent.MusicSystems.splice(e,1)}this.parent=t,this.boundingBox.Parent=t.PositionAndShape}get NextSystem(){const t=this.Parent.MusicSystems.indexOf(this);return t!==this.Parent.MusicSystems.length?this.Parent.MusicSystems[t+1]:void 0}get StaffLines(){return this.staffLines}get GraphicalMeasures(){return this.graphicalMeasures}get MeasureNumberLabels(){return this.measureNumberLabels}get Labels(){return this.labels.values()}get ObjectsToRedraw(){return this.objectsToRedraw}get InstrumentBrackets(){return this.instrumentBrackets}get GroupBrackets(){return this.groupBrackets}get GraphicalMarkedAreas(){return this.graphicalMarkedAreas}get SystemLines(){return this.systemLines}get Id(){return this.id}createSystemLeftLine(t,e,i){let s=-t/2;i&&(s=this.maxLabelLength+e-t/2);const r=this.staffLines[0].Measures[0];let o;this.staffLines.length>1&&(o=this.staffLines[this.staffLines.length-1].Measures[0]);const a=this.createSystemLine(s,t,Et.SingleThin,ns.MeasureBegin,this,r,o);this.SystemLines.push(a),a.PositionAndShape.RelativePosition=new O(s,0),a.PositionAndShape.BorderLeft=0,a.PositionAndShape.BorderRight=t,a.PositionAndShape.BorderTop=0,a.PositionAndShape.BorderBottom=this.boundingBox.Size.height,this.createLinesForSystemLine(a)}createVerticalLineForMeasure(t,e,i,s,r,o){const a=o.ParentStaffLine,l=new O(a.PositionAndShape.RelativePosition.x,a.PositionAndShape.RelativePosition.y),h=a.ParentStaff.ParentInstrument.Staves;if(a.ParentStaff===h[0]){let c;h.length>1&&(c=this.getBottomStaffLine(a).Measures[r]);const u=this.createSystemLine(t,e,i,s,this,o,c),f=l.x+t;u.PositionAndShape.RelativePosition=new O(f,0),u.PositionAndShape.BorderLeft=0,u.PositionAndShape.BorderRight=e,this.SystemLines.push(u)}}setYPositionsToVerticalLineObjectsAndCreateLines(t){}calculateBorders(t){}alignBeginInstructions(){}GetLeftBorderAbsoluteXPosition(){return this.StaffLines[0].PositionAndShape.AbsolutePosition.x+this.StaffLines[0].Measures[0].beginInstructionsWidth}GetRightBorderAbsoluteXPosition(){return this.StaffLines[0].PositionAndShape.AbsolutePosition.x+this.StaffLines[0].StaffLines[0].End.x}AddGraphicalMeasures(t){for(let e=0,i=t.length;e1){let o,a;for(let l=0,h=this.staffLines.length;lthis.maxLabelLength&&(this.maxLabelLength=c.PositionAndShape.Size.width,e=r)}this.updateMusicSystemStaffLineXPosition(e)}setMusicSystemLabelsYPosition(){this.labels.forEach((t,e)=>{let i=0,s=0;for(let r=0;r0&&(e.PositionAndShape.RelativePosition=new O(0,i/s+2))})}checkStaffEntriesForStaffEntryLink(){let t=!1,e=!1;for(let i=0;i=0;i--){if(e=t.InstrumentalGroups[i],e instanceof Cr){if(e.Visible===!0)return e;continue}return this.findLastVisibleInstrumentInInstrumentalGroup(e)}}updateMusicSystemStaffLineXPosition(t){for(let e=0,i=this.StaffLines.length;e1}isVisible(){return this.ParentStaff.ParentInstrument.Visible}getGraphicalMeasureDurationFromStaffEntries(){let t=new W(0,1);const e=[];for(let i=0,s=this.staffEntries.length;i0&&o.Add(l.notes[0].graphicalNoteLength);t.lt(o)&&(t=W.createFromFraction(o))}return t}addGraphicalStaffEntry(t){this.staffEntries.push(t)}addGraphicalStaffEntryAtTimestamp(t){if(t)if(this.staffEntries.length===0||this.staffEntries[this.staffEntries.length-1].relInMeasureTimestamp.lt(t.relInMeasureTimestamp))this.staffEntries.push(t);else for(let e=this.staffEntries.length-1;e>=0;e--){if(this.staffEntries[e].relInMeasureTimestamp.lt(t.relInMeasureTimestamp)){this.staffEntries.splice(e+1,0,t);break}e===0&&this.staffEntries.splice(e,0,t)}}isPianoRightHand(){return this.isUpperStaffOfInstrument()}isPianoLeftHand(){return this.isLowerStaffOfInstrument()}isUpperStaffOfInstrument(){return this.parentStaff.ParentInstrument.Staves.length===1?!0:this.ParentStaff===this.parentStaff.ParentInstrument.Staves[0]}isLowerStaffOfInstrument(){return this.parentStaff.ParentInstrument.Staves.length===1?!1:this.ParentStaff===this.ParentStaff.ParentInstrument.Staves.last()}beginsWithLineRepetition(){const t=this.parentSourceMeasure;return t?t.beginsWithLineRepetition():!1}endsWithLineRepetition(){const t=this.parentSourceMeasure;return t?t.endsWithLineRepetition():!1}beginsWithWordRepetition(){const t=this.parentSourceMeasure;return t?t.beginsWithWordRepetition():!1}endsWithWordRepetition(){const t=this.parentSourceMeasure;return t?t.endsWithWordRepetition():!1}getTransposedHalftones(){return this.parentStaff.ParentInstrument.GetMusicSheet.Transpose+this.parentStaff.ParentInstrument.Transpose}}class $a extends Pa{constructor(t,e){super(t,e)}applyBordersFromVexflow(){const t=this.vfStaveNote;if(!t.getNoteHeadBeginX)return;const e=t.getBoundingBox(),i=t.getNoteHeadBeginX()-e.x;this.PositionAndShape.RelativePosition.y=e.y/_t,this.PositionAndShape.BorderTop=0,this.PositionAndShape.BorderBottom=e.h/_t,this.PositionAndShape.BorderLeft=-(i+t.width/2)/_t,this.PositionAndShape.BorderRight=(e.w-i)/_t}set vfStaveNote(t){this.mVexFlowStaveNote=t}get vfStaveNote(){return this.mVexFlowStaveNote}color(){var f;const t=this.rules.DefaultColorNotehead,e=this.rules.DefaultColorRest,i=this.rules.DefaultColorStem,s="#00000000";let r,o;const a=this.vfStaveNote;for(let d=0;dl.symbol_type===e))return;const a=new gt.Repetition(e,s,-this.rules.RepetitionSymbolsYOffset);this.stave.addModifier(a,i);return}this.addVolta(t)}addVolta(t){var i;let e=gt.Volta.type.BEGIN;if(t.type===q.Ending){switch(t.alignment){case Dt.Begin:this.parentSourceMeasure.endsRepetitionEnding()?e=gt.Volta.type.BEGIN_END:e=gt.Volta.type.BEGIN;break;case Dt.End:if(this.parentSourceMeasure.beginsRepetitionEnding())return;e=gt.Volta.type.END;break}const s=this.ParentStaffLine.SkyBottomLineCalculator,r=this.PositionAndShape.AbsolutePosition.x+this.PositionAndShape.BorderMarginLeft+.4,o=Math.max(this.PositionAndShape.AbsolutePosition.x+this.PositionAndShape.BorderMarginRight,r+.4),a=s.getSkyLineMinInRange(r,o)-2;let l=-6.1+this.rules.VoltaOffset,h=this.rules.VoltaOffset;a0){j.trace(`Ghost Found in between (measure ${this.MeasureNumber})`);const u=this.createGhostGves(c);i.splice(o,0,...u),o+=u.length}}else{const c=W.minus(l,this.parentSourceMeasure.AbsoluteTimestamp);if(c.RealValue>0){j.trace(`Ghost Found at start (measure ${this.MeasureNumber})`);const u=this.createGhostGves(c);i.splice(0,0,...u),o+=u.length}}e=h}const s=W.plus(this.parentSourceMeasure.AbsoluteTimestamp,this.parentSourceMeasure.Duration),r=W.minus(s,e);if(r.RealValue>0){j.trace(`Ghost Found at end (measure ${this.MeasureNumber})`);const o=this.createGhostGves(r);i=i.concat(o)}return i}createGhostGves(t){const e=Yt.GhostNotes(t),i=[];for(const s of e){const r=new $a(void 0,void 0);r.vfStaveNote=s,i.push(r)}return i}handleBeam(t,e){const i=t.sourceNote.ParentVoiceEntry.ParentVoice.VoiceId;let s=this.beams[i];s||(s=this.beams[i]=[]);let r;for(const a of s)a[0]===e&&(r=a);r||(r=[e,[]],s.push(r));const o=t.parentVoiceEntry;r[1].indexOf(o)<0&&r[1].push(o)}handleTuplet(t,e){const i=t.sourceNote.ParentVoiceEntry.ParentVoice.VoiceId;e=t.sourceNote.NoteTuplet;let s=this.tuplets[i];s||(s=this.tuplets[i]=[]);let r;for(const a of s)a[0]===e&&(r=a);r||(r=[e,[]],s.push(r));const o=t.parentVoiceEntry;r[1].indexOf(o)<0&&r[1].push(o)}finalizeBeams(){this.vfbeams={};const t=[];for(const e in this.beams)if(this.beams.hasOwnProperty(e)){let i=this.vfbeams[e];i||(i=this.vfbeams[e]=[]);for(const s of this.beams[e]){let r=!1;for(const d of s[0].Notes)if(d.Length.RealValue>=new W(1,4).RealValue&&(!d.TypeLength||d.TypeLength.RealValue>.125)){r=!0;break}if(r){j.debug("Beam between note >= quarter, likely tremolo, currently unsupported. continuing.");continue}const o=[],a=s[0],l=s[1];let h=!0;for(const d of l)d.parentVoiceEntry.ParentVoice===a.Notes[0].ParentVoiceEntry.ParentVoice&&(h=d.parentVoiceEntry.WantedStemDirection===Ft.Undefined);let c=!1,u;const f=[];for(const d of l){const p=d.vfStaveNote;p&&(o.push(p),t.push(p)),d.parentVoiceEntry.IsGrace&&(c=!0),d.parentVoiceEntry.StemColor&&this.rules.ColoringEnabled&&f.push(d.parentVoiceEntry.StemColor)}if(o.length>1){const d=new gt.Beam(o,h);if(c&&(d.render_options.beam_width=3,d.render_options.partial_beam_length=4),f.length>=2&&this.rules.ColorBeams){u=f[0];for(const p of f)if(p!==u){u=void 0;break}d.setStyle({fillStyle:u,strokeStyle:u})}this.rules.FlatBeams&&(d.render_options.flat_beams=!0,d.render_options.flat_beam_offset=this.rules.FlatBeamOffset,d.render_options.flat_beam_offset_per_beam=this.rules.FlatBeamOffsetPerBeam),i.push(d)}else j.debug("Warning! Beam with no notes!")}}this.rules.AutoBeamNotes&&this.autoBeamNotes(t)}autoBeamNotes(t){if(!this.rules.AutoBeamTabs&&this.isTabMeasure)return;let e=[],i=[],s,r=[];this.autoTupletVfBeams=[];const o=[];this.autoVfBeams=[];let a=this.parentSourceMeasure.ActiveTimeSignature;a||(a=this.parentSourceMeasure.Duration);for(const c of this.staffEntries)for(const u of c.graphicalVoiceEntries){const f=u.vfStaveNote,d=u.notes[0],p=c.relInMeasureTimestamp.isOnBeat(a),g=i.length>=2,m=d.sourceNote.Length.RealValue-new W(1,4).RealValue>-W.FloatInaccuracyTolerance,S=u.parentVoiceEntry.IsGrace||m||t.contains(f);if(S||p){if(g){for(const y of i)e.push(y);o.push(e.slice()),e=[]}if(i=[],S)continue}const b=u.notes[0].sourceNote.NoteTuplet;if(b){let y=!1;for(const x of b.Notes){for(const w of x)if(w.NoteTypeXml>=yo.QUARTER||w.ParentVoiceEntry.IsGrace||w.isRest()&&!this.rules.AutoBeamOptions.beam_rests){y=!0;break}if(y)break}if(!s)s=b;else if(s!==b){if(r.length>1){const x=new gt.Beam(r,!0);this.rules.FlatBeams&&(x.render_options.flat_beams=!0,x.render_options.flat_beam_offset=this.rules.FlatBeamOffset,x.render_options.flat_beam_offset_per_beam=this.rules.FlatBeamOffsetPerBeam),this.autoTupletVfBeams.push(x)}r=[],s=b}y||r.push(f);continue}else s=void 0;i.push(f)}if(r.length>=2){const c=new gt.Beam(r,!0);this.rules.FlatBeams&&(c.render_options.flat_beams=!0,c.render_options.flat_beam_offset=this.rules.FlatBeamOffset,c.render_options.flat_beam_offset_per_beam=this.rules.FlatBeamOffsetPerBeam),this.autoTupletVfBeams.push(c)}if(i.length>=2){for(const c of i)e.push(c);o.push(e)}const l=this.rules.AutoBeamOptions,h={beam_middle_only:l.beam_middle_rests_only,beam_rests:l.beam_rests,maintain_stem_directions:l.maintain_stem_directions};if(l.groups&&l.groups.length){const c=[];for(const u of l.groups)c.push(new gt.Fraction(u[0],u[1]));h.groups=c}for(const c of o){const u=gt.Beam.generateBeams(c,h);for(const f of u)this.rules.FlatBeams&&(f.render_options.flat_beams=!0,f.render_options.flat_beam_offset=this.rules.FlatBeamOffset,f.render_options.flat_beam_offset_per_beam=this.rules.FlatBeamOffsetPerBeam),this.autoVfBeams.push(f)}}finalizeTuplets(){this.vftuplets={};for(const t in this.tuplets)if(this.tuplets.hasOwnProperty(t)){let e=this.vftuplets[t];e||(e=this.vftuplets[t]=[]);for(const i of this.tuplets[t]){const s=[],r=i[1];for(const o of r)s.push(o.vfStaveNote);if(s.length>1){const o=i[0],a=o.Notes[0][0].NormalNotes,l=o.Bracket||o.TupletLabelNumber===3&&this.rules.TripletsBracketed||o.TupletLabelNumber!==3&&this.rules.TupletsBracketed;let h=gt.Tuplet.LOCATION_TOP;o.tupletLabelNumberPlacement===z.Below&&(h=gt.Tuplet.LOCATION_BOTTOM),e.push(new gt.Tuplet(s,{bracketed:l,location:h,notes_occupied:a,num_notes:o.TupletLabelNumber,ratioed:this.rules.TupletsRatioed}))}else j.debug("Warning! Tuplet with no notes! Trying to ignore, but this is a serious problem.")}}}layoutStaffEntry(t){}graphicalMeasureCreatedCalculations(){let t,e=[];const i=[];for(const r of this.staffEntries){t=!1,e=[];for(const o of r.graphicalVoiceEntries){if(o.parentVoiceEntry.IsGrace){e.push(o),i.push(o),t||(t=o.parentVoiceEntry.GraceSlur);continue}if(o.vfStaveNote=Yt.StaveNote(o),e.length>0){const a=[];for(let h=0;h0&&(c.GraceSlash=!1);const u=Yt.StaveNote(c);c.vfStaveNote=u,a.push(u)}const l=new gt.GraceNoteGroup(a,t);o.vfStaveNote.addModifier(0,l),e=[]}}}if(e.length>0)for(const r of e)r.vfStaveNote=Yt.StaveNote(r),r.parentVoiceEntry.GraceAfterMainNote=!0;this.finalizeBeams(),this.finalizeTuplets();const s=this.getVoicesWithinMeasure();if(this.rules.RenderFingerings)for(const r of this.staffEntries)r.setModifierXOffsets();for(const r of s){if(!r)continue;this.vfVoices[r.VoiceId]=new gt.Voice({beat_value:this.parentSourceMeasure.Duration.Denominator,num_beats:this.parentSourceMeasure.Duration.Numerator,resolution:gt.RESOLUTION}).setMode(gt.Voice.Mode.SOFT);const o=this.getRestFilledVexFlowStaveNotesPerVoice(r);for(const a of o){if(a.parentVoiceEntry&&a.parentVoiceEntry.IsGrace&&!a.parentVoiceEntry.GraceAfterMainNote)continue;const l=a;if(l.vfStaveNote.ticks.denominator===0)continue;if(a.notes.length===0||!a.notes[0]||!a.notes[0].sourceNote.PrintObject){this.vfVoices[r.VoiceId].addTickable(l.vfStaveNote);continue}const h=l.parentStaffEntry;if(h&&h.vfClefBefore){const c=new Su([h.vfClefBefore]);l.vfStaveNote.getCategory&&l.vfStaveNote.getCategory()==="stavenotes"&&l.vfStaveNote.addModifier(0,c)}a.parentVoiceEntry&&this.rules.RenderFingerings&&((this.rules.FingeringPosition===z.Left||this.rules.FingeringPosition===z.Right)&&this.createFingerings(a),this.createStringNumber(a)),this.createArpeggio(a),this.vfVoices[r.VoiceId].addTickable(l.vfStaveNote)}}this.setStemDirectionFromVexFlow();for(const r of i)this.createFingerings(r),this.createStringNumber(r),this.createArpeggio(r);this.createArticulations(),this.createOrnaments()}createArpeggio(t){if(t.parentVoiceEntry&&t.parentVoiceEntry.Arpeggio){const e=t.parentVoiceEntry.Arpeggio;if(t.notes&&t.notes.length>1){const i=Yt.StrokeTypeFromArpeggioType(e.type),s=new gt.Stroke(i,{all_voices:this.rules.ArpeggiosGoAcrossVoices});this.rules.RenderArpeggios&&t.vfStaveNote.addStroke(0,s)}else j.debug(`[OSMD] arpeggio in measure ${this.MeasureNumber} could not be drawn. voice entry had less than two notes, arpeggio is likely between voice entries, not currently supported in Vexflow.`)}}setStemDirectionFromVexFlow(){for(const t of this.staffEntries)for(const e of t.graphicalVoiceEntries)for(const i of e.notes){const s=i.vfnote;if(!s||!s[0])continue;switch(s[0].getStemDirection()){case gt.Stem.UP:e.parentVoiceEntry.StemDirection=Ft.Up;break;case gt.Stem.DOWN:e.parentVoiceEntry.StemDirection=Ft.Down;break}}}createArticulations(){for(let t=0,e=this.staffEntries.length;t1||t.parentStaffEntry.graphicalVoiceEntries.length>1?h=gt.StaveModifier.Position.LEFT:u.idInMusicSheet===0?(h=gt.StaveModifier.Position.ABOVE,a=z.Above):(h=gt.StaveModifier.Position.BELOW,a=z.Below)}const c=new gt.FretHandFinger(o.value);if(c.setPosition(h),c.setOffsetX(l),a===z.Above||a===z.Below){const u=a===z.Above?-1:1,f=a===z.Above?s:i-1-s;if(this.rules.FingeringInsideStafflines&&i>1){const d=c.getWidth()/2,p=i*2.5;c.setOffsetY(u*(f+p)*d)}else if(!this.rules.FingeringInsideStafflines){const d=new gt.StringNumber(o.value);d.radius=0,d.setPosition(h),d.setOffsetY(u*f*d.getWidth()*2/3),e.vfStaveNote.addModifier(s,d);continue}}e.vfStaveNote.addModifier(s,c)}}createStringNumber(t){if(!this.rules.RenderStringNumbersClassical)return;const e=t;t.notes.forEach((i,s)=>{const r=i.sourceNote.StringInstruction;if(r){let o=r.value;switch(o){case"1":o="I";break;case"2":o="II";break;case"3":o="III";break;case"4":o="IV";break;case"5":o="V";break;case"6":o="VI";break}const a=new gt.StringNumber(o);a.radius=0;const l=-this.rules.StringNumberOffsetY;t.notes.length>1||t.parentStaffEntry.graphicalVoiceEntries.length>1?(a.setOffsetX(i.baseStringNumberXOffset*13),a.setPosition(gt.Modifier.Position.RIGHT)):a.setPosition(gt.Modifier.Position.ABOVE),a.setOffsetY(l),e.vfStaveNote.addModifier(s,a)}})}lineTo(t,e){const i=new gt.StaveConnector(t.getVFStave(),this.stave);i.setType(e),this.connectors.push(i)}getVFStave(){return this.stave}updateInstructionWidth(){let t=0,e=0;const i=this.stave.getModifiers();for(const s of i)s.getPosition()===wn.BEGIN?t+=s.getWidth()+s.getPadding(void 0):s.getPosition()===wn.END&&(e+=s.getWidth()+s.getPadding(void 0));this.beginInstructionsWidth=(t!=null?t:0)/_t,this.endInstructionsWidth=(e!=null?e:0)/_t}addStaveTie(t,e){this.vfTies.push(t),e.vfTie=t}}var wn=(n=>(n[n.LEFT=1]="LEFT",n[n.RIGHT=2]="RIGHT",n[n.ABOVE=3]="ABOVE",n[n.BELOW=4]="BELOW",n[n.BEGIN=5]="BEGIN",n[n.END=6]="END",n))(wn||{});class yu extends Pe{constructor(t,e=void 0,i=void 0){super(),this.graphicalChordContainers=[],this.tabStaffEntry=void 0,this.MaxAccidentals=0,this.graphicalInstructions=[],this.ties=[],this.graphicalTies=[],this.lyricsEntries=[],this.parentMeasure=t,this.graphicalVoiceEntries=[],this.sourceStaffEntry=e,i?(this.staffEntryParent=i,this.parentVerticalContainer=i.parentVerticalContainer,this.PositionAndShape=new le(this,i.PositionAndShape)):this.PositionAndShape=new le(this,t.PositionAndShape),e&&(this.relInMeasureTimestamp=e.Timestamp),this.FingeringEntries=[]}get GraphicalInstructions(){return this.graphicalInstructions}get GraphicalTies(){return this.graphicalTies}get LyricsEntries(){return this.lyricsEntries}set LyricsEntries(t){this.lyricsEntries=t}getAbsoluteTimestamp(){const t=this.parentMeasure.parentSourceMeasure.AbsoluteTimestamp.clone();return this.relInMeasureTimestamp&&t.Add(this.relInMeasureTimestamp),t}findTieGraphicalNoteFromNote(t){for(const e of this.graphicalVoiceEntries)for(const i of e.notes){const s=i.sourceNote;if(!s.isRest()&&s.Pitch.FundamentalNote===t.Pitch.FundamentalNote&&s.Pitch.Octave===t.Pitch.Octave&&s.getAbsoluteTimestamp().Equals(t.getAbsoluteTimestamp()))return i}}findEndTieGraphicalNoteFromNoteWithStartingSlur(t,e){if(!!t){for(const i of this.graphicalVoiceEntries)if(i.parentVoiceEntry===t.ParentVoiceEntry)for(const s of i.notes){const r=s.sourceNote;if(r.NoteTie&&r.NoteSlurs.indexOf(e)!==-1)return s}}}findGraphicalNoteFromGraceNote(t){if(!!t){for(const e of this.graphicalVoiceEntries)if(e.parentVoiceEntry===t.ParentVoiceEntry){for(const i of e.notes)if(i.sourceNote===t)return i}}}findGraphicalNoteFromNote(t){if(!!t){for(const e of this.graphicalVoiceEntries)if(e.parentVoiceEntry===t.ParentVoiceEntry){for(const i of e.notes)if(i.sourceNote===t&&this.getAbsoluteTimestamp().Equals(t.getAbsoluteTimestamp()))return i}}}getGraphicalNoteDurationFromVoice(t){for(const e of this.graphicalVoiceEntries)if(e.parentVoiceEntry.ParentVoice===t)return e.notes[0].graphicalNoteLength;return new W(0,1)}findVoiceEntryGraphicalNotes(t){for(const e of this.graphicalVoiceEntries)if(e.parentVoiceEntry===t)return e.notes}isVoiceEntryPartOfLinkedVoiceEntry(t){if(this.sourceStaffEntry.Link)for(let e=0,i=this.sourceStaffEntry.Link.LinkStaffEntries.length;e0&&(t=s)}return t}findStaffEntryMaxNoteLength(){let t=new W(0,1);for(const e of this.graphicalVoiceEntries)for(const i of e.notes){const s=i.graphicalNoteLength;t.lt(s)&&s.GetExpandedNumerator()>0&&(t=s)}return t}findOrCreateGraphicalVoiceEntry(t){for(const i of this.graphicalVoiceEntries)if(i.parentVoiceEntry===t)return i;const e=Lt.symbolFactory.createVoiceEntry(t,this);return this.graphicalVoiceEntries.push(e),e}findOrCreateGraphicalVoiceEntryFromGraphicalNote(t){for(const i of this.graphicalVoiceEntries)if(i===t.parentVoiceEntry)return i;const e=Lt.symbolFactory.createVoiceEntry(t.sourceNote.ParentVoiceEntry,this);return this.graphicalVoiceEntries.push(e),e}addGraphicalNoteToListAtCorrectYPosition(t,e){const i=t.notes;if(i.length===0||e.PositionAndShape.RelativePosition.y=0;s--){if(i[s].PositionAndShape.RelativePosition.y>e.PositionAndShape.RelativePosition.y){i.splice(s+1,0,e);break}if(s===0){i.splice(0,0,e);break}}}hasOnlyRests(){for(const e of this.graphicalVoiceEntries)for(const i of e.notes)if(!i.sourceNote.isRest())return!1;return!0}getSkylineMin(){var s;const t=(s=this.parentMeasure)==null?void 0:s.ParentStaffLine.SkyBottomLineCalculator;if(!t)return;const[e,i]=this.getAbsoluteStartAndEnd();return t.getSkyLineMinInRange(e,i)}getHighestYAtEntry(){return this.parentMeasure.ParentStaffLine.PositionAndShape.AbsolutePosition.y+this.getSkylineMin()}getLowestYAtEntry(){return this.parentMeasure.ParentStaffLine.PositionAndShape.AbsolutePosition.y+this.getBottomlineMax()}getBottomlineMax(){var s;const t=(s=this.parentMeasure)==null?void 0:s.ParentStaffLine.SkyBottomLineCalculator;if(!t)return;const[e,i]=this.getAbsoluteStartAndEnd();return t.getBottomLineMaxInRange(e,i)}getAbsoluteStartAndEnd(){let t=this.PositionAndShape.AbsolutePosition.x;t-=this.parentMeasure.ParentStaffLine.PositionAndShape.AbsolutePosition.x;const e=t+this.PositionAndShape.Size.width;return[t,e]}}const xu=M.Flow;class vu extends yu{constructor(t,e,i){super(t,e,i)}calculateXPosition(){const t=this.parentMeasure.getVFStave();let e=0;for(const i of this.graphicalVoiceEntries)if(i.vfStaveNote){if(i.vfStaveNote.setStave(t),t&&t.getLines&&t.getLines()===1&&i.vfStaveNote.getStemDirection()<0&&(i.vfStaveNote.setStemDirection(xu.Stem.UP),i.parentVoiceEntry.StemDirection=Ft.Up),!i.vfStaveNote.preFormatted)continue;i.applyBordersFromVexflow(),this.parentMeasure.ParentStaff.isTab?this.PositionAndShape.RelativePosition.x=(i.vfStaveNote.getAbsoluteX()+i.vfStaveNote.glyph.getWidth())/_t:this.PositionAndShape.RelativePosition.x=i.vfStaveNote.getBoundingBox().getX()/_t;const s=i.notes[0].sourceNote;s.isRest()&&s.Length.RealValue===this.parentMeasure.parentSourceMeasure.ActiveTimeSignature.RealValue&&(this.PositionAndShape.RelativePosition.x+=this.parentMeasure.parentSourceMeasure.Rules.WholeRestXShiftVexflow-.1,i.PositionAndShape.BorderLeft=-.7,i.PositionAndShape.BorderRight=.7),i.PositionAndShape.BorderLeftr.staffLine),i=this.calculateModifierXOffsets(e,1),s=this.calculateModifierXOffsets(e,.5);t.forEach((r,o)=>{r.baseFingeringXOffset=s[o],r.baseStringNumberXOffset=i[o]})}calculateModifierXOffsets(t,e){const i=[];for(let s=0;s=0;a--){if(Math.abs(t[s]-t[a])<=e&&r===i[a]){r++,o=!0;break}o=!1}i.push(r)}return i}}class Bn extends qa{constructor(t,e,i,s=oe.NONE,r,o=void 0){if(super(t,e,r,o),this.clef=i,this.octaveShift=s,t.Pitch){const a=t.isRest()?t.Pitch:_n.getPitchFromOctaveShift(t.Pitch,s);this.vfpitch=Yt.pitch(a,t.isRest(),this.clef,this.sourceNote.Notehead),this.vfpitch[1]=void 0}}setAccidental(t){const e=this.drawPitch(t);this.vfpitch=Yt.pitch(e,this.sourceNote.isRest(),this.clef,this.sourceNote.Notehead),this.DrawnAccidental=e.Accidental}drawPitch(t){return _n.getPitchFromOctaveShift(t,this.octaveShift)}Transpose(t,e,i,s){const r=super.Transpose(t,e,i,s),o=_n.getPitchFromOctaveShift(r,this.octaveShift);return this.vfpitch=Yt.pitch(o,this.sourceNote.isRest(),this.clef,this.sourceNote.Notehead),this.vfpitch[1]=void 0,o}setIndex(t,e){this.vfnote=[t,e],this.vfnoteIndex=e}notehead(t=void 0){let e=t;e||(e=this.vfnote[0]);const i=e.note_heads;return i&&i.length>this.vfnoteIndex&&i[this.vfnoteIndex]?e.note_heads[this.vfnoteIndex]:{line:0}}Clef(){return this.clef}getSVGId(){if(!!this.vfnote)return this.vfnote[0].getAttribute("id")}getSVGGElement(){if(!!this.vfnote)return this.vfnote[0].getAttribute("el")}getStemSVG(){return document.getElementById("vf-"+this.getSVGId()+"-stem")}getBeamSVGs(){const t=[];for(let e=0;;e++){const i=document.getElementById(`vf-${this.getSVGId()}-beam${e}`);if(!i)break;t.push(i)}return t}}class _u extends Pe{constructor(t,e,i,s,r,o){super(),this.chordSymbolContainer=t,this.boundingBox=new le(this,e),this.rules=o,this.calculateLabel(i,r,s)}get GetChordSymbolContainer(){return this.chordSymbolContainer}get GraphicalLabel(){return this.graphicalLabel}calculateLabel(t,e,i){const s=Ka.calculateChordText(this.chordSymbolContainer,e,i);this.graphicalLabel=new Se(new jt(s),t,this.rules.ChordSymbolTextAlignment,this.rules,this.boundingBox),this.graphicalLabel.PositionAndShape.RelativePosition=new O(this.rules.ChordSymbolRelativeXOffset,0),this.graphicalLabel.Label.colorDefault=this.rules.DefaultColorChordSymbol}}const As=M.Flow;class wu extends Es{constructor(t,e=void 0,i=void 0){super(t,e,i),this.isTabMeasure=!0}resetLayout(){var e;const t=(e=this.ParentStaff.StafflineCount)!=null?e:6;this.stave=new As.TabStave(0,0,0,{space_above_staff_ln:0,space_below_staff_ln:0,num_lines:t}),this.updateInstructionWidth()}graphicalMeasureCreatedCalculations(){for(let e=0,i=this.staffEntries.length;e1){const a=Yt.StrokeTypeFromArpeggioType(o.type),l=new As.Stroke(a,{all_voices:this.rules.ArpeggiosGoAcrossVoices});this.rules.RenderArpeggios&&r.vfStaveNote.addStroke(0,l)}else j.debug(`[OSMD] arpeggio in measure ${this.MeasureNumber} could not be drawn. voice entry had less than two notes, arpeggio is likely between voice entries, not currently supported in Vexflow.`)}this.vfVoices[e.VoiceId].addTickable(r.vfStaveNote)}}}}class Eu extends Pe{constructor(t,e){super(),this.measures=[],this.staffLines=new Array(5),this.octaveShifts=[],this.lyricLines=[],this.lyricsDashes=[],this.abstractExpressions=[],this.graphicalSlurs=[],this.Pedals=[],this.WavyLines=[],this.parentMusicSystem=t,this.parentStaff=e,this.boundingBox=new le(this,t.PositionAndShape),this.skyBottomLine=Lt.symbolFactory.createSkyBottomLineCalculator(this),this.staffHeight=this.parentMusicSystem.rules.StaffHeight,this.topLineOffset=0,this.bottomLineOffset=4,this.calculateStaffLineOffsets()}calculateStaffLineOffsets(){if(this.ParentStaff.isTab)switch(this.ParentStaff.StafflineCount){case 5:this.staffHeight=this.bottomLineOffset=this.ParentStaff.ParentInstrument.GetMusicSheet.Rules.TabStaffInterlineHeight*6;break;default:this.staffHeight=this.bottomLineOffset=this.ParentStaff.ParentInstrument.GetMusicSheet.Rules.TabStaffInterlineHeight*this.ParentStaff.StafflineCount;break}else switch(this.ParentStaff.StafflineCount){case 4:this.bottomLineOffset=1;break;case 3:this.topLineOffset=1,this.bottomLineOffset=1;break;case 2:this.topLineOffset=2,this.bottomLineOffset=1;break;case 1:this.topLineOffset=2,this.bottomLineOffset=2;break}}get Measures(){return this.measures}set Measures(t){this.measures=t}get StaffLines(){return this.staffLines}set StaffLines(t){this.staffLines=t}get Index(){return this.parentMusicSystem.StaffLines.indexOf(this)}get NextStaffLine(){const t=this.Index;return t!==this.parentMusicSystem.StaffLines.length?this.parentMusicSystem.StaffLines[t+1]:void 0}get LyricLines(){return this.lyricLines}get AbstractExpressions(){return this.abstractExpressions}set AbstractExpressions(t){this.abstractExpressions=t}set LyricLines(t){this.lyricLines=t}get LyricsDashes(){return this.lyricsDashes}set LyricsDashes(t){this.lyricsDashes=t}get ParentMusicSystem(){return this.parentMusicSystem}set ParentMusicSystem(t){this.parentMusicSystem=t}get ParentStaff(){return this.parentStaff}set ParentStaff(t){this.parentStaff=t}get SkyBottomLineCalculator(){return this.skyBottomLine}get SkyLine(){return this.skyBottomLine.SkyLine}get BottomLine(){return this.skyBottomLine.BottomLine}get OctaveShifts(){return this.octaveShifts}set OctaveShifts(t){this.octaveShifts=t}get StaffHeight(){return this.staffHeight}get TopLineOffset(){return this.topLineOffset}get BottomLineOffset(){return this.bottomLineOffset}get GraphicalSlurs(){return this.graphicalSlurs}addSlurToStaffline(t){this.graphicalSlurs.push(t)}addActivitySymbolClickArea(){const t=new wa(this),e=this.PositionAndShape;t.PositionAndShape.RelativePosition=new O(e.RelativePosition.x+e.BorderRight+.5,e.RelativePosition.y+.5),t.PositionAndShape.Parent=this.parentMusicSystem.PositionAndShape}isPartOfMultiStaffInstrument(){return this.parentStaff.ParentInstrument.Staves.length>1}findClosestStaffEntry(t){let e;for(let i=0,s=this.Measures.length;i0){const o=r.map(l=>l.PositionAndShape.Center.y),a=Math.max(...o);for(let l=0;l0?r[l-1]:void 0;if(u){const d=this.getOverlap(h.PositionAndShape,u.PositionAndShape);h.squeeze(-(d.x+this.rules.DynamicExpressionSpacer))}if(f){const d=this.getOverlap(f.PositionAndShape,h.PositionAndShape);h.squeeze(d.x+this.rules.DynamicExpressionSpacer)}}}}}getDistance(t,e){const i=t.RelativePosition.x+t.BorderMarginRight,s=e.RelativePosition.x+e.BorderMarginLeft,r=t.RelativePosition.y+t.BorderMarginBottom,o=e.RelativePosition.y+e.BorderMarginTop;return new O(s-i,o-r)}getOverlap(t,e){return new O(t.RelativePosition.x+t.BorderMarginRight-(e.RelativePosition.x+e.BorderMarginLeft),t.RelativePosition.y+t.BorderMarginBottom-(e.RelativePosition.y+e.BorderMarginTop))}}class Pu extends Eu{constructor(t,e){super(t,e),this.slursInVFStaffLine=[],this.alignmentManager=new Mu(this)}get SlursInVFStaffLine(){return this.slursInVFStaffLine}addVFSlurToVFStaffline(t){this.slursInVFStaffLine.push(t)}get AlignmentManager(){return this.alignmentManager}}const Lu=M.Flow;class Tu extends Es{constructor(t,e=void 0,i=void 0){super(t,e,i),this.minimumStaffEntriesWidth=-1,i?this.rules=i.ParentMusicSystem.rules:e&&(this.rules=e.Rules),this.resetLayout(),this.multiRestElement=new Lu.MultiMeasureRest(e.multipleRestMeasures,{})}draw(t){var r,o,a,l,h;const e=t.openGroup();(r=e==null?void 0:e.classList)==null||r.add("vf-measure");const i=t.openGroup();(o=i==null?void 0:i.classList)==null||o.add("vf-stave"),i==null||i.setAttribute("id",(l=(a=this.stave)==null?void 0:a.attrs)==null?void 0:l.id),this.stave.setContext(t).draw(),t.closeGroup();const s=t.openGroup();(h=s==null?void 0:s.classList)==null||h.add("vf-voices"),this.multiRestElement.setStave(this.stave),this.multiRestElement.setContext(t),this.multiRestElement.draw(),t.closeGroup();for(const c of this.connectors)c.setContext(t).draw();return t.closeGroup(),e}format(){}getVoicesWithinMeasure(){return[]}getGraphicalVoiceEntriesPerVoice(t){return[]}getRestFilledVexFlowStaveNotesPerVoice(t){return[]}handleBeam(t,e){}handleTuplet(t,e){}finalizeBeams(){}finalizeTuplets(){}layoutStaffEntry(t){}graphicalMeasureCreatedCalculations(){}createArticulations(){}createOrnaments(){}createFingerings(t){}getVFStave(){return this.stave}}const Cu=M.Flow;class el{getInnerElement(){return this.inner}getCanvas(){return this.canvas}getRenderElement(){let t=this.canvas;return this.getVexflowBackendType()===Cu.Renderer.Backends.CANVAS&&(t=this.inner),t}getRenderer(){return this.renderer}removeAllChildrenFromContainer(t){for(;t.children.length!==0;)t.removeChild(t.children.item(0))}removeFromContainer(t){const e=this.getRenderElement();for(let i=0;i \r<`)),r.download="opensheetmusicdisplay_download.svg",r.innerHTML=window.location.href+"/download",document.body.appendChild(r)}}class Nu extends Ya{constructor(t,e,i){super(t,e,i);const s=new jt(this.Expression);this.label=new Se(s,this.rules.ContinuousDynamicTextHeight,vt.CenterCenter,this.rules,this.PositionAndShape),this.label.Label.fontStyle=ue.BoldItalic,this.label.setLabelPositionAndShapeBorders(),this.PositionAndShape.calculateBoundingBox()}get InstantaneousDynamic(){return this.mInstantaneousDynamicExpression}get Expression(){return ie[this.mInstantaneousDynamicExpression.DynEnum]}}class Au extends Pe{constructor(t,e){super(),this.getOctaveShift=t,this.setSymbol(),this.PositionAndShape=new le(this,e)}setSymbol(){switch(this.getOctaveShift.Type){case oe.VA8:this.octaveSymbol=Ge.VA8;break;case oe.VB8:this.octaveSymbol=Ge.VB8;break;case oe.MA15:this.octaveSymbol=Ge.MA15;break;case oe.MB15:this.octaveSymbol=Ge.MB15;break;default:throw new Li("")}}}const Is=M.Flow;class na extends Au{constructor(t,e){switch(super(t,e),t.Type){case oe.VA8:this.position=Is.TextBracket.Positions.TOP,this.supscript="va",this.text="8";break;case oe.MA15:this.position=Is.TextBracket.Positions.TOP,this.supscript="ma",this.text="15";break;case oe.VB8:this.position=Is.TextBracket.Positions.BOTTOM,this.supscript="vb",this.text="8";break;case oe.MB15:this.position=Is.TextBracket.Positions.BOTTOM,this.supscript="mb",this.text="15";break;default:j.error("Unknown or NONE octaveshift. This should not be called!");break}}setStartNote(t){for(const e of t.graphicalVoiceEntries){const i=e;if(i!=null&&i.vfStaveNote)return this.startNote=i.vfStaveNote,!0}return!1}setEndNote(t){for(const e of t.graphicalVoiceEntries){const i=e;if(i!=null&&i.vfStaveNote)return this.endNote=i.vfStaveNote,!0}return!1}getTextBracket(){return new Is.TextBracket({position:this.position,start:this.startNote,stop:this.endNote,superscript:this.supscript,text:this.text})}}class qs{constructor(t){this.staffPitchListMapping=new Ye,this.baseLineNote=ut.B,this.baseLineOctave=1,this.rules=t}trackNote(t){if(!(t instanceof Bn)||t.Clef().ClefType!==Pt.percussion||t.sourceNote.isRest()||this.rules.PercussionOneLineCutoff===0||this.rules.PercussionForceVoicesOneLineCutoff===-1)return;const e=t.parentVoiceEntry.parentStaffEntry.sourceStaffEntry.ParentStaff.idInMusicSheet;let i;this.staffPitchListMapping.containsKey(e)||this.staffPitchListMapping.setValue(e,new Array),i=this.staffPitchListMapping.getValue(e);const s=t.sourceNote.Pitch;qs.findOrInsert(i,s)}static PitchIndexOf(t,e,i=0){if(i>t.length-1)return-1;for(let s=i;sthis.rules.PercussionOneLineCutoff&&!s)return t;const r=t,o=t.sourceNote.Pitch;let a=this.baseLineNote,l=this.baseLineOctave;if(this.rules.PercussionUseXMLDisplayStep&&t.sourceNote.displayStepUnpitched!==void 0&&(a=t.sourceNote.displayStepUnpitched,l=t.sourceNote.displayOctaveUnpitched+this.rules.PercussionOneLineXMLDisplayStepOctaveOffset),i.length<=this.rules.PercussionForceVoicesOneLineCutoff)r.setAccidental(new Kt(a,l,o.Accidental));else{const h=qs.PitchIndexOf(i,o);if(h>-1){const c=Math.ceil(i.length/2);if(!this.rules.PercussionUseXMLDisplayStep)if(h>=c)switch(l=2,(h-c)%5){case 1:a=ut.E;break;case 2:a=ut.G;break;case 3:a=ut.B;break;case 4:a=ut.D,l=3;break;default:a=ut.C;break}else switch(h%5){case 1:a=ut.F;break;case 2:a=ut.D;break;case 3:a=ut.B,l=0;break;case 4:a=ut.G,l=0;break;default:a=ut.A;break}const u=new Kt(a,l,o.Accidental);r.setAccidental(u);const f=r.parentVoiceEntry.parentVoiceEntry;!this.rules.SetWantedStemDirectionByXml&&f.Notes.length<2&&(u.Octave>this.baseLineOctave||u.FundamentalNote===this.baseLineNote&&u.Octave===this.baseLineOctave?r.parentVoiceEntry.parentVoiceEntry.WantedStemDirection=Ft.Up:r.parentVoiceEntry.parentVoiceEntry.WantedStemDirection=Ft.Down)}}return r}getStafflineUniquePositionCount(t){return this.staffPitchListMapping.containsKey(t)?this.staffPitchListMapping.getValue(t).length:0}}class sl{constructor(t){this.mStaffLineParent=t,this.mRules=t.ParentMusicSystem.rules}calculateLines(){const t=Math.max(Math.ceil(this.StaffLineParent.PositionAndShape.Size.width*this.SamplingUnit),1);this.mSkyLine=[],this.mBottomLine=[];const e=new il(this.StaffLineParent.ParentMusicSystem.rules);for(const o of this.StaffLineParent.Measures){o.PositionAndShape.calculateAbsolutePositionsRecursive(0,0);const a=o.getVFStave();let l=a.getWidth();if(!(l>0)&&!o.IsExtraGraphicalMeasure&&(j.warn("SkyBottomLineCalculator: width not > 0 in measure "+o.MeasureNumber),l=50),!(l>=50)&&o.IsExtraGraphicalMeasure)continue;e.initializeHeadless(l);const h=e.getContext(),c=e.getCanvas();l=c.width;const u=c.height;this.mRules.DYMusicScoreType==="jianpu"?a.setY(a.y-50):a.setY(a.y+100);const f=a.getWidth();a.setWidth(l),o.format(),a.setWidth(f);try{o.draw(h)}catch(b){j.warn("SkyBottomLineCalculator.calculateLines.draw",b)}const d=h.getImageData(0,0,l,u),p=4,g=Math.max(Math.ceil(o.PositionAndShape.Size.width*this.mRules.SamplingUnit),1),m=new Array(g),S=new Array(g);for(let b=0;b0){m[b]=y;break}}for(let y=u;y>0;y--){const w=y*l*p+b*p;if(d.data[w+3]>0){S[b]=y;break}}}for(let b=0;b(o-Math.max(...this.mSkyLine))/_t+this.StaffLineParent.TopLineOffset),this.mBottomLine=this.mBottomLine.map(o=>(o-Math.min(...this.mBottomLine))/_t+this.StaffLineParent.BottomLineOffset)}findPreviousValidNumber(t,e){for(let i=t;i>=0;i--)if(!isNaN(e[i]))return e[i];return 0}findNextValidNumber(t,e){if(t>=e.length)return e[t-1];for(let i=t;i=this.BottomLine.length&&(i=this.BottomLine.length-1),s<0&&(s=0),s>=this.BottomLine.length&&(s=this.BottomLine.length),this.SkyLine[i]=t.y;for(let o=i+1;o=this.BottomLine.length&&(i=this.BottomLine.length-1),s<0&&(s=0),s>=this.BottomLine.length&&(s=this.BottomLine.length),this.BottomLine[i]=t.y;for(let o=i+1;ot)}setBottomLineWithValue(t){this.BottomLine.forEach(e=>t)}getLeftIndexForPointX(t,e){const i=Math.floor(t*this.SamplingUnit);return i<0?0:i>=e?e-1:i}getRightIndexForPointX(t,e){const i=Math.ceil(t*this.SamplingUnit);return i<0?0:i>=e?e-1:i}updateStaffLineBorders(){this.mStaffLineParent.PositionAndShape.BorderTop=this.getSkyLineMin(),this.mStaffLineParent.PositionAndShape.BorderMarginTop=this.getSkyLineMin(),this.mStaffLineParent.PositionAndShape.BorderBottom=this.getBottomLineMax(),this.mStaffLineParent.PositionAndShape.BorderMarginBottom=this.getBottomLineMax()}getSkyLineMin(){return Math.min(...this.SkyLine.filter(t=>!isNaN(t)))}getSkyLineMinAtPoint(t){const e=Math.round(t*this.SamplingUnit);return this.mSkyLine[e]}getSkyLineMinInRange(t,e){return this.getMinInRange(this.SkyLine,t,e)}getBottomLineMax(){return Math.max(...this.BottomLine.filter(t=>!isNaN(t)))}getBottomLineMaxAtPoint(t){const e=Math.round(t*this.SamplingUnit);return this.mBottomLine[e]}getBottomLineMaxInRange(t,e){return this.getMaxInRange(this.BottomLine,t,e)}getBottomLineMaxInBoundingBox(t){const e=Math.floor(t.AbsolutePosition.x+t.BorderLeft),i=Math.ceil(t.AbsolutePosition.x+t.BorderRight);return this.getMaxInRange(this.mBottomLine,e,i)}updateWithBoundingBoxRecursively(t){if(t.ChildElements&&t.ChildElements.length>0)for(const e of t.ChildElements)this.updateWithBoundingBoxRecursively(e);else{const e=t.BorderTop+t.AbsolutePosition.y,i=t.BorderBottom+t.AbsolutePosition.y;if(e<0){const s=Math.floor(t.AbsolutePosition.x+t.BorderLeft),r=Math.ceil(t.AbsolutePosition.x+t.BorderRight);this.updateInRange(this.mSkyLine,s,r,e)}else if(i>this.StaffLineParent.StaffHeight){const s=Math.floor(t.AbsolutePosition.x+t.BorderLeft),r=Math.ceil(t.AbsolutePosition.x+t.BorderRight);this.updateInRange(this.mBottomLine,s,r,i)}}}updateInRange(t,e=0,i=t.length,s=0){if(e=Math.floor(e*this.SamplingUnit),i=Math.ceil(i*this.SamplingUnit),it.length&&(i=t.length);for(let r=e;rMath.abs(t[r])?s:t[r]}setInRange(t,e=0,i=t.length,s=0){if(e=Math.floor(e*this.SamplingUnit),i=Math.ceil(i*this.SamplingUnit),it.length&&(i=t.length);for(let r=e;r=t.length&&(e=t.length-1),i<0&&(i=0),i>=t.length&&(i=t.length),e>=0&&i<=t.length)return Math.min(...t.slice(e,i+1))}getMaxInRange(t,e,i){if(e=Math.floor(e*this.SamplingUnit),i=Math.ceil(i*this.SamplingUnit),!t)return Number.MIN_VALUE;if(e<0&&(e=0),e>=t.length&&(e=t.length-1),i<0&&(i=0),i>=t.length&&(i=t.length),e>=0&&i<=t.length)return Math.max(...t.slice(e,i+1))}get SamplingUnit(){return this.mRules.SamplingUnit}get StaffLineParent(){return this.mStaffLineParent}get SkyLine(){return this.mSkyLine}get BottomLine(){return this.mBottomLine}}var nl={exports:{}};/*! * d-path-parser - v1.0.0 * by Massimo Artizzu (MaxArt2501) * * https://github.com/MaxArt2501/d-path-parser * * Licensed under the MIT License * See LICENSE for details */(function(n,t){(function(e,i){n.exports=i()})(We,function(){return function(i){for(var s={command:/\s*([achlmqstvz])/gi,number:/\s*([+-]?\d*\.?\d+(?:e[+-]?\d+)?)/gi,comma:/\s*(?:(,)|\s)/g,flag:/\s*([01])/g},r={number:function(g){return+d("number",g)},"coordinate pair":function(g){var m=d("number",g);if(m===null&&!g)return null;d("comma");var S=d("number",!0);return{x:+m,y:+S}},"arc definition":function(g){var m=r["coordinate pair"](g);if(!m&&!g)return null;d("comma");var S=+d("number",!0);d("comma",!0);var b=!!+d("flag",!0);d("comma");var y=!!+d("flag",!0);d("comma");var x=r["coordinate pair"](!0);return{radii:m,rotation:S,large:b,clockwise:y,end:x}}},o=0,a=[];oe.bottom)switch(t.tagName.toLowerCase()){case"g":for(const f of t.children)this.recursiveUpdate(f,e,i,s);break;case"circle":case"rect":case"line":case"path":let c=Math.floor((r.x-i.x)/_t*this.mRules.SamplingUnit);const u=c+Math.ceil(r.width/_t*this.mRules.SamplingUnit);if(t.parentElement.classList.contains("vf-beams")&&t.hasAttribute("d")){const f=Iu(t.getAttribute("d"));if(f.length===5){const d=f[0],p=f[3],g=(p.end.y-d.end.y)/(p.end.x-d.end.x);let m=d.end.y/_t;for(c;c<=u;c++)mh[c]&&(h[c]=m),m+=g/this.mRules.SamplingUnit}}else for(c;c<=u;c++)oh[c]&&(h[c]=a);break}}calculateLinesForMeasure(t,e){var T,E,C;const i=e.getBBox(),s=Math.max(Math.round(t.PositionAndShape.Size.width*this.mRules.SamplingUnit),1),r=i.height/_t,a=e.getElementsByClassName("vf-stave")[0].getBBox();let l=(a==null?void 0:a.height)/_t,h=(a==null?void 0:a.y)/_t;const c=t.getVFStave();let u=((T=c.options)!=null&&T.num_lines?c.options.num_lines:5)-1,f=-1,d=0;const p=[u];for(const P of(E=c.options)==null?void 0:E.line_config)P.visible?(f===-1&&(f=d),p.push(d)):u--,d++;const g=p.pop();f===-1&&(f=0),u=g-f;const m=(C=c.options)==null?void 0:C.spacing_between_lines_px,S=u*m/_t;l-S>.2&&(l=S,h=f*m/_t);const b=h+l,y=new Array(s).fill(h),x=new Array(s).fill(b),w=[y,x];if(r>l)for(const P of e.children)this.recursiveUpdate(P,{top:h,bottom:b},i,[y,x]);return w}calculateLines(){this.mSkyLine=[],this.mBottomLine=[];const t=document.createElement("div");document.body.append(t);const e=new Rr(this.mRules);e.initialize(t,1,"0");const i=e.getContext(),s=i.openGroup();s.classList.add("staffline");for(const r of this.StaffLineParent.Measures){r.PositionAndShape.calculateAbsolutePositionsRecursive(0,0),r.setAbsoluteCoordinates(r.PositionAndShape.AbsolutePosition.x*_t,r.PositionAndShape.AbsolutePosition.y*_t);const o=r.draw(i),[a,l]=this.calculateLinesForMeasure(r,o);this.mSkyLine.push(...a),this.mBottomLine.push(...l)}i.closeGroup();for(const r of s.getElementsByClassName("vf-ties"))for(const o of r.childNodes)if(o.nodeName.toLowerCase()==="path"){const a=o.getBBox();let l=Math.floor(a.x/_t*this.mRules.SamplingUnit);const h=l+Math.ceil(a.width/_t*this.mRules.SamplingUnit),c=a.y/_t,u=a.height/_t+c;for(l;l<=h;l++)cthis.mBottomLine[l]&&(this.mBottomLine[l]=u)}e.clear(),t.remove()}}const Bu=M.Flow;class Du{constructor(){this.hasBBox=!1,document.createElementNS("http://www.w3.org/2000/svg","g").getBBox!==void 0&&(this.hasBBox=!0)}createMusicSystem(t,e){return new gu(t,e)}createStaffLine(t,e){return new Pu(t,e)}createSkyBottomLineCalculator(t){return t.ParentMusicSystem.rules.PerformanceMode&&this.hasBBox?new ku(t):new sl(t)}createGraphicalMeasure(t,e,i=!1){return new Es(e,t,void 0)}createMultiRestMeasure(t,e,i){return new Tu(e,t,i)}createTabStaffMeasure(t,e){return new wu(e,t)}createExtraGraphicalMeasure(t){const e=new Es(t.ParentStaff,void 0,t);return e.IsExtraGraphicalMeasure=!0,e.ExtraGraphicalMeasurePreviousMeasure=t.Measures.last(),e}createStaffEntry(t,e){return new vu(e,t,void 0)}createVoiceEntry(t,e){return new $a(t,e)}createNote(t,e,i,s=oe.NONE,r,o=void 0){return new Bn(t,e,i,s,r,o)}createGraceNote(t,e,i,s,r=oe.NONE){return new Bn(t,e,i,r,s)}addGraphicalAccidental(t,e){t.setAccidental(e)}addFermataAtTiedEndNote(t,e){}createInStaffClef(t,e){const i=t,s=Yt.Clef(e,"small");i.vfClefBefore=new Bu.ClefNote(s.type,s.size,s.annotation)}createChordSymbols(t,e,i,s){const r=e.parentMeasure.parentSourceMeasure.Rules;let o=0;const a=r.ChordSymbolXSpacing;for(const l of t.ChordContainers){const h=new _u(l,e.PositionAndShape,r.ChordSymbolTextHeight,i,s,e.parentMeasure.parentSourceMeasure.Rules),c=h.GraphicalLabel;c.PositionAndShape.RelativePosition.y-=r.ChordSymbolYOffset,c.PositionAndShape.RelativePosition.x+=o,c.setLabelPositionAndShapeBorders(),h.PositionAndShape.calculateBoundingBox(),e.graphicalChordContainers.push(h),o+=c.PositionAndShape.Size.width+a}}createGraphicalTechnicalInstruction(t,e){}}class Fu{constructor(t,e=void 0,i=void 0){this.tie=t,this.startNote=e,this.endNote=i}get SVGElement(){return this.vfTie.getAttribute("el")}get GetTie(){return this.tie}get StartNote(){return this.startNote}get Tie(){return this.tie}set StartNote(t){this.startNote=t}get EndNote(){return this.endNote}set EndNote(t){this.endNote=t}}class Yi{constructor(t,e,i,s){this.lyricsEntry=t,this.graphicalStaffEntry=e;const r=e.parentMeasure.parentSourceMeasure.Rules.LyricsAlignmentStandard;t.Text.length>=4&&t.Parent.Notes[0].Length.Denominator>4&&vt.LeftBottom;const o=new jt(t.Text);this.graphicalLabel=new Se(o,i,r,this.graphicalStaffEntry.parentMeasure.parentSourceMeasure.Rules,e.PositionAndShape),this.graphicalLabel.PositionAndShape.RelativePosition=new O(0,s),r===vt.LeftBottom&&(this.graphicalLabel.PositionAndShape.RelativePosition.x-=1)}get LyricsEntry(){return this.lyricsEntry}get ParentLyricWord(){return this.graphicalLyricWord}set ParentLyricWord(t){this.graphicalLyricWord=t}get GraphicalLabel(){return this.graphicalLabel}set GraphicalLabel(t){this.graphicalLabel=t}get StaffEntryParent(){return this.graphicalStaffEntry}set StaffEntryParent(t){this.graphicalStaffEntry=t}}class Ou{constructor(t){this.graphicalLyricsEntries=[],this.lyricWord=t,this.initialize()}get GetLyricWord(){return this.lyricWord}get GraphicalLyricsEntries(){return this.graphicalLyricsEntries}set GraphicalLyricsEntries(t){this.graphicalLyricsEntries=t}isFilled(){for(let t=0;t=re.bezierCurveStepSize?new O:new O(re.oneMinusTPow3[t]*this.bezierStartPt.x+re.bezierFactorOne[t]*this.bezierStartControlPt.x+re.bezierFactorTwo[t]*this.bezierEndControlPt.x+re.tPow3[t]*this.bezierEndPt.x,re.oneMinusTPow3[t]*this.bezierStartPt.y+re.bezierFactorOne[t]*this.bezierStartControlPt.y+re.bezierFactorTwo[t]*this.bezierEndControlPt.y+re.tPow3[t]*this.bezierEndPt.y)}};let rl=re;rl.bezierCurveStepSize=1e3;const qi=class extends rl{constructor(n,t){super(),this.staffEntries=[],this.slur=n,this.rules=t}static Compare(n,t){if(n.staffEntries.length<1)return-1;if(t.staffEntries.length<1)return 1;const e=W.minus(n.staffEntries[n.staffEntries.length-1].getAbsoluteTimestamp(),n.staffEntries[0].getAbsoluteTimestamp()),i=W.minus(t.staffEntries[t.staffEntries.length-1].getAbsoluteTimestamp(),t.staffEntries[0].getAbsoluteTimestamp());return e.RealValue>i.RealValue?1:i.RealValue>e.RealValue?-1:0}calculateCurve(n){const t=this.staffEntries[0],e=this.staffEntries[this.staffEntries.length-1];let i=t.findGraphicalNoteFromNote(this.slur.StartNote);!i&&this.graceStart&&(i=t.findGraphicalNoteFromGraceNote(this.slur.StartNote)),i||(i=t.findEndTieGraphicalNoteFromNoteWithStartingSlur(this.slur.StartNote,this.slur));let s=e.findGraphicalNoteFromNote(this.slur.EndNote);!s&&this.graceEnd&&(s=e.findGraphicalNoteFromGraceNote(this.slur.EndNote));const r=t.parentMeasure.ParentStaffLine,o=r.SkyBottomLineCalculator;this.calculatePlacement(o,r);const a=this.calculateStartAndEnd(i,s,r,n,o),l=a.startX,h=a.endX;let c=a.startY,u=a.endY;const f=n.SlurTangentMinAngle,d=n.SlurTangentMaxAngle;let p;if(this.placement===z.Above){c-=n.SlurNoteHeadYOffset,u-=n.SlurNoteHeadYOffset;const g=new O(this.staffEntries[0].parentMeasure.PositionAndShape.RelativePosition.x+this.staffEntries[0].PositionAndShape.RelativePosition.x,c);i?g.x+=this.staffEntries[0].PositionAndShape.BorderRight:g.x=this.staffEntries[0].parentMeasure.beginInstructionsWidth,this.graceStart&&(g.x+=e.PositionAndShape.RelativePosition.x);const m=new O(this.staffEntries[this.staffEntries.length-1].parentMeasure.PositionAndShape.RelativePosition.x+this.staffEntries[this.staffEntries.length-1].PositionAndShape.RelativePosition.x,u);if(s?m.x+=this.staffEntries[this.staffEntries.length-1].PositionAndShape.BorderLeft:m.x=this.staffEntries[this.staffEntries.length-1].parentMeasure.PositionAndShape.RelativePosition.x+this.staffEntries[this.staffEntries.length-1].parentMeasure.PositionAndShape.Size.width,this.graceEnd&&(m.x+=e.staffEntryParent.PositionAndShape.RelativePosition.x),p=this.calculateTopPoints(g,m,r,o),p.length===0){const ct=new O((m.x-g.x)/2+g.x,(m.y-g.y)/2+g.y);p.push(ct)}const S=Math.atan((u-c)/(h-l)),b=new O(0,0);let y=new O(h-l,-(u-c));const x=js.getRotationMatrix(S),w=x.getTransposeMatrix();y=x.vectorMultiplication(y);const T=this.calculateTranslatedAndRotatedPointListAbove(p,l,c,x);let E=this.calculateMaxLeftSlope(T,b,y),C=this.calculateMaxRightSlope(T,b,y);const P=b.y-b.x*E,I=y.y-y.x*C,F=new O;let L=!1;Math.abs(Math.abs(E)-Math.abs(C))<1e-4?(F.x=y.x/2,F.y=0,L=!0):(F.x=(I-P)/(E-C),F.y=E*F.x+P);const k=this.calculateHeightWidthRatio(y.x,T);let v=0,G=0;if(Math.abs(k)>.001){const ct=Math.abs(E/(k*2)),Nt=Math.abs(E);v=Math.max(0,Nt*(Math.min(10,ct-1)/10)),E-=v;const pt=Math.abs(C/(k*2)),dt=Math.abs(C);G=Math.max(0,dt*(Math.min(10,pt-1)/10)),C+=G}let et=f,H=-f;if(!L){const ct=this.calculateAngles(f,E,C,d);et=ct.startAngle,H=ct.endAngle}const nt=this.calculateControlPoints(y.x,et,H,T,k,c,u);let K=nt.startControlPoint,lt=nt.endControlPoint;K=w.vectorMultiplication(K),K.x+=l,K.y=-K.y+c,lt=w.vectorMultiplication(lt),lt.x+=l,lt.y=-lt.y+c,this.bezierStartPt=new O(l,c-v),this.bezierStartControlPt=new O(K.x,K.y-v),this.bezierEndControlPt=new O(lt.x,lt.y-G),this.bezierEndPt=new O(h,u-G);const A=r.SkyLine.length,B=o.getLeftIndexForPointX(this.bezierStartPt.x,A),ot=o.getLeftIndexForPointX(this.bezierEndPt.x,A),rt=this.bezierEndPt.x-this.bezierStartPt.x,J=o.SamplingUnit;for(let ct=B;ct=B&&(r.SkyLine[dt]=Math.min(r.SkyLine[dt],pt.y)),dt++,dt.001){const ct=Math.abs(E/(k*2)),Nt=Math.abs(E);v=Math.max(0,Nt*(Math.min(10,ct-1)/10)),E-=v;const pt=Math.abs(C/(k*2)),dt=Math.abs(C);G=Math.max(0,dt*(Math.min(10,pt-1)/10)),C+=G}let et=f,H=-f;if(!L){const ct=this.calculateAngles(f,E,C,d);et=ct.startAngle,H=ct.endAngle}const nt=this.calculateControlPoints(y.x,et,H,T,k,c,u);let K=nt.startControlPoint,lt=nt.endControlPoint;K=w.vectorMultiplication(K),K.x+=l,K.y+=c,lt=w.vectorMultiplication(lt),lt.x+=l,lt.y+=c,this.bezierStartPt=new O(l,c+v),this.bezierStartControlPt=new O(K.x,K.y+v),this.bezierEndControlPt=new O(lt.x,lt.y+G),this.bezierEndPt=new O(h,u+G);const A=r.BottomLine.length,B=o.getLeftIndexForPointX(this.bezierStartPt.x,A),ot=o.getLeftIndexForPointX(this.bezierEndPt.x,A),rt=this.bezierEndPt.x-this.bezierStartPt.x,J=o.SamplingUnit;for(let ct=B;ct=B&&(r.BottomLine[dt]=Math.max(r.BottomLine[dt],pt.y)),dt++,dt0){this.placement=z.Above;return}const e=this.staffEntries[0],i=this.staffEntries[this.staffEntries.length-1],s=e.graphicalVoiceEntries[0].parentVoiceEntry.StemDirection,r=i.graphicalVoiceEntries[0].parentVoiceEntry.StemDirection;if(s===r)this.placement=s===Ft.Up?z.Below:z.Above;else{let o=e.PositionAndShape.BorderLeft+e.PositionAndShape.RelativePosition.x+e.parentMeasure.PositionAndShape.RelativePosition.x,a=i.PositionAndShape.BorderRight+i.PositionAndShape.RelativePosition.x+i.parentMeasure.PositionAndShape.RelativePosition.x;this.graceStart&&(o+=i.PositionAndShape.RelativePosition.x),this.graceEnd&&(a+=i.staffEntryParent.PositionAndShape.RelativePosition.x);const l=n.getSkyLineMinInRange(o,a)*-1;n.getBottomLineMaxInRange(o,a)-t.StaffHeight>l?this.placement=z.Above:this.placement=z.Below}}calculateTopPoints(n,t,e,i){const s=[];let r=i.getRightIndexForPointX(n.x,e.SkyLine.length),o=i.getLeftIndexForPointX(t.x,e.SkyLine.length);r<0&&(r=0),o>=e.SkyLine.length&&(o=e.SkyLine.length-1);for(let a=r;a=e.BottomLine.length&&(o=e.BottomLine.length-1);for(let a=r;ah&&n>c&&(l+=n/70*this.rules.SlurHeightFlattenLongSlursFactorByWidth,l*=1+t/30*this.rules.SlurHeightFlattenLongSlursFactorByAngle,a/=l);const u=Math.min(.5,Math.max(.1,1.7*t/80*a*Math.pow(Math.max(s,.05),.4))),f=Math.min(.5,Math.max(.1,1.7*-e/80*a*Math.pow(Math.max(s,.05),.4))),d=new O;d.x=n*u*Math.cos(t*qi.degreesToRadiansFactor),d.y=n*u*Math.sin(t*qi.degreesToRadiansFactor);const p=new O;p.x=n-n*f*Math.cos(e*qi.degreesToRadiansFactor),p.y=-(n*f*Math.sin(e*qi.degreesToRadiansFactor));let g=d.y-p.y;for(;this.rules.SlurMaximumYControlPointDistance&&Math.abs(g)>this.rules.SlurMaximumYControlPointDistance;)g<0?(d.y+=1,p.y-=1):(d.y-=1,p.y+=1),g=d.y-p.y;return{startControlPoint:d,endControlPoint:p}}calculateAngles(n,t,e,i){let r=Math.atan(t)/qi.degreesToRadiansFactor;t>0?r+=20:r-=20;let o=Math.atan(e)/qi.degreesToRadiansFactor;e<0?o-=20:o+=20;const a=Math.min(Math.max(n,r),i),l=Math.max(Math.min(-n,o),-i);return{startAngle:a,endAngle:l}}};let En=qi;En.degreesToRadiansFactor=Math.PI/180;class Vu extends Pe{constructor(t,e){super(),this.getPedal=t,this.setSymbol(),this.PositionAndShape=new le(this,e)}setSymbol(){!this.getPedal.IsLine&&this.getPedal.IsSign?this.pedalSymbol=Ge.PEDAL_SYMBOL:this.getPedal.IsLine&&this.getPedal.IsSign?this.pedalSymbol=Ge.PEDAL_MIXED:this.pedalSymbol=Ge.PEDAL_BRACKET}}class br extends Vu{constructor(t,e,i=!1,s=!1){switch(super(t,e),this.vfStyle=M.Flow.PedalMarking.Styles.BRACKET,this.ChangeBegin=!1,this.ChangeEnd=!1,this.line=-3,this.EndSymbolPositionAndShape=void 0,this.ChangeBegin=t.ChangeBegin,this.ChangeEnd=t.ChangeEnd,this.pedalSymbol){case Ge.PEDAL_SYMBOL:this.vfStyle=M.Flow.PedalMarking.Styles.TEXT,this.EndSymbolPositionAndShape=new le(this,e);break;case Ge.PEDAL_MIXED:i&&s?this.vfStyle=M.Flow.PedalMarking.Styles.BRACKET_OPEN_BOTH:i?this.vfStyle=M.Flow.PedalMarking.Styles.BRACKET_OPEN_BEGIN:s?this.vfStyle=M.Flow.PedalMarking.Styles.MIXED_OPEN_END:this.vfStyle=M.Flow.PedalMarking.Styles.MIXED;break;case Ge.PEDAL_BRACKET:default:i&&s?this.vfStyle=M.Flow.PedalMarking.Styles.BRACKET_OPEN_BOTH:i?this.vfStyle=M.Flow.PedalMarking.Styles.BRACKET_OPEN_BEGIN:s?this.vfStyle=M.Flow.PedalMarking.Styles.BRACKET_OPEN_END:this.vfStyle=M.Flow.PedalMarking.Styles.BRACKET;break}}setStartNote(t){if(!t)return!1;for(const e of t.graphicalVoiceEntries){const i=e;if(i!=null&&i.vfStaveNote)return this.startNote=i.vfStaveNote,this.startVfVoiceEntry=i,!0}return!1}setEndNote(t){if(!t)return!1;for(const e of t.graphicalVoiceEntries){const i=e;if(i!=null&&i.vfStaveNote)return this.endNote=i.vfStaveNote,this.endVfVoiceEntry=i,!0}return!1}setEndMeasure(t){this.endMeasure=t}CalculateBoundingBox(){}setLine(t){this.line=t}getPedalMarking(){var e,i,s,r;const t=new M.Flow.PedalMarking([this.startNote,this.endNote]);return this.endMeasure&&t.setEndStave(this.endMeasure.getVFStave()),t.setStyle(this.vfStyle),t.setLine(this.line),t.setCustomText(this.DepressText,this.ReleaseText),(((e=this.endVfVoiceEntry)==null?void 0:e.parentStaffEntry)===((r=(s=(i=this.endVfVoiceEntry)==null?void 0:i.parentStaffEntry)==null?void 0:s.parentMeasure)==null?void 0:r.staffEntries.last())||!this.endVfVoiceEntry)&&(t.EndsStave=!0),t.ChangeBegin=this.ChangeBegin,t.ChangeEnd=this.ChangeEnd,t}}class Gu extends Pe{constructor(t,e){super(),this.getWavyLine=t,this.PositionAndShape=new le(this,e)}}class ra extends Gu{constructor(t,e,i=!1){super(t,e),this.line=1,this.isVibrato=!1,this.toEndOfStopStave=!1,this.isVibrato=i}get ToEndOfStopStave(){return this.toEndOfStopStave}setStartNote(t){for(const e of t.graphicalVoiceEntries){const i=e;if(i!=null&&i.vfStaveNote)return this.startNote=i.vfStaveNote,this.startVfVoiceEntry=i,!0}return!1}setEndNote(t){for(const e of t.graphicalVoiceEntries){const i=e;if(i!=null&&i.vfStaveNote){this.endNote=i.vfStaveNote,this.endVfVoiceEntry=i;const s=this.endVfVoiceEntry.parentStaffEntry.parentMeasure.staffEntries,r=s[s.length-1];return this.toEndOfStopStave=r===this.endVfVoiceEntry.parentStaffEntry,!0}}return!1}CalculateBoundingBox(){const t=this.getVibratoBracket();this.boundingBox.Size.height=t.render_options.wave_height*.2}getVibratoBracket(){const t=new M.Flow.VibratoBracket({start:this.startNote,stop:this.endNote,toEndOfStopStave:this.toEndOfStopStave});return t.setLine(this.line),this.isVibrato?t.render_options.vibrato_width=20:t.render_options.wave_girth=4,t}}const ji=M.Flow;class Sr extends Lt{constructor(t){var e,i,s,r,o,a,l,h;super(),this.beamsNeedUpdate=!1,this.rules=t,Lt.symbolFactory=new Du,Lt.TextMeasurer=new Xa(this.rules),Lt.stafflineNoteCalculator=new qs(this.rules),((e=this.rules.DefaultVexFlowNoteFont)==null?void 0:e.toLowerCase())==="gonville"?M.Flow.DEFAULT_FONT_STACK=[(i=M.Flow.Fonts)==null?void 0:i.Gonville,(s=M.Flow.Fonts)==null?void 0:s.Bravura,(r=M.Flow.Fonts)==null?void 0:r.Custom]:((o=this.rules.DefaultVexFlowNoteFont)==null?void 0:o.toLowerCase())==="petaluma"&&(M.Flow.DEFAULT_FONT_STACK=[(a=M.Flow.Fonts)==null?void 0:a.Petaluma,(l=M.Flow.Fonts)==null?void 0:l.Gonville,(h=M.Flow.Fonts)==null?void 0:h.Bravura])}clearRecreatedObjects(){super.clearRecreatedObjects(),Lt.stafflineNoteCalculator=new qs(this.rules);for(const t of this.graphicalMusicSheet.MeasureList)for(const e of t)e==null||e.clean()}formatMeasures(){for(const t of this.graphicalMusicSheet.MeasureList){if(!t||!t[0])continue;t[0].format();for(const i of t){for(const s of i.staffEntries)s.calculateXPosition();i.finalizeBeams()}}this.beamsNeedUpdate=!1}calculateMeasureXLayout(t){const e=[];for(const c of t)c&&e.push(c);if(e.length===0)return 0;t=e;const i=[],s=new ji.Formatter({softmaxFactor:this.rules.SoftmaxFactorVexFlow});let r=t[0].staffEntries.length,o=1;for(const c of t){if(!c)continue;let u=0;for(const p of c.staffEntries)u+=p.setMaxAccidentals();c.parentSourceMeasure.ImplicitMeasure&&(r=Math.max(c.staffEntries.length,r),o=Math.max(c.staffEntries.length+u,o));const f=c.vfVoices,d=[];for(const p in f)f.hasOwnProperty(p)&&(d.push(f[p]),i.push(f[p]));if(d.length===0){j.debug("Found a measure with no voices. Continuing anyway.",f);continue}s.joinVoices(d)}let a=12;const l=t[0].parentSourceMeasure,h=.3;if(i.length>0){a=s.preCalculateMinTotalWidth(i)/_t*this.rules.VoiceSpacingMultiplierVexflow+this.rules.VoiceSpacingAddendVexflow+r*h,l!=null&&l.ImplicitMeasure&&(a=l.Duration.RealValue/l.ActiveTimeSignature.RealValue*a,r>1&&(a+=o*h*1.5),a*=this.rules.PickupMeasureWidthMultiplier),Lt.setMeasuresMinStaffEntriesWidth(t,a);const c=(f,d)=>{s.formatToStave(i,d.getVFStave())},u=(f,d)=>{s.formatToStave(i,d.getVFStave(),{align_rests:!0,context:void 0})};for(const f of t){if(this.rules.AlignRests===Hs.Never)f.formatVoices=c;else if(this.rules.AlignRests===Hs.Always)f.formatVoices=u;else if(this.rules.AlignRests===Hs.Auto){let d=!1;for(const p of f.staffEntries){let g=0,m=0;for(const S of p.graphicalVoiceEntries)if(S.parentVoiceEntry.IsGrace||S&&S.notes&&S.notes[0]&&S.notes[0].sourceNote&&S.notes[0].sourceNote.PrintObject&&g++,S&&S.notes&&S.notes[0]&&S.notes[0].sourceNote&&S.notes[0].sourceNote.isRest()&&S.notes[0].sourceNote.PrintObject&&m++,g>1&&m>=1){d=!0;break}if(d)break}d?f.formatVoices=u:f.formatVoices=c}if(f===t[0]){const d=f;d.formatVoices(a*_t,d)}}}for(const c of t)if(!!c)for(const u of c.staffEntries)u.calculateXPosition();for(const c of t){if(!c)continue;const u=c.vfVoices,f=[];for(const d in u)u.hasOwnProperty(d)&&f.push(u[d]);if(f.length===0){j.debug("Found a measure with no voices. Continuing anyway.",u);continue}s.joinVoices(f)}return a}calculateElongationFactor(t,e,i,s,r,o,a,l){let h=r,c=0;for(const u of t){const f=u.GraphicalLabel.Label.textAlignment;let d=a,p=l;if(u instanceof Yi&&u.ParentLyricWord){u.LyricsEntry.SyllableIndex>0&&(d=this.rules.BetweenSyllableMinimumDistance,cr.IsCenterAligned(f)&&(d+=1));const L=u.ParentLyricWord.GetLyricWord.Syllables;L.length>1&&u.LyricsEntry.SyllableIndex4&&(I*=1.1)}}else i[c]&&(I=y/x);C=Math.max(P,I),h=Math.max(h,C);let F=Math.max(y-x||0,0);i[c]&&(F+=i[c].cumulativeOverlap),i[c]={cumulativeOverlap:F,extend:u instanceof Yi?u.LyricsEntry.extend:!1,labelWidth:m,measureNumber:o,sourceNoteDuration:u instanceof Yi?u.LyricsEntry&&u.LyricsEntry.Parent.Notes[0].Length:!1,text:u instanceof Yi?u.LyricsEntry.Text:u.GraphicalLabel.Label.text,xPosition:b},c++}return h}calculateElongationFactorFromStaffEntries(t,e,i,s){let r=i;const o={},a={};for(const l of t)l.LyricsEntries.length>0&&(r=this.calculateElongationFactor(l.LyricsEntries,l,o,e,r,s,this.rules.HorizontalBetweenLyricsDistance,this.rules.LyricOverlapAllowedIntoNextMeasure)),l.graphicalChordContainers.length>0&&(r=this.calculateElongationFactor(l.graphicalChordContainers,l,a,e,r,s,this.rules.ChordSymbolXSpacing,this.rules.ChordOverlapAllowedIntoNextMeasure));return r}calculateMeasureWidthFromStaffEntries(t,e){let i=1;for(const r of t)!r||r.staffEntries.length===0||(i=this.calculateElongationFactorFromStaffEntries(r.staffEntries,e,i,r.MeasureNumber));return i=Math.min(i,this.rules.MaximumLyricsElongationFactor),e*i}createGraphicalTie(t,e,i,s,r){return new Fu(t,s,r)}updateStaffLineBorders(t){t.SkyBottomLineCalculator.updateStaffLineBorders()}graphicalMeasureCreatedCalculations(t){t.rules=this.rules,t.graphicalMeasureCreatedCalculations()}layoutVoiceEntry(t,e,i,s){for(let r=0;r=2&&(o=s.vfnote[0],a=s.vfnote[1]);let l,h=0;if(r&&r.vfnote&&r.vfnote.length>=2&&(l=r.vfnote[0],h=r.vfnote[1]),e){if(o){const c=new ji.StaveTie({first_indices:[a],first_note:o});s.parentVoiceEntry.parentStaffEntry.parentMeasure.addStaveTie(c,t)}if(l){const c=new ji.StaveTie({last_indices:[h],last_note:l});r.parentVoiceEntry.parentStaffEntry.parentMeasure.addStaveTie(c,t)}}else if(o||l){let c;if(i)if(t.Tie.Type==="S"){const f=t.StartNote.sourceNote,d=t.EndNote.sourceNote;let p=1;f.FretNumber>d.FretNumber&&(p=-1),c=new ji.TabSlide({first_indices:[a],first_note:o,last_indices:[h],last_note:l},p)}else c=new ji.TabTie({first_indices:[a],first_note:o,last_indices:[h],last_note:l},t.Tie.Type);else{c=new ji.StaveTie({first_indices:[a],first_note:o,last_indices:[h],last_note:l});const f=t.Tie.getTieDirection(s.sourceNote);f===z.Below?c.setDirection(1):f===z.Above&&c.setDirection(-1);try{Math.abs((o==null?void 0:o.getTieRightX())-(l==null?void 0:l.getTieLeftX()))<10&&(c.render_options.first_x_shift=-3,c.render_options.last_x_shift=3)}catch(d){console.log(d)}}r.parentVoiceEntry.parentStaffEntry.parentMeasure.addStaveTie(c,t)}}calculateDynamicExpressionsForMultiExpression(t,e,i){if(ethis.rules.MaxMeasureToDrawIndex)return;const s=t.AbsoluteTimestamp,r=this.graphicalMusicSheet.MeasureList[e],o=r[i].ParentStaffLine,a=r[i];if(!o)return;const l=this.getRelativePositionInStaffLineFromTimestamp(s,i,o,o==null?void 0:o.isPartOfMultiStaffInstrument());if(l.x<=0&&(l.x=a.beginInstructionsWidth+this.rules.RhythmRightMargin),t.InstantaneousDynamic){const h=new Nu(t.InstantaneousDynamic,o,a);this.calculateGraphicalInstantaneousDynamicExpression(h,l,s),this.dynamicExpressionMap.set(s.RealValue,h.PositionAndShape)}if(t.StartingContinuousDynamic){const h=t.StartingContinuousDynamic,c=new tl(t.StartingContinuousDynamic,o,a.parentSourceMeasure);if(c.StartMeasure=a,!c.IsVerbal&&h.EndMultiExpression)try{this.calculateGraphicalContinuousDynamic(c,l),c.updateSkyBottomLine()}catch{}else c.IsVerbal?this.calculateGraphicalVerbalContinuousDynamic(c,l):j.warn("This continuous dynamic is not covered. measure"+t.SourceMeasureParent.MeasureNumber)}}createMetronomeMark(t,e){var b,y,x,w,T,E,C,P,I;const i=Math.max(t.ParentMultiTempoExpression.SourceMeasureParent.MeasureNumber-1,0),s=e||i,r=Math.max(t.StaffNumber-1,0),o=this.graphicalMusicSheet.MeasureList[s][r].getVFStave();let a="q";if(t.beatUnit){const F=ws.getNoteDurationFromType(t.beatUnit);a=Yt.durations(F,!1)[0]}let l=this.rules.MetronomeMarkYShift,h=!1;const c=[];if(t.parentMeasure){for(const F of t.parentMeasure.StaffLinkedExpressions)for(const L of F)L&&L instanceof ms&&c.push(L);for(const F of t.parentMeasure.TempoExpressions){const L=((b=F.InstantaneousTempo)==null?void 0:b.Enum)===bt.metronomeMark;if(!t.beatUnit&&F.InstantaneousTempo.beatUnit){const k=ws.getNoteDurationFromType(t.beatUnit);a=Yt.durations(k,!1)[0]}if(F.getPlacementOfFirstEntry()===z.Above&&!L){h=!0;break}}}h&&(l-=1.4);const u=(y=this.graphicalMusicSheet.MeasureList[0][0].ParentStaffLine)==null?void 0:y.SkyLine;let f=t.TempoInBpm,d="",p="",g="";for(const F of this.graphicalMusicSheet.MeasureList[s][r].parentSourceMeasure.TempoExpressions){if(p=F.CombinedExpressionsText,Ha(F.CombinedExpressionsText)){d=F.CombinedExpressionsText;break}if(ps(F.CombinedExpressionsText)||An(F.CombinedExpressionsText)){d=eu(F.CombinedExpressionsText),f=F.sourceMeasure.TempoInBPM,ps(F.CombinedExpressionsText)&&(g=a);break}}const m={bpm:t.TempoInBpm,dots:t.dotted,duration:a,name:d};d&&(m.bpm=f/(m.dots?1.5:1),ps(p)?m.duration=g:(f===Lr[d]||!Lr[d])&&(m.duration=""));const S=((w=(x=this.graphicalMusicSheet.MeasureList[s][r].vfVoices)==null?void 0:x[1])==null?void 0:w.boundingBox.y)||0;if(this.rules.MetronomeMarksDrawn){if(u){const v=((E=(T=this.graphicalMusicSheet.MeasureList[0])==null?void 0:T[r])==null?void 0:E.ParentStaffLine).Measures.map(G=>G.MeasureNumber-1);if(S&&v.includes(s)&&(ps(p)||An(p))){const G=u.slice(0,9);let et=Math.min(...G);et=et<0?et-1:et,l+=et}v.includes(s)&&c.length?u[0]=Math.min(u[0],-4.5+l-4):u[0]=Math.min(u[0],-4.5+l)}o.options.line_config.reduce((k,v)=>(v.visible&&k++,k),0)<5&&(l-=2),o.setTempo(m,l*_t);let L=0;try{L+=((I=(P=(C=this.graphicalMusicSheet.MeasureList[s][r])==null?void 0:C.vfVoices)==null?void 0:P[1])==null?void 0:I.getTickables())[t.parentMeasure.metronomeNoteIndex].getBoundingBox().getX()-o.getNoteStartX()}catch{}o.getModifiers()[o.getModifiers().length-1].setShiftX(L)}}calculateRehearsalMark(t){var f,d,p,g,m;const e=t.rehearsalExpression;if(!e)return;const i=this.graphicalMusicSheet.MeasureList[0][0].MeasureNumber,s=Math.max(t.measureListIndex+1-i,0),r=0,o=(f=this.graphicalMusicSheet.MeasureList[s][r])==null?void 0:f.getVFStave();if(!o)return;const a=-this.rules.RehearsalMarkYOffsetDefault-this.rules.RehearsalMarkYOffset;let l=this.rules.RehearsalMarkXOffsetDefault+this.rules.RehearsalMarkXOffset;t.IsSystemStartMeasure&&(l+=this.rules.RehearsalMarkXOffsetSystemStartMeasure);const h=this.rules.RehearsalMarkFontSize,c=o.getModifiers(),u=c.find(S=>S.getCategory().toLocaleLowerCase()==="repetitions");if(u&&u.setShiftY(u.y_shift-10),o.setSection(e.label,a,l,h),(d=this.graphicalMusicSheet.MeasureList[s][r])!=null&&d.ParentStaffLine.AbstractExpressions){const S=c.find(b=>b.getCategory().toLocaleLowerCase()==="stavesection");for(let b of((m=(g=(p=t==null?void 0:t.VerticalMeasureList)==null?void 0:p[0])==null?void 0:g.ParentStaffLine)==null?void 0:m.AbstractExpressions)||[])b instanceof Us&&(S&&(b.Label.PositionAndShape.RelativePosition.y-=.5),u&&(b.Label.PositionAndShape.RelativePosition.y-=1.7))}}calculateSingleOctaveShift(t,e,i,s){var p;const r=e.OctaveShiftStart,o=r.ParentStartMultiExpression.Timestamp,a=(p=r.ParentEndMultiExpression)==null?void 0:p.Timestamp,l=this.rules.MinMeasureToDrawIndex,h=this.rules.MaxMeasureToDrawIndex;let c=this.graphicalMusicSheet.MeasureList[i][s].ParentStaffLine;c||(c=this.graphicalMusicSheet.MeasureList[l][s].ParentStaffLine);let u;r.ParentEndMultiExpression?u=this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(r.ParentEndMultiExpression.SourceMeasureParent,s):u=this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(s,!0),u.MeasureNumber>h+1&&(u=this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(s,!0));let f;if(r.ParentEndMultiExpression?f=this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(r.ParentStartMultiExpression.SourceMeasureParent,s):f=this.graphicalMusicSheet.MeasureList[l][s],f.MeasureNumberh||u.parentSourceMeasure.measureListIndexh)return;let d=u.ParentStaffLine;if(d||(d=c),u&&c&&d){const g=new na(r,c.PositionAndShape);if(!g.startNote){let b;for(const y of f.staffEntries)if(y){b=y;break}if(!b||(g.setStartNote(b),!g.startNote))return}if(!g.endNote){let b;for(let y=u.staffEntries.length-1;y>=0;y++)if(u.staffEntries[y]){b=u.staffEntries[y];break}if(g.setEndNote(b),!g.endNote)return}let m=f.findGraphicalStaffEntryFromTimestamp(o);m||(m=f.staffEntries[0]);let S=u.findGraphicalStaffEntryFromTimestamp(a);if(S||(S=u.staffEntries[u.staffEntries.length-1]),g.setStartNote(m),d!==c){g.endsOnDifferentStaffLine=!0;let b=c.Measures[c.Measures.length-1];b===void 0&&(b=u);const y=b.staffEntries[b.staffEntries.length-1];g.setEndNote(y);const x=d.ParentMusicSystem.Id-c.ParentMusicSystem.Id;if(x>0)for(let w=c.ParentMusicSystem.Id;wh+1&&(u=this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(s,!0));let f;if(r.ParentEndMultiExpression?f=this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(r.ParentStartMultiExpression.SourceMeasureParent,s):(f=this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(r.ParentStartMultiExpression.SourceMeasureParent,s),f||(f=this.graphicalMusicSheet.MeasureList[l][s])),f.MeasureNumberh||u.parentSourceMeasure.measureListIndexh)return;let d=u.ParentStaffLine;if(d||(d=c),u&&c&&d){let g=!1;c!==d&&(g=!0);const m=new br(r,c.PositionAndShape,!1,g);let S=f.findGraphicalStaffEntryFromTimestamp(o);S||(S=f.staffEntries[0]);let b=u.findGraphicalStaffEntryFromTimestamp(a);if(b||(b=u.staffEntries[u.staffEntries.length-1]),!m.setStartNote(S))return;if(d!==c)if(m.pedalSymbol===Ge.PEDAL_SYMBOL){m.setEndNote(b),m.setEndMeasure(u),m.ReleaseText=" ",m.CalculateBoundingBox(),this.calculatePedalSkyBottomLine(m.startVfVoiceEntry,m.endVfVoiceEntry,m,c);const y=d.Measures[0],x=new br(r,y.PositionAndShape),w=y.staffEntries[0];if(!x.setStartNote(w))return;x.setEndNote(b),m.setEndMeasure(u),d.Pedals.push(x),x.CalculateBoundingBox(),x.DepressText=" ",this.calculatePedalSkyBottomLine(x.startVfVoiceEntry,x.endVfVoiceEntry,x,d)}else{let y=c.Measures[c.Measures.length-1];y===void 0&&(y=u);const x=y.staffEntries[y.staffEntries.length-1];m.setEndNote(x),m.setEndMeasure(u),m.ChangeEnd=!1;const w=d.ParentMusicSystem.Id-c.ParentMusicSystem.Id;if(w>0){let T=1;for(let E=c.ParentMusicSystem.Id;Eh+1&&(u=this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(s,!0));let f;if(r.ParentEndMultiExpression?f=this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(r.ParentStartMultiExpression.SourceMeasureParent,s):f=this.graphicalMusicSheet.MeasureList[l][s],f.MeasureNumberh||u.parentSourceMeasure.measureListIndexh)return;let d=u.ParentStaffLine;if(d||(d=c),u&&c&&d){const m=new ra(r,c.PositionAndShape,f.ParentStaff.isTab);let S=f.findGraphicalStaffEntryFromTimestamp(o);S||(S=f.staffEntries[0]);let b=u.findGraphicalStaffEntryFromTimestamp(a);if(b||(b=u.staffEntries[u.staffEntries.length-1]),m.setStartNote(S),d!==c){let y=c.Measures[c.Measures.length-1];y===void 0&&(y=u);const x=y.staffEntries[y.staffEntries.length-1];if(m.setEndNote(x),d.ParentMusicSystem.Id-c.ParentMusicSystem.Id>0)for(let T=c.ParentMusicSystem.Id;Tu){const y=u;u=c,c=y}s.SkyBottomLineCalculator.updateBottomLineInRange(c,u,f+S)}for(const S of s.Pedals){const b=S,y=b.getPedalMarking(),x=y.line+3+(s.StaffLines.length-1);if(f>x){const w=y.render_options.text_margin_right/10;let T=b.startVfVoiceEntry.PositionAndShape.AbsolutePosition.x-w,E;b.setLine(f-3-(s.StaffLines.length-1));let C=(p=b.endVfVoiceEntry)==null?void 0:p.PositionAndShape;if(C||(C=b.endMeasure.PositionAndShape),b.EndSymbolPositionAndShape){const P=a.render_options.glyph_point_size/20;E=T+3.4;const I=C.AbsolutePosition.x-w,F=I+1.5;s.SkyBottomLineCalculator.updateBottomLineInRange(T,E,f+P),s.SkyBottomLineCalculator.updateBottomLineInRange(I,F,f+P)}else{const P=y.render_options.bracket_height/10;if(y.EndsStave)E=C.AbsolutePosition.x+C.Size.width-w;else switch(a.style){case o.BRACKET_OPEN_END:case o.BRACKET_OPEN_BOTH:case o.MIXED_OPEN_END:E=C.AbsolutePosition.x+C.BorderRight-w;break;default:E=C.AbsolutePosition.x+C.BorderLeft-w;break}const I=(m=(g=b.endVfVoiceEntry)==null?void 0:g.parentStaffEntry)==null?void 0:m.vfClefBefore;if(I&&(E+=I.getWidth()/10),T>E){const F=T;T=E,E=F}s.SkyBottomLineCalculator.updateBottomLineInRange(T,E,f+P)}}}}calculateOctaveShiftSkyBottomLine(t,e,i,s){if(!e){j.warn("octaveshift: no endStaffEntry");return}let r=t.PositionAndShape.Size.width,o=e.PositionAndShape.Size.width;t.hasOnlyRests()?r=-r:r/=2,e.hasOnlyRests()?o*=2:o/=2,t===e&&(o*=2);const a=t.PositionAndShape.AbsolutePosition.x-r,l=e.PositionAndShape.AbsolutePosition.x+o;i.PositionAndShape.Size.width=a-l;const h=i.getTextBracket(),c=h.font.size/10;if(h.position===ji.TextBracket.Positions.TOP){const u=Math.ceil(s.SkyBottomLineCalculator.getSkyLineMinInRange(a,l));if(u===1/0)return;h.start.getStave().options.top_text_position=Math.abs(u),s.SkyBottomLineCalculator.updateSkyLineInRange(a,l,u-c*2)}else{const u=s.SkyBottomLineCalculator.getBottomLineMaxInRange(a,l);if(u===1/0)return;h.start.getStave().options.bottom_text_position=u,t.parentMeasure!==e.parentMeasure&&(h.stop.getStave().options.bottom_text_position=u),s.SkyBottomLineCalculator.updateBottomLineInRange(a,l,u+c*1.5)}}calculateWordRepetitionInstruction(t,e){let i;const s=this.graphicalMusicSheet.MeasureList[e];for(let r=0,o=s.length;r{i.updateSkyBottomLine()})}catch{}}handleTiedGraphicalNote(t,e,i,s,r,o,a,l){}handleBeam(t,e,i){t.parentVoiceEntry.parentStaffEntry.parentMeasure.handleBeam(t,e)}handleVoiceEntryLyrics(t,e,i){t.LyricsEntries.forEach((s,r)=>{const o=new Yi(r,e,this.rules.LyricsHeight,this.rules.StaffHeight);if(e.LyricsEntries.push(o),o.GraphicalLabel.setLabelPositionAndShapeBorders(),r.Word){const l=r.Word.Syllables.indexOf(r);let h=i.indexOf(r.Word);if(h===-1&&(i.push(r.Word),h=i.indexOf(r.Word)),this.graphicalLyricWords.length===0||h>this.graphicalLyricWords.length-1){const c=new Ou(r.Word);o.ParentLyricWord=c,c.GraphicalLyricsEntries[l]=o,this.graphicalLyricWords.push(c)}else{const c=this.graphicalLyricWords[h];o.ParentLyricWord=c,c.GraphicalLyricsEntries[l]=o,c.isFilled()&&(i.splice(h,1),this.graphicalLyricWords.splice(this.graphicalLyricWords.indexOf(c),1))}}})}handleVoiceEntryOrnaments(t,e,i){}handleVoiceEntryArticulations(t,e,i){}handleVoiceEntryTechnicalInstructions(t,e,i){}handleTuplet(t,e,i){t.parentVoiceEntry.parentStaffEntry.parentMeasure.handleTuplet(t,e)}findIndexGraphicalSlurFromSlur(t,e){for(let i=0;i=0){const u=s[c];u.staffEntries.indexOf(o)===-1&&u.staffEntries.push(o),s.splice(c,1)}}}for(const a of s)a.staffEntries.indexOf(o)===-1&&a.staffEntries.push(o)}}for(const e of this.musicSystems)for(const i of e.StaffLines){const s=i.GraphicalSlurs.sort(En.Compare);for(const r of s)r.slur.isCrossed()||r.calculateCurve(this.rules)}}}class Wu{constructor(t){this.musicSheet=t}reInit(){this.init()}init(){this.parts=this.musicSheet.Repetitions.slice(),this.sheetStart=this.musicSheet.SelectionStart=new W(0,1),this.sheetEnd=this.musicSheet.SelectionEnd=this.musicSheet.SheetEndTimestamp,this.calcMapping()}getCurrentRepetitionTimestampTransform(t){let e;for(let i=this.timestamps.length-1;i>=0;i--)if(e=this.timestamps[i],t.gte(e.from))return e;return this.timestamps[0]}absoluteEnrolledToSheetTimestamp(t){if(this.timestamps.length===0)return t;const e=this.getCurrentRepetitionTimestampTransform(t);return W.plus(t,W.minus(e.to,e.from))}get Parts(){return this.parts}get MusicSheet(){return this.musicSheet}getIterator(t){return t?new Ss(this.musicSheet,t,void 0):new Ss(this.musicSheet,this.musicSheet.SelectionStart,this.musicSheet.SelectionEnd)}setSelectionStart(t){this.musicSheet.SelectionStart=t,this.musicSheet.SelectionEnd=void 0}setSelectionRange(t,e){this.musicSheet.SelectionStart=t!=null?t:this.sheetStart,this.musicSheet.SelectionEnd=e!=null?e:this.sheetEnd}calcMapping(){this.timestamps=[];const t=this.getIterator();let e=t.CurrentRepetition,i=new oa(t.CurrentEnrolledTimestamp.clone(),t.CurrentSourceTimestamp.clone(),void 0,0);for(this.timestamps.push(i);!t.EndReached;){if(t.JumpOccurred||e!==t.CurrentRepetition){if(e=t.CurrentRepetition,t.backJumpOccurred){const s=t.JumpResponsibleRepetition;i.nextBackJump=t.CurrentEnrolledTimestamp,i.curRepetition=s,i.curRepetitionIteration=t.CurrentJumpResponsibleRepetitionIterationBeforeJump;for(let r=this.timestamps.length-2;r>=0&&!(s.AbsoluteTimestamp.gt(this.timestamps[r].to)||this.timestamps[r].curRepetition);r--)this.timestamps[r].nextBackJump=i.nextBackJump,this.timestamps[r].curRepetition=s,this.timestamps[r].curRepetitionIteration=i.curRepetitionIteration}i=new oa(t.CurrentEnrolledTimestamp.clone(),t.CurrentSourceTimestamp.clone(),void 0,0),this.timestamps.push(i)}t.moveToNext()}}}class oa{constructor(t,e,i,s){this.from=t,this.to=e,this.curRepetition=i,this.curRepetitionIteration=s,this.nextBackJump=void 0,this.nextForwardJump=void 0}}class ol{constructor(t){this.enrolledTimestamps=[],this.visible=!0,this.musicSheet=t}get Visible(){return this.visible}set Visible(t){this.visible=t}getFirstSourceMeasure(){return this.musicSheet.SourceMeasures[this.startIndex]}getLastSourceMeasure(){return this.musicSheet.SourceMeasures[this.endIndex]}}class aa extends ol{constructor(t,e,i){super(t),this.musicSheet=t,this.startIndex=e,this.endIndex=i}get MeasuresCount(){return this.endIndex-this.startIndex+1}get StartIndex(){return this.startIndex}get EndIndex(){return this.endIndex}get ParentRepetition(){return this.parentRepetition}set ParentRepetition(t){this.parentRepetition=t}get AbsoluteTimestamp(){return W.createFromFraction(this.musicSheet.SourceMeasures[this.startIndex].AbsoluteTimestamp)}setStartIndex(t){this.startIndex=t}setEndIndex(t){this.endIndex=t}}class Dn extends ol{constructor(t,e=!1){super(t),this.backwardJumpInstructions=[],this.endingParts=[],this.endingIndexDict={},this.userNumberOfRepetitions=0,this.visibles=[],this.fromWords=!1,this.repetitonIterationOrder=[],this.numberOfEndings=1,this.musicSheet2=t,this.virtualOverallRepetition=e}get BackwardJumpInstructions(){return this.backwardJumpInstructions}get EndingIndexDict(){return this.endingIndexDict}get EndingParts(){return this.endingParts}get Visibles(){return this.visibles}set Visibles(t){this.visibles=t}get DefaultNumberOfRepetitions(){let t=2;return this.virtualOverallRepetition&&(t=1),Math.max(t,Object.keys(this.endingIndexDict).length,this.checkRepetitionForMultipleLyricVerses())}get UserNumberOfRepetitions(){return this.userNumberOfRepetitions}set UserNumberOfRepetitions(t){this.userNumberOfRepetitions=t,this.repetitonIterationOrder=[];const e=this.userNumberOfRepetitions-this.NumberOfEndings;for(let i=1;i<=this.userNumberOfRepetitions;i++)i<=e?this.repetitonIterationOrder.push(1):this.repetitonIterationOrder.push(i-e)}getForwardJumpTargetForIteration(t){const e=this.repetitonIterationOrder[t-1];return this.endingIndexDict[e]?this.endingIndexDict[e].part.StartIndex:-1}getBackwardJumpTarget(){return this.startMarker.measureIndex}setEndingsStartIndex(t,e){const i=new la(new aa(this.musicSheet2,e,e));this.endingParts.push(i);for(const s of t)try{this.endingIndexDict[s]=i,i.endingIndices.push(s),this.numberOfEndings0&&(s=1),r.Add(new W(s,e)),r}}class al{constructor(){this.idString="random idString, not initialized",this.sourceMeasures=[],this.repetitions=[],this.dynListStaves=[],this.timestampSortedDynamicExpressionsList=[],this.timestampSortedTempoExpressionsList=[],this.instrumentalGroups=[],this.instruments=[],this.musicPartManager=void 0,this.musicSheetErrors=new Uc,this.staves=[],this.playbackDataDict=new Ye,this.transpose=0,this.defaultStartTempoInBpm=0,this.drawErroneousMeasures=!1,this.hasBeenOpenedForTheFirstTime=!1,this.currentEnrolledPosition=new W(0,1),this.soundTempos=new Map,this.playbackSettings=new wo,this.playbackSettings.rhythm=new W(4,4,0,!1),this.userStartTempoInBPM=100,this.pageWidth=120,this.MusicPartManager=new Wu(this),this.hasBPMInfo=!1}get SoundTempos(){return this.soundTempos}set SoundTempos(t){this.soundTempos=t}static getIndexFromStaff(t){return t.idInMusicSheet}get CurrentKeyInstruction(){return this.currentKeyInstruction}set CurrentKeyInstruction(t){this.currentKeyInstruction=t}get SourceMeasures(){return this.sourceMeasures}set SourceMeasures(t){this.sourceMeasures=t}get Repetitions(){return this.repetitions}set Repetitions(t){this.repetitions=t}get DynListStaves(){return this.dynListStaves}get TimestampSortedTempoExpressionsList(){return this.timestampSortedTempoExpressionsList}get TimestampSortedDynamicExpressionsList(){return this.timestampSortedDynamicExpressionsList}get InstrumentalGroups(){return this.instrumentalGroups}get Parts(){return this.instruments}get Instruments(){return this.instruments}get SheetPlaybackSetting(){return this.playbackSettings}set SheetPlaybackSetting(t){this.playbackSettings=t}get DrawErroneousMeasures(){return this.drawErroneousMeasures}set DrawErroneousMeasures(t){this.drawErroneousMeasures=t}get HasBeenOpenedForTheFirstTime(){return this.hasBeenOpenedForTheFirstTime}set HasBeenOpenedForTheFirstTime(t){this.hasBeenOpenedForTheFirstTime=t}InitializeStartTempoInBPM(t){this.playbackSettings.BeatsPerMinute=t,this.userStartTempoInBPM=t}get DefaultStartTempoInBpm(){return this.defaultStartTempoInBpm}set DefaultStartTempoInBpm(t){this.defaultStartTempoInBpm=t,this.InitializeStartTempoInBPM(t)}get Path(){return this.path}set Path(t){this.path=t}get Staves(){return this.staves}get TitleString(){return this.title?this.title.text:""}set TitleString(t){this.Title=new jt(t)}get SubtitleString(){return this.subtitle?this.subtitle.text:""}set SubtitleString(t){this.Subtitle=new jt(t)}get ComposerString(){return this.composer?this.composer.text:""}set ComposerString(t){this.Composer=new jt(t)}get LyricistString(){return this.lyricist?this.lyricist.text:""}set LyricistString(t){this.Lyricist=new jt(t)}get Title(){return this.title}set Title(t){this.title=t}get Subtitle(){return this.subtitle}set Subtitle(t){this.subtitle=t}get Composer(){return this.composer}set Composer(t){this.composer=t}get Lyricist(){return this.lyricist}set Lyricist(t){this.lyricist=t}get Rules(){return this.rules||(j.debug("warning: sheet.Rules was undefined. Creating new EngravingRules."),this.rules=new Ui),this.rules}set Rules(t){this.rules=t}get SheetErrors(){return this.musicSheetErrors}get PlaybackDataDict(){return this.playbackDataDict}get SelectionStart(){return this.selectionStart}set SelectionStart(t){this.selectionStart=t.clone(),this.currentEnrolledPosition=t.clone()}get SelectionEnd(){return this.selectionEnd}set SelectionEnd(t){this.selectionEnd=t}set HasBPMInfo(t){this.hasBPMInfo=t}get HasBPMInfo(){return this.hasBPMInfo}addMeasure(t){this.sourceMeasures.push(t),t.measureListIndex=this.sourceMeasures.length-1}checkForInstrumentWithNoVoice(){for(let t=0,e=this.instruments.length;t0){const t=this.TimestampSortedTempoExpressionsList[0];if(t.InstantaneousTempo)return t.InstantaneousTempo.TempoInBpm;if(t.ContinuousTempo)return t.ContinuousTempo.StartTempo}return this.userStartTempoInBPM}get Errors(){return this.musicSheetErrors.measureErrors}get FirstMeasureNumber(){try{return this.getFirstSourceMeasure().MeasureNumber}catch(t){return j.info("MusicSheet.FirstMeasureNumber: ",t),0}}get LastMeasureNumber(){try{return this.getLastSourceMeasure().MeasureNumber}catch(t){return j.info("MusicSheet.LastMeasureNumber: ",t),0}}get CurrentEnrolledPosition(){return this.currentEnrolledPosition.clone()}set CurrentEnrolledPosition(t){this.currentEnrolledPosition=t.clone()}get Transpose(){return this.transpose}set Transpose(t){this.transpose=t}get FullNameString(){return this.ComposerString+" "+this.TitleString}get IdString(){return this.idString}set IdString(t){this.idString=t}getEnrolledSelectionStartTimeStampWorkaround(){const t=this.MusicPartManager.getIterator(this.SelectionStart);return W.createFromFraction(t.CurrentEnrolledTimestamp)}get SheetEndTimestamp(){const t=this.getLastSourceMeasure();return W.plus(t.AbsoluteTimestamp,t.Duration)}getSourceMeasureFromTimeStamp(t){for(let e=0,i=this.sourceMeasures.length;e0&&s.Voices[0].Visible&&t.push(s)}return t}}al.defaultTitle="[no title given]";class Uu{constructor(){this.syllables=[]}get Syllables(){return this.syllables}containsVoiceEntry(t){for(let e=0,i=this.Syllables.length;e=0&&(this.syllableIndex=r)}get Text(){return this.text}set Text(t){this.text=t}get Word(){return this.word}get Parent(){return this.parent}set Parent(t){this.parent=t}get VerseNumber(){return this.verseNumber}get SyllableIndex(){return this.syllableIndex}}class zu{constructor(t){this.openLyricWords={},this.musicSheet=t}addLyricEntry(t,e){var i,s;if(t){const r=t;for(let o=0,a=r.length;o0)for(let x=S;x1&&(d=parseInt(m[1],10))}catch{const S=Tt.translateText("ReaderErrorMessages/LyricVerseNumberError","Invalid lyric verse number");this.musicSheet.SheetErrors.pushMeasureError(S);continue}}let g;if(h==="single"||h==="end"){if(this.openLyricWords[d]){this.currentLyricWord=this.openLyricWords[d];const m=this.currentLyricWord.Syllables.length;g=new ks(u,d,this.currentLyricWord,e,m),this.currentLyricWord.Syllables.push(g),delete this.openLyricWords[d],this.currentLyricWord=void 0}else g=new ks(u,d,void 0,e);g.extend=l.element("extend")!==void 0}else if(h==="begin")this.openLyricWords[d]&&(delete this.openLyricWords[d],this.currentLyricWord=void 0),this.currentLyricWord=new Uu,this.openLyricWords[d]=this.currentLyricWord,g=new ks(u,d,this.currentLyricWord,e,0),this.currentLyricWord.Syllables.push(g);else if(h==="middle")if(this.openLyricWords[d]){this.currentLyricWord=this.openLyricWords[d];const m=this.currentLyricWord.Syllables.length;g=new ks(u,d,this.currentLyricWord,e,m),this.currentLyricWord.Syllables.push(g)}else g=new ks(u,d,void 0,e);g&&(e.LyricsEntries[d]||(e.LyricsEntries.setValue(d,g),(s=(i=e.ParentSourceStaffEntry)==null?void 0:i.VerticalContainerParent)!=null&&s.ParentMeasure&&(e.ParentSourceStaffEntry.VerticalContainerParent.ParentMeasure.hasLyrics=!0)),e.ParentVoice.Parent.LyricVersesNumbers[d]||e.ParentVoice.Parent.LyricVersesNumbers.push(d))}}}catch{const c=Tt.translateText("ReaderErrorMessages/LyricError","Error while reading lyric entry.");this.musicSheet.SheetErrors.pushMeasureError(c);continue}}e.ParentVoice.Parent.LyricVersesNumbers=e.ParentVoice.Parent.LyricVersesNumbers.filter((o,a,l)=>l.indexOf(o)===a)}}}class Bs{constructor(t,e){this.articulationEnum=t,this.placement=e}Equals(t){return t.articulationEnum===this.articulationEnum&&t.placement===this.placement}}class Hu{constructor(t){this.rules=t}getAccEnumFromString(t){switch(t){case"sharp":return yt.SHARP;case"flat":return yt.FLAT;case"natural":return yt.NATURAL;case"double-sharp":case"sharp-sharp":return yt.DOUBLESHARP;case"double-flat":case"flat-flat":return yt.DOUBLEFLAT;case"triple-sharp":return yt.TRIPLESHARP;case"triple-flat":return yt.TRIPLEFLAT;case"quarter-sharp":return yt.QUARTERTONESHARP;case"quarter-flat":return yt.QUARTERTONEFLAT;case"three-quarters-sharp":return yt.THREEQUARTERSSHARP;case"three-quarters-flat":return yt.THREEQUARTERSFLAT;case"slash-quarter-sharp":return yt.SLASHQUARTERSHARP;case"slash-sharp":return yt.SLASHSHARP;case"double-slash-flat":return yt.DOUBLESLASHFLAT;case"sori":return yt.SORI;case"koron":return yt.KORON;default:return yt.NONE}}addArticulationExpression(t,e){var i,s;if(t!==void 0&&t.elements().length>0){const r=t.elements();for(let o=0,a=r.length;o0&&e.Articulations[0].articulationEnum!==wt.staccato&&e.Articulations.splice(0,0,d),h==="strongaccent"){const p=(s=l==null?void 0:l.attribute("type"))==null?void 0:s.value;p==="up"?d.articulationEnum=wt.marcatoup:p==="down"&&(d.articulationEnum=wt.marcatodown)}if(h==="detachedlegato"){const p=new Bs(wt.staccato,u),g=new Bs(wt.tenuto,u);e.Articulations.push(p,g)}if(!e.hasArticulation(d))switch(e.Articulations.push(d),d.articulationEnum){case wt.staccato:case wt.staccatissimo:e.DurationModifier=d;break;case wt.accent:case wt.strongaccent:e.VolumeModifier=d;break;default:break}}}catch(c){const u="Invalid note articulation.";j.debug("addArticulationExpression",u,c);return}}}}addFermata(t,e){var r;let i=wt.fermata;t.attributes().length>0&&t.attribute("type")&&t.attribute("type").value==="inverted"&&(i=wt.invertedfermata);let s=z.Above;((r=t.attribute("placement"))==null?void 0:r.value)==="below"&&(s=z.Below),e.Articulations.push(new Bs(i,s))}addTechnicalArticulations(t,e,i){var a,l;const s={bend:wt.bend,"down-bow":wt.downbow,"open-string":wt.naturalharmonic,"snap-pizzicato":wt.snappizzicato,stopped:wt.lefthandpizzicato,"up-bow":wt.upbow};for(const h in s){if(!s.hasOwnProperty(h))continue;const c=s[h],u=t.element(h);if(u){let f;((a=u.attribute("placement"))==null?void 0:a.value)==="above"&&(f=z.Above),((l=u.attribute("placement"))==null?void 0:l.value)==="below"&&(f=z.Below);const d=new Bs(c,f);e.hasArticulation(d)||e.Articulations.push(d)}}const r=t.element("fingering");if(r){const h=this.createTechnicalInstruction(r,i);h.type=Pr.Fingering,i.Fingering=h,e.TechnicalInstructions.push(h)}const o=t.element("string");if(o){const h=this.createTechnicalInstruction(o,i);h.type=Pr.String,i.StringInstruction=h,e.TechnicalInstructions.push(h)}}createTechnicalInstruction(t,e){const i=new Jc;i.sourceNote=e,i.value=t.value;const s=t.attribute("placement");return this.rules.FingeringPositionFromXML&&(i.placement=this.getPlacement(s)),i}getPlacement(t,e=z.NotYetDefined){if(e!==z.NotYetDefined)return e;if(t)switch(t.value){case"above":return z.Above;case"below":return z.Below;case"left":return z.Left;case"right":return z.Right;default:return z.NotYetDefined}else return z.NotYetDefined}addOrnament(t,e){if(t){let i;const s={"delayed-inverted-turn":Ne.DelayedInvertedTurn,"delayed-turn":Ne.DelayedTurn,"inverted-mordent":Ne.InvertedMordent,"inverted-turn":Ne.InvertedTurn,mordent:Ne.Mordent,"trill-mark":Ne.Trill,turn:Ne.Turn};for(const r in s){if(!s.hasOwnProperty(r))continue;const o=t.element(r);if(o){i=new Xc(s[r]);const a=o.attribute("placement");a&&a.value==="below"&&(i.placement=z.Below)}}if(i){const r=t.elements("accidental-mark");if(r){let o=z.Below,a=yt.NONE;const l=r;for(let h=0,c=l.length;h0&&(this.currentVoiceEntry.GraceVoiceEntriesBefore=this.graceVoiceEntriesTempList,this.graceVoiceEntriesTempList=[]))}finalizeReadingMeasure(){this.graceVoiceEntriesTempList.length>0&&this.currentNormalVoiceEntry!==void 0&&this.currentNormalVoiceEntry.GraceVoiceEntriesAfter.concat(this.graceVoiceEntriesTempList),this.graceVoiceEntriesTempList=[],this.pluginManager.processVoiceMeasureReadPlugins(this.currMeasureVoiceEntries,this.activeKey,this.activeRhythm),this.currMeasureVoiceEntries.length=0,this.openBeams.length>1&&this.handleOpenBeam()}read(t,e,i,s,r,o,a,l,h,c,u,f,d,p,g,m,S,b,y,x,w,T){this.currentStaffEntry=a,this.currentMeasure=l;try{this.currentNote=o?this.addRestNote(t.element("rest"),e,s,r,d,p,y):this.addSingleNote(t,e,s,i,r,u,f,d,p,g,m,S,b,y,w,T),this.currentNote.DotsXml=x;const E=t.elements("lyric");this.lyricsReader!==void 0&&E&&(this.lyricsReader.addLyricEntry(E,this.currentVoiceEntry),this.voice.Parent.HasLyrics=!0);let C=!1;const P=t.element("notations");if(P){this.articulationReader&&this.readArticulations(P,this.currentVoiceEntry,this.currentNote);const I=P.elements("slur");this.slurReader!==void 0&&I.length>0&&!this.currentNote.ParentVoiceEntry.IsGrace&&this.slurReader.addSlur(I,this.currentNote);const F=P.elements("tuplet");F.length>0&&(this.openTupletNumber=this.addTuplet(t,F),C=!0);const L=P.element("arpeggiate");if(L!==void 0){let et;if(this.currentVoiceEntry.Arpeggio)et=this.currentVoiceEntry.Arpeggio;else{let H=!1;for(const nt of this.currentStaffEntry.VoiceEntries)if(nt.Arpeggio){H=!0,et=nt.Arpeggio;break}if(!H){let nt=Xe.ARPEGGIO_DIRECTIONLESS;const K=L.attribute("direction");if(K)switch(K.value){case"up":nt=Xe.ROLL_UP;break;case"down":nt=Xe.ROLL_DOWN;break;default:nt=Xe.ARPEGGIO_DIRECTIONLESS}et=new zc(this.currentVoiceEntry,nt),this.currentVoiceEntry.Arpeggio=et}}et.addNote(this.currentNote)}const k=P.elements("tied");k.length>0&&this.addTie(k,h,c,Fs.SIMPLE);const v=P.elements("slide");v.length>0&&this.addTie(v,h,c,Fs.SLIDE);const G=P.element("technical");if(G){const et=G.elements("hammer-on");et.length>0&&this.addTie(et,h,c,Fs.HAMMERON);const H=G.elements("pull-off");H.length>0&&this.addTie(H,h,c,Fs.PULLOFF)}}t.element("time-modification")!==void 0&&!C&&this.handleTimeModificationNode(t)}catch(E){j.warn(E);const C=Tt.translateText("ReaderErrorMessages/NoteError","Ignored erroneous Note.");this.musicSheet.SheetErrors.pushMeasureError(C),this.musicSheet.SheetErrors.pushMeasureError(E)}return this.currentNote}checkForStaffEntryLink(t,e,i,s){const r=new Kc(this.currentVoiceEntry);r.LinkStaffEntries.push(i),i.Link=r;const o=this.currentVoiceEntry.Timestamp.clone(),a=s.getVerticalContainerByTimestamp(o);return i=a.StaffEntries[t],i||(i=new we(a,e),a.StaffEntries[t]=i),i.VoiceEntries.push(this.currentVoiceEntry),r.LinkStaffEntries.push(i),i.Link=r,i}checkForOpenBeam(){this.openBeams.length>0&&this.currentNote&&this.handleOpenBeam()}checkOpenTies(){const t=this.openTieDict;for(const e in t)if(t.hasOwnProperty(e)){const i=t[e];W.plus(i.StartNote.ParentStaffEntry.Timestamp,i.Duration).lt(i.StartNote.SourceMeasure.Duration)&&delete t[e]}}hasVoiceEntry(){return this.currentVoiceEntry!==void 0}readArticulations(t,e,i){const s=t.element("articulations");s&&this.articulationReader.addArticulationExpression(s,e);const r=t.element("fermata");r&&this.articulationReader.addFermata(r,e);const o=t.element("technical");o&&this.articulationReader.addTechnicalArticulations(o,e,i);const a=t.element("ornaments");a&&this.articulationReader.addOrnament(a,e)}addSingleNote(t,e,i,s,r,o,a,l,h,c,u,f,d,p,g,m){let S=0,b,y=yt.NONE,x=ut.C,w=ut.C,T=0,E=0,C,P,I;const F=t.elements();for(let K=0,lt=F.length;K0&&this.openBeams.last().ExtendedNoteList.push(p),p}addNoteInfo(t,e,i,s,r,o,a,l,h){t.NoteTypeXml=e,t.PrintObject=i,t.IsCueNote=s,t.NormalNotes=r,t.displayStepUnpitched=o,t.displayOctaveUnpitched=a,t.NoteheadColorXml=l,t.NoteheadColor=l}createBeam(t,e){var i;try{const s=t.element("beam");let r;if(s!==void 0&&s.hasAttributes&&(r=s.attribute("number")),r){let o=parseInt(r.value,10);const a=t.elements("beam"),l=a[0].value;a&&(l==="begin"?(o===((i=this.openBeams.last())==null?void 0:i.BeamNumber)?(this.beamNumberOffset++,o+=this.beamNumberOffset):this.openBeams.last()&&this.handleOpenBeam(),this.openBeams.push(new Hc(o,this.beamNumberOffset))):o+=this.beamNumberOffset);let h=!1;if(!(o>0&&o<=this.openBeams.length)||!this.openBeams[o-1]){j.debug("[OSMD] invalid beamnumber");return}for(let c=0,u=this.openBeams[o-1].Notes.length;c1){let s=t.element("time-modification");s&&(s=s.element("actual-notes"));const r=e;for(let o=0,a=r.length;o1&&this.openTupletNumber--),this.tupletDict[u]=d;const g=[];g.push(this.currentNote),d.Notes.push(g),d.Fractions.push(this.getTupletNoteDurationFromType(t)),this.currentNote.NoteTuplet=d,this.openTupletNumber=u}else if(c.value==="stop"){let u=1;l.attribute("number")&&(u=parseInt(l.attribute("number").value,10));const f=this.tupletDict[u];if(f){const d=l.attribute("placement");d&&(d.value==="below"?f.tupletLabelNumberPlacement=z.Below:f.tupletLabelNumberPlacement=z.Above,f.PlacementFromXml=!0);const p=[];if(p.push(this.currentNote),f.Notes.push(p),!f.PlacementFromXml){let g=!1;for(const m of f.Notes){for(const S of m)if(!S.isRest()){S.StemDirectionXml===Ft.Down?f.tupletLabelNumberPlacement=z.Below:f.tupletLabelNumberPlacement=z.Above,g=!0;break}if(g)break}}f.Fractions.push(this.getTupletNoteDurationFromType(t)),this.currentNote.NoteTuplet=f,delete this.tupletDict[u],Object.keys(this.tupletDict).length===0?this.openTupletNumber=0:Object.keys(this.tupletDict).length>1&&this.openTupletNumber--}}}}}else if(e[0]){const s=e[0];if(s.hasAttributes){const r=s.attribute("type").value;let o=1;s.attribute("number")&&(o=parseInt(s.attribute("number").value,10));const a=isNaN(o),l=s.attribute("bracket");if(l&&l.value==="yes"&&(i=!0),r==="start"){let h=0,c=t.element("time-modification");if(c&&(c=c.element("actual-notes")),c&&(h=parseInt(c.value,10),isNaN(h))){const p=Tt.translateText("ReaderErrorMessages/TupletNoteDurationError","Invalid tuplet note duration.");throw this.musicSheet.SheetErrors.pushMeasureError(p),new Ee(p)}a&&(this.openTupletNumber++,o=this.openTupletNumber);let u=this.tupletDict[o];u||(u=this.tupletDict[o]=new Qo(h,i),u.tupletLabelNumberPlacement=z.Above);const f=s.attribute("placement");f&&(f.value==="below"?u.tupletLabelNumberPlacement=z.Below:u.tupletLabelNumberPlacement=z.Above,u.PlacementFromXml=!0);const d=[];d.push(this.currentNote),u.Notes.push(d),u.Fractions.push(this.getTupletNoteDurationFromType(t)),this.currentNote.NoteTuplet=u,this.openTupletNumber=o}else if(r==="stop"){a&&(o=this.openTupletNumber);const h=this.tupletDict[this.openTupletNumber];if(h){const c=s.attribute("placement");c&&(c.value==="below"?h.tupletLabelNumberPlacement=z.Below:h.tupletLabelNumberPlacement=z.Above,h.PlacementFromXml=!0);const u=[];if(u.push(this.currentNote),h.Notes.push(u),!h.PlacementFromXml){let f=!1;for(const d of h.Notes){for(const p of d)if(!p.isRest()){p.StemDirectionXml===Ft.Down?h.tupletLabelNumberPlacement=z.Below:h.tupletLabelNumberPlacement=z.Above,f=!0;break}if(f)break}}h.Fractions.push(this.getTupletNoteDurationFromType(t)),this.currentNote.NoteTuplet=h,Object.keys(this.tupletDict).length===0?this.openTupletNumber=0:Object.keys(this.tupletDict).length>1&&this.openTupletNumber--,delete this.tupletDict[o]}}}}return this.openTupletNumber}handleTimeModificationNode(t){if(this.tupletDict[this.openTupletNumber])try{const e=this.tupletDict[this.openTupletNumber],i=Ti.last(e.Notes),s=i[0].ParentVoiceEntry;let r;s.Timestamp.Equals(this.currentVoiceEntry.Timestamp)?r=i:(r=[],e.Notes.push(r),e.Fractions.push(this.getTupletNoteDurationFromType(t))),r.push(this.currentNote),this.currentNote.NoteTuplet=e}catch(e){const i=Tt.translateText("ReaderErrorMessages/TupletNumberError","Invalid tuplet number.");throw this.musicSheet.SheetErrors.pushMeasureError(i),e}else if(this.currentVoiceEntry.Notes.length>0){const e=this.currentVoiceEntry.Notes[0];if(e.NoteTuplet){const i=e.NoteTuplet;Ti.last(i.Notes).push(this.currentNote),this.currentNote.NoteTuplet=i}}}addTie(t,e,i,s){if(t){if(t.length===1){const r=t[0];if(r!==void 0&&r.attributes()){const o=this.getTieDirection(r),a=r.attribute("type").value;try{if(a==="start"){const l=this.findCurrentNoteInTieDict(this.currentNote);l<0&&delete this.openTieDict[l];const h=this.getNextAvailableNumberForTie(),c=new qc(this.currentNote,s);this.openTieDict[h]=c,c.TieNumber=h,c.TieDirection=o}else if(a==="stop"){const l=this.findCurrentNoteInTieDict(this.currentNote),h=this.openTieDict[l];h&&(h.AddNote(this.currentNote),delete this.openTieDict[l])}}catch{const h=Tt.translateText("ReaderErrorMessages/TieError","Error while reading tie.");this.musicSheet.SheetErrors.pushMeasureError(h)}}}else if(t.length===2){const r=this.findCurrentNoteInTieDict(this.currentNote);if(r>=0){const o=this.openTieDict[r];o.AddNote(this.currentNote);for(const a of t)if(a.attribute("type").value==="start"){const h=this.getTieDirection(a);o.NoteIndexToTieDirection[o.Notes.length-1]=h}}}}}getTieDirection(t){let e=z.NotYetDefined;const i=t.attribute("placement");i&&(i.value==="above"?e=z.Above:i.value==="below"&&(e=z.Below));const s=t.attribute("orientation");return s&&(s.value==="over"?e=z.Above:s.value==="under"&&(e=z.Below)),e}getNextAvailableNumberForTie(){const t=Object.keys(this.openTieDict);if(t.length===0)return 1;t.sort((e,i)=>+e-+i);for(let e=0;e0?s.RealValue>0?(h=W.multiply(W.minus(s,r),h),this.directionTimestamp=W.plus(h,s)):this.directionTimestamp=W.createFromFraction(h):this.offsetDivisions<0&&(s.RealValue>0?(h=W.multiply(W.minus(s,r),h),this.directionTimestamp=W.minus(s,h)):this.directionTimestamp=W.createFromFraction(h));const c=t.attribute("placement");if(c)try{const u=c.value;u==="below"?this.placement=z.Below:u==="above"&&(this.placement=z.Above)}catch(u){const f=Tt.translateText("ReaderErrorMessages/ExpressionPlacementError","Invalid expression placement -> set to default.");j.debug("ExpressionReader.readExpressionParameters",f,u),this.musicSheet.SheetErrors.pushMeasureError(f),this.placement=z.Below}if(this.placement===z.NotYetDefined)try{const u=t.element("direction-type");if(u){const f=u.element("dynamics");if(f){const m=f.attribute("default-y");m&&this.readExpressionPlacement(m,"read dynamics y pos")}const d=u.element("wedge");if(d){const m=d.attribute("default-y");m&&this.readExpressionPlacement(m,"read wedge y pos")}const p=u.element("words");if(p){const m=p.attribute("default-y");m&&this.readExpressionPlacement(m,"read words y pos")}const g=u.element("rehearsal");if(g){const m=g.attribute("default-y");m&&this.readExpressionPlacement(m,"read rehearsal pos")}}}catch(u){const f=Tt.translateText("ReaderErrorMessages/ExpressionPlacementError","Invalid expression placement -> set to default.");j.debug("ExpressionReader.readExpressionParameters",f,u),this.musicSheet.SheetErrors.pushMeasureError(f),this.placement=z.Below}this.placement===z.NotYetDefined&&(e.Staves.length>1?this.placement=z.Below:e.HasLyrics?this.placement=z.Above:this.placement=z.Below)}read(t,e,i,s=void 0,r=0){let o=!1,a=!1;const l=t.element("sound");if(l){const u=l.attribute("tempo"),f=l.attribute("dynamics");if(u){const d=u.value.match(/^(\d+)(\.\d+)?$/);(d==null?void 0:d.length)>0?this.soundTempo=Math.round(Number.parseFloat(u.value)):(j.info("invalid xml tempo: "+u.value),this.soundTempo=100),e.TempoInBPM=this.soundTempo,this.musicSheet.DefaultStartTempoInBpm===0&&(this.musicSheet.DefaultStartTempoInBpm=this.soundTempo),this.musicSheet.HasBPMInfo=!0,o=!0}if(f){const d=f.value.match(/\d+/);this.soundDynamic=d!==void 0?parseInt(d[0],10):100,a=!0}}const h=t.element("direction-type");if(!h)return;let c=h.element("metronome");if(c){e.metronomeNoteIndex=r;const u=c.element("beat-unit"),f=c.element("beat-unit-dot")!==void 0,d=c.element("per-minute");if(u!==void 0&&d){c.hasAttributes&&c.attribute("default-x")!==void 0&&(this.directionTimestamp=W.createFromFraction(i));const g=parseFloat(d.value);this.createNewTempoExpressionIfNeeded(e);const m=new qt(void 0,this.placement,this.staffNumber,g,this.currentMultiTempoExpression,!0);m.parentMeasure=e,this.soundTempo=g,e.TempoInBPM=this.soundTempo*(f?1.5:1),this.musicSheet.DefaultStartTempoInBpm===0&&(this.musicSheet.DefaultStartTempoInBpm=this.soundTempo),e.MeasureNumberXML===1&&this.musicSheet.SourceMeasures.length===0&&(this.musicSheet.DefaultStartTempoInBpm=this.soundTempo),this.musicSheet.HasBPMInfo=!0,m.dotted=f,m.beatUnit=u.value,this.currentMultiTempoExpression.addExpression(m,""),this.currentMultiTempoExpression.CombinedExpressionsText="test"}return}if(c=h.element("dynamics"),c){const u=t.element("notations")!==void 0;this.interpretInstantaneousDynamics(c,e,i,u);return}if(c=h.element("words"),c){const u=h.elements("words");let f="";for(const d of u)f+=d.value;if(c.value=f,o||ps(c.value)||An(c.value)){this.createNewTempoExpressionIfNeeded(e),this.currentMultiTempoExpression.CombinedExpressionsText=c.value,(ps(c.value)||An(c.value))&&(c.value=void 0);const d=new qt(c.value,this.placement,this.staffNumber,this.soundTempo,this.currentMultiTempoExpression);this.currentMultiTempoExpression.addExpression(d,"")}else a||this.interpretWords(c,e,i);return}if(c=h.element("wedge"),c){this.interpretWedge(c,e,s,e.MeasureNumber);return}if(c=h.element("rehearsal"),c){this.interpretRehearsalMark(c,e,i,e.MeasureNumber);return}}closeOpenExpressions(t,e){for(const i of this.openContinuousDynamicExpressions)this.createNewMultiExpressionIfNeeded(t,i.NumberXml,e),this.closeOpenContinuousDynamic(i,t,e);this.openContinuousTempoExpression&&this.closeOpenContinuousTempo(W.plus(t.AbsoluteTimestamp,e))}addOctaveShift(t,e,i){var a;let s=1;const r=t.element("staff");if(r)try{s=parseInt(r.value,10)}catch(l){const h=Tt.translateText("ReaderErrorMessages/OctaveShiftStaffError","Invalid octave shift staff number -> set to default");this.musicSheet.SheetErrors.pushMeasureError(h),s=1,j.debug("ExpressionReader.addOctaveShift",h,l)}const o=t.element("direction-type");if(o){const l=o.element("octave-shift"),h=this.readPlacement(t);if(l!==void 0&&l.hasAttributes)try{const c=this.readNumber(l);if(l.attribute("size")){const u=parseInt(l.attribute("size").value,10);let f=0;u===8?f=1:u===15&&(f=2);let d=(a=l.attribute("type"))==null?void 0:a.value;if(d||(h===z.Above?d="down":h===z.Below&&(d="up")),d==="up"||d==="down"){const p=new _n(d,f);p.StaffNumber=s,this.getMultiExpression=this.createNewMultiExpressionIfNeeded(e,c),this.getMultiExpression.OctaveShiftStart=p,p.ParentStartMultiExpression=this.getMultiExpression,this.openOctaveShift=p}else if(d==="stop"){if(this.openOctaveShift){this.getMultiExpression=this.createNewMultiExpressionIfNeeded(e,this.openOctaveShift.numberXml,i);const p=this.getMultiExpression;p.OctaveShiftEnd=this.openOctaveShift,this.openOctaveShift.ParentEndMultiExpression=this.getMultiExpression,this.openOctaveShift=void 0}}else d||j.debug("octave-shift missing type in xml")}}catch(c){const u=Tt.translateText("ReaderErrorMessages/OctaveShiftError","Error while reading octave shift.");this.musicSheet.SheetErrors.pushMeasureError(u),j.debug("ExpressionReader.addOctaveShift",u,c)}}}addPedalMarking(t,e,i){var r,o,a,l;const s=t.element("direction-type");if(s){const h=s.element("pedal");if(h!==void 0&&h.hasAttributes){let c=!1,u=!1;try{switch(((r=h.attribute("line"))==null?void 0:r.value)==="yes"?u=!0:((o=h.attribute("line"))==null?void 0:o.value)==="no"&&(u=!1,c=!0),((a=h.attribute("sign"))==null?void 0:a.value)==="yes"?c=!0:((l=h.attribute("sign"))==null?void 0:l.value)==="no"&&(c=!1,u=!0),h.attribute("type").value){case"start":this.openPedal&&this.openPedal.IsLine&&this.endOpenPedal(e),this.createNewMultiExpressionIfNeeded(e,-1),this.openPedal=new ca(u,c),this.getMultiExpression.PedalStart=this.openPedal,this.openPedal.ParentStartMultiExpression=this.getMultiExpression;break;case"stop":this.openPedal&&this.endOpenPedal(e);break;case"change":this.openPedal&&this.openPedal.IsLine&&(this.openPedal.ChangeEnd=!0,this.createNewMultiExpressionIfNeeded(e,-1),this.getMultiExpression.PedalEnd=this.openPedal,this.openPedal.ParentEndMultiExpression=this.getMultiExpression,this.createNewMultiExpressionIfNeeded(e,-1),this.openPedal=new ca(u,c),this.openPedal.ChangeBegin=!0,this.getMultiExpression.PedalStart=this.openPedal,this.openPedal.ParentStartMultiExpression=this.getMultiExpression);break;case"continue":break;default:break}}catch(f){const d=Tt.translateText("ReaderErrorMessages/PedalError","Error while reading pedal.");this.musicSheet.SheetErrors.pushMeasureError(d),j.debug("ExpressionReader.addPedalMarking",d,f)}}}}endOpenPedal(t){this.createNewMultiExpressionIfNeeded(t,-1),this.getMultiExpression.PedalEnd=this.openPedal,this.openPedal.ParentEndMultiExpression=this.getMultiExpression,this.openPedal=void 0}addWavyLine(t,e,i,s){if(t&&t.hasAttributes)try{switch(t.attribute("type").value){case"start":this.createNewMultiExpressionIfNeeded(e,-1),this.openWavyLine=new ju(this.placement),this.getMultiExpression.WavyLineStart=this.openWavyLine,this.openWavyLine.ParentStartMultiExpression=this.getMultiExpression;break;case"stop":this.openWavyLine&&(this.createNewMultiExpressionIfNeeded(e,-1,i),this.getMultiExpression.WavyLineEnd=this.openWavyLine,this.openWavyLine.ParentEndMultiExpression=this.getMultiExpression,this.openWavyLine=void 0);break;case"continue":break;default:break}}catch(r){const o=Tt.translateText("ReaderErrorMessages/WavyLineError","Error while reading wavy-line.");this.musicSheet.SheetErrors.pushMeasureError(o),j.debug("ExpressionReader.addWavyLine",o,r)}}initialize(){this.placement=z.NotYetDefined,this.soundTempo=0,this.soundDynamic=0,this.offsetDivisions=0}readPlacement(t){var i;const e=(i=t.attribute("placement"))==null?void 0:i.value;return e==="above"?z.Above:e==="below"?z.Below:z.NotYetDefined}readExpressionPlacement(t,e){try{const i=parseInt(t.value,10);i<0?this.placement=z.Below:i>0&&(this.placement=z.Above)}catch(i){j.debug("ExpressionReader.readExpressionParameters",e,i)}}interpretInstantaneousDynamics(t,e,i,s){if(t.hasElements){t.hasAttributes&&t.attribute("default-x")&&(this.directionTimestamp=W.createFromFraction(i));const r=this.readNumber(t);let o=t.elements()[0].name;if(o==="other-dynamics"&&(o=t.elements()[0].value),o){s?this.createNewMultiExpressionIfNeeded(e,r,W.createFromFraction(i)):this.createNewMultiExpressionIfNeeded(e,r);const a=new Ai(o,this.soundDynamic,this.placement,this.staffNumber,e);a.InMeasureTimestamp=i.clone(),this.getMultiExpression.addExpression(a,""),this.initialize(),this.activeInstantaneousDynamic?this.activeInstantaneousDynamic.DynEnum=a.DynEnum:this.activeInstantaneousDynamic=new Ai(o,0,z.NotYetDefined,1,e)}}}interpretWords(t,e,i){const s=t.value;let r;const o=t.attribute("font-style");if(o&&o.value==="italic"&&(r=ue.Italic),s.length>0){if(t.hasAttributes&&t.attribute("default-x")&&(this.directionTimestamp=W.createFromFraction(i)),this.checkIfWordsNodeIsRepetitionInstruction(s))return;this.fillMultiOrTempoExpression(s,e,i,r),this.initialize()}}readNumber(t){var s;let e=1;const i=(s=t.attribute("number"))==null?void 0:s.value;return i&&(e=Number.parseInt(i,10)),e}interpretWedge(t,e,i,s){var o,a;t!==void 0&&t.hasAttributes&&t.attribute("default-x")&&(this.directionTimestamp=W.createFromFraction(i));const r=this.readNumber(t);((a=(o=t.attribute("type"))==null?void 0:o.value)==null?void 0:a.toLowerCase())==="stop"?this.createNewMultiExpressionIfNeeded(e,r,i):this.createNewMultiExpressionIfNeeded(e,r),this.addWedge(t,e,i),this.initialize()}interpretRehearsalMark(t,e,i,s){e.rehearsalExpression=new lu(t.value,this.placement)}createNewMultiExpressionIfNeeded(t,e,i=void 0){i||(i=this.directionTimestamp);let s=this.getMultiExpression;return(!s||s&&(s.SourceMeasureParent!==t||s.numberXml!==e||s.SourceMeasureParent===t&&s.Timestamp!==i))&&(this.getMultiExpression=s=new nu(t,W.createFromFraction(i)),t.StaffLinkedExpressions[this.globalStaffIndex].push(s)),s}createNewTempoExpressionIfNeeded(t){(!this.currentMultiTempoExpression||this.currentMultiTempoExpression.SourceMeasureParent!==t||this.currentMultiTempoExpression.Timestamp!==this.directionTimestamp)&&(this.currentMultiTempoExpression=new ou(t,W.createFromFraction(this.directionTimestamp)),t.TempoExpressions.push(this.currentMultiTempoExpression))}addWedge(t,e,i){if(t!==void 0&&t.hasAttributes){const s=this.readNumber(t),r=t.attribute("type").value.toLowerCase();try{if(r==="crescendo"||r==="diminuendo"){const o=new ei(Re[r],this.placement,this.staffNumber,e,this.activeInstantaneousDynamic,s);this.openContinuousDynamicExpressions.push(o);let a=this.getMultiExpression;a||(a=this.createNewMultiExpressionIfNeeded(e,s)),a.StartingContinuousDynamic=o,o.StartMultiExpression=a,this.activeInstantaneousDynamic!==void 0&&this.activeInstantaneousDynamic.StaffNumber===o.StaffNumber&&(this.activeInstantaneousDynamic=void 0)}else if(r==="stop")for(const o of this.openContinuousDynamicExpressions)o.NumberXml===s&&o.NumberXml===s&&this.closeOpenContinuousDynamic(o,e,i)}catch(o){const a="ReaderErrorMessages/WedgeError, Error while reading Crescendo / Diminuendo.";this.musicSheet.SheetErrors.pushMeasureError(a),j.debug("ExpressionReader.addWedge",a,o)}}}fillMultiOrTempoExpression(t,e,i,s){if(!t)return;const r=t.trim();this.createExpressionFromString("",r,e,i,t,s)}createExpressionFromString(t,e,i,s,r,o){if(qt.isInputStringInstantaneousTempo(e)||Ni.isInputStringContinuousTempo(e)){if(i.TempoExpressions.length>0)for(let c=0,u=i.TempoExpressions.length;c0)for(let c=0,u=i.TempoExpressions.length;c0&&!this.hasDigit(e)&&this.globalStaffIndex>0){if(f.EntriesList[0].label.indexOf(e)>=0)return!1;break}}let l=vt.CenterBottom;this.musicSheet.Rules.CompactMode&&(l=vt.LeftBottom);const h=new ms(e,this.placement,l,this.staffNumber);return h.fontStyle=o,a.addExpression(h,t),!1}closeOpenContinuousDynamic(t,e,i){if(!t)return;const s=t.NumberXml;t.EndMultiExpression=this.createNewMultiExpressionIfNeeded(e,s,i),t.StartMultiExpression.EndingContinuousDynamic=t,this.openContinuousDynamicExpressions=this.openContinuousDynamicExpressions.filter(r=>r!==t)}closeOpenContinuousTempo(t){this.openContinuousTempoExpression.AbsoluteEndTimestamp=t,this.openContinuousTempoExpression=void 0}checkIfWordsNodeIsRepetitionInstruction(t){return t=t.trim().toLowerCase(),t==="coda"||t==="tocoda"||t==="to coda"||t==="fine"||t==="d.c."||t==="dacapo"||t==="da capo"||t==="d.s."||t==="dalsegno"||t==="dal segno"||t==="d.c. al fine"||t==="d.s. al fine"||t==="d.c. al coda"||t==="d.s. al coda"}hasDigit(t){return/\d/.test(t)}}class qu{constructor(){}get StartNote(){return this.startNote}set StartNote(t){this.startNote=t}get EndNote(){return this.endNote}set EndNote(t){this.endNote=t}startNoteHasMoreStartingSlurs(){if(!this.startNote)return!1;for(let t=0,e=this.startNote.NoteSlurs.length;t0){const s=i.attribute("type").value;let r=1;try{i.attribute("number")&&(r=parseInt(i.attribute("number").value,10))}catch(h){j.debug("VoiceGenerator.addSlur number: ",h)}let o=z.NotYetDefined;const a=i.attribute("placement");a&&a.value&&(a.value==="above"?o=z.Above:a.value==="below"&&(o=z.Below));const l=i.attribute("orientation");if(l&&l.value&&(l.value==="over"?o=z.Above:l.value==="under"&&(o=z.Below)),s==="start"){let h=this.openSlurDict[r];h||(h=new qu,this.openSlurDict[r]=h),h.StartNote=e,h.PlacementXml=o}else if(s==="stop"){const h=this.openSlurDict[r];h&&(h.EndNote=e,e.checkForDoubleSlur(h)||(e.NoteSlurs.push(h),h.StartNote.NoteSlurs.push(h)),delete this.openSlurDict[r])}}}}catch{const s=Tt.translateText("ReaderErrorMessages/SlurError","Error while reading slur.");this.musicSheet.SheetErrors.pushMeasureError(s)}}}class Zu{constructor(t,e,i,s){this.voiceGeneratorsDict={},this.staffMainVoiceGeneratorDict={},this.divisions=0,this.currentClefNumber=1,this.currentXmlMeasureIndex=0,this.activeKeyHasBeenInitialized=!1,this.abstractInstructions=[],this.openChordSymbolContainers=[],this.soundTempos=new Map,this.xmlNotes=[],this.repetitionInstructionReader=e,this.xmlMeasureList=i,this.musicSheet=s.GetMusicSheet,this.instrument=s,this.activeClefs=new Array(s.Staves.length),this.activeClefsHaveBeenInitialized=new Array(s.Staves.length);for(let r=0;r=this.xmlMeasureList.length)return!1;this.currentMeasure=t,this.followingMultirestMeasures=Math.max(this.followingMultirestMeasures-1,0),this.inSourceMeasureInstrumentIndex=this.musicSheet.getGlobalStaffIndexOfFirstStaff(this.instrument),this.repetitionInstructionReader&&this.repetitionInstructionReader.prepareReadingMeasure(t,this.currentXmlMeasureIndex);let s=new W(0,1),r=new W(0,1),o=!1;this.maxTieNoteFraction=new W(0,1);let a=!1;const l=[];try{const y=this.xmlMeasureList[this.currentXmlMeasureIndex],x=y.elements();if(t.Rules.UseXMLMeasureNumbers&&!Number.isInteger(t.MeasureNumberXML)){const T=parseInt((h=y.attribute("number"))==null?void 0:h.value,10);Number.isInteger(T)&&(t.MeasureNumberXML=T)}let w;for(let T=0;T0&&(w=x[T-1]),E.name==="print"){const C=E.attribute("new-system");(C==null?void 0:C.value)==="yes"&&(t.printNewSystemXml=!0);const P=E.attribute("new-page");(P==null?void 0:P.value)==="yes"&&(t.printNewPageXml=!0)}else if(E.name==="note"){E.element("grace")||(this.xmlNotes.push(E),l.push(E));let C=!0;((c=E.attribute("print-object"))==null?void 0:c.value)==="no"&&(C=!1);let P=1;this.instrument.Staves.length>1&&E.element("staff")&&(P=parseInt(E.element("staff").value,10),isNaN(P)&&(j.debug("InstrumentReader.readNextXmlMeasure.get staff number"),P=1)),this.currentStaff=this.instrument.Staves[P-1];const I=E.element("chord")!==void 0;if(E.element("voice")){const R=parseInt(E.element("voice").value,10);this.currentVoiceGenerator=this.getOrCreateVoiceGenerator(R,P-1)}else(!I||!this.currentVoiceGenerator)&&(this.currentVoiceGenerator=this.getOrCreateVoiceGenerator(1,P-1));let F=0,L=new W(0,1),k=2,v,G=!1;if(E.element("duration")){if(F=parseInt(E.element("duration").value,10),isNaN(F)){const R=Tt.translateText("ReaderErrorMessages/NoteDurationError","Invalid Note Duration.");this.musicSheet.SheetErrors.pushMeasureError(R),j.debug("InstrumentReader.readNextXmlMeasure",R);continue}else if(L=new W(F,4*this.divisions),F===0?L=this.getNoteDurationFromTypeNode(E):v=this.getNoteDurationFromTypeNode(E),E.element("time-modification")){L=this.getNoteDurationForTuplet(E);const R=E.element("time-modification");R!=null&&R.element("normal-notes")&&(k=parseInt(R.element("normal-notes").value,10)),G=!0}}const et=E.element("rest")!==void 0,H=E.element("notations"),nt=E.element("grace")!==void 0||F===0||I&&a;let K=!1,lt=!1;if(nt){const R=E.element("duration"),D=E.element("grace");D&&D.attributes()&&D.attribute("slash")&&D.attribute("slash").value==="yes"&&(K=!0),R||(L=this.getNoteDurationFromTypeNode(E));const Q=E.element("notations");Q&&Q.element("slur")&&(lt=!0)}let A=!1;E.element("cue")&&(A=!0);const ot=E.element("type");let rt=yo.UNDEFINED;if(ot){const R=ot.attribute("size");(R==null?void 0:R.value)==="cue"&&(A=!0),rt=ws.StringToNoteType(ot.value)}let J=Ft.Undefined,ct;const Nt=E.element("stem");if(Nt){switch(Nt.value){case"down":J=Ft.Down;break;case"up":J=Ft.Up;break;case"double":J=Ft.Double;break;case"none":J=Ft.None;break;default:J=Ft.Undefined}const R=Nt.attribute("color");R&&(ct=this.parseXmlColor(R.value))}let pt=0,dt="",Ct="";if(H){const R=H.element("ornaments");if(R){const Q=R.element("tremolo");if(Q){const U=Q.attribute("type");if(dt=U.value,U){const it=parseInt(Q.value,10);it>0&&(pt=it),(U.value==="start"||U.value==="stop")&&(L=new W(parseInt(E.element("duration").value,10),4*this.divisions))}}const $=R.elements("wavy-line");if($!==void 0)for(const U of $){const it=this.expressionReaders[this.readExpressionStaffNumber(E)-1];it&&(it.readExpressionParameters(U,this.instrument,this.divisions,s,r,this.currentMeasure.MeasureNumber,!1),it.addWavyLine(U,this.currentMeasure,s,r))}}const D=H.element("glissando");D&&D.attribute("type").value==="start"&&(Ct="start")}let Ht;const me=E.element("notehead");if(me){const R=me.attribute("color");R&&(Ht=this.parseXmlColor(R.value))}let ce;const _=E.attribute("color");_&&(ce=this.parseXmlColor(_.value),Ht||(Ht=ce),ct||(ct=ce));let Z=s.clone();I&&(Z=r.clone()),this.currentStaffEntry=this.currentMeasure.findOrCreateStaffEntry(Z,this.inSourceMeasureInstrumentIndex+P-1,this.currentStaff).staffEntry,(!this.currentVoiceGenerator.hasVoiceEntry()||!I&&!nt&&!a||nt&&!a||nt&&!I||!nt&&a)&&this.currentVoiceGenerator.createVoiceEntry(Z,this.currentStaffEntry,this.activeKey,this.ActiveRhythm,nt,K,lt),!nt&&!I&&(r=s.clone(),s.Add(L)),I&&this.currentStaffEntry!==void 0&&this.currentStaffEntry.ParentStaff!==this.currentStaff&&(this.currentStaffEntry=this.currentVoiceGenerator.checkForStaffEntryLink(this.inSourceMeasureInstrumentIndex+P-1,this.currentStaff,this.currentStaffEntry,this.currentMeasure));const Y=this.currentStaffEntry!==void 0&&this.currentStaffEntry.Timestamp!==void 0&&this.currentStaffEntry.Timestamp.Equals(new W(0,1))&&!this.currentStaffEntry.hasNotes();this.saveAbstractInstructionList(this.instrument.Staves.length,Y),this.openChordSymbolContainers.length!==0&&(this.currentStaffEntry.ChordContainers=this.openChordSymbolContainers,this.openChordSymbolContainers=[]),this.activeRhythm,!G&&!nt&&(L=new W(F,4*this.divisions));const N=E.elements("dot").length;if(this.currentVoiceGenerator.read(E,L,v,rt,k,et,this.currentStaffEntry,this.currentMeasure,e,this.maxTieNoteFraction,I,i,C,A,nt,J,pt,ct,Ht,N,dt,Ct),H!==void 0&&H.element("dynamics")){const R=this.expressionReaders[this.readExpressionStaffNumber(E)-1];R&&(R.readExpressionParameters(E,this.instrument,this.divisions,s,r,this.currentMeasure.MeasureNumber,!1),R.read(E,this.currentMeasure,r,void 0,l.length))}a=nt}else if(E.name==="attributes"){const C=E.element("divisions");if(C&&(this.divisions=parseInt(C.value,10),isNaN(this.divisions))){const F=Tt.translateText("ReaderErrorMessages/DivisionError","Invalid divisions value at Instrument: ");if(j.debug("InstrumentReader.readNextXmlMeasure",F),this.divisions=this.readDivisionsFromNotes(),this.divisions>0)this.musicSheet.SheetErrors.push(F+this.instrument.Name);else throw o=!0,new Ee(F+this.instrument.Name)}if(!E.element("divisions")&&this.divisions===0&&this.currentXmlMeasureIndex===0){const F=Tt.translateText("ReaderErrorMessages/DivisionError","Invalid divisions value at Instrument: ");if(this.divisions=this.readDivisionsFromNotes(),this.divisions>0)this.musicSheet.SheetErrors.push(F+this.instrument.Name);else throw o=!0,new Ee(F+this.instrument.Name)}this.addAbstractInstruction(E,i,w,s.clone()),s.Equals(new W(0,1))&&this.isAttributesNodeAtBeginOfMeasure(this.xmlMeasureList[this.currentXmlMeasureIndex],E)&&this.saveAbstractInstructionList(this.instrument.Staves.length,!0),this.isAttributesNodeAtEndOfMeasure(this.xmlMeasureList[this.currentXmlMeasureIndex],E)&&this.saveClefInstructionAtEndOfMeasure();const P=E.elements("staff-details");for(const F of P){const L=F.element("staff-lines");if(L){let k=1;const v=F.attribute("number");v&&(k=parseInt(v.value,10)),this.instrument.Staves[k-1].StafflineCount=parseInt(L.value,10)}}const I=E.element("measure-style");if(I){const F=I.element("multiple-rest");if(F){const L=F.value;let k=0;try{k=Number.parseInt(L,10),t.multipleRestMeasures!==void 0&&k!==t.multipleRestMeasures?t.multipleRestMeasures=0:(t.multipleRestMeasures=k,this.currentMultirestStartMeasure=t,this.followingMultirestMeasures=k+1)}catch(v){console.log("multirest parse error: "+v)}}}}else if(E.name==="forward"){const C=parseInt(E.element("duration").value,10);s.Add(new W(C,4*this.divisions))}else if(E.name==="backup"){const C=parseInt(E.element("duration").value,10);s.Sub(new W(C,4*this.divisions)),s.IsNegative()&&(s=new W(0,1)),r.Sub(new W(C,4*this.divisions)),r.IsNegative()&&(r=new W(0,1))}else if(E.name==="direction"){const C=E.elements("direction-type"),P=E.element("direction-type");let I=Math.min(1,s.RealValue);this.activeRhythm!==void 0&&this.activeRhythm.Rhythm&&(I/=this.activeRhythm.Rhythm.RealValue);let F=!1;if(this.repetitionInstructionReader&&(F=this.repetitionInstructionReader.handleRepetitionInstructionsFromWordsOrSymbols(P,I)),!F){let L=this.expressionReaders[0];const k=this.readExpressionStaffNumber(E)-1;if(ket==null?void 0:et.toLocaleLowerCase()).includes((u=v.value)==null?void 0:u.toLocaleLowerCase())&&(this.currentGradualChangeMeasure=this.currentMeasure,this.currentMeasure.speedInfo={startWord:(f=v.value)==null?void 0:f.toLocaleLowerCase(),startXmlNoteIndex:l.length,endXmlNoteIndex:0,resetXmlNoteIndex:0,startMeasureListIndex:this.currentXmlMeasureIndex,endMeasureListIndex:0,resetMeasureListIndex:0},this.xmlNotes=[]),v.value.startsWith(Wa)&&((d=this.currentGradualChangeMeasure)==null?void 0:d.speedInfo)&&(this.currentGradualChangeMeasure.speedInfo=os(be({},this.currentGradualChangeMeasure.speedInfo),{endXmlNoteIndex:this.xmlNotes.length,endMeasureListIndex:this.currentXmlMeasureIndex})),((p=v.value)==null?void 0:p.toLocaleLowerCase())==="a tempo".toLocaleLowerCase()&&((g=this.currentGradualChangeMeasure)==null?void 0:g.speedInfo))){const{endXmlNoteIndex:et,resetXmlNoteIndex:H,endMeasureListIndex:nt}=this.currentGradualChangeMeasure.speedInfo;H===0&&(this.currentGradualChangeMeasure.speedInfo=os(be({},this.currentGradualChangeMeasure.speedInfo),{endXmlNoteIndex:et||this.xmlNotes.length,endMeasureListIndex:nt||this.currentXmlMeasureIndex,resetXmlNoteIndex:this.xmlNotes.length,resetMeasureListIndex:this.currentXmlMeasureIndex})),this.xmlNotes=[]}if(C.find(G=>G.element("metronome"))&&((m=this.currentGradualChangeMeasure)==null?void 0:m.speedInfo)){const{endXmlNoteIndex:G,resetXmlNoteIndex:et,endMeasureListIndex:H}=this.currentGradualChangeMeasure.speedInfo;et===0&&(this.currentGradualChangeMeasure.speedInfo=os(be({},this.currentGradualChangeMeasure.speedInfo),{endXmlNoteIndex:G||this.xmlNotes.length,endMeasureListIndex:H||this.currentXmlMeasureIndex,resetXmlNoteIndex:this.xmlNotes.length,resetMeasureListIndex:this.currentXmlMeasureIndex})),this.xmlNotes=[]}L.readExpressionParameters(E,this.instrument,this.divisions,s,r,this.currentMeasure.MeasureNumber,!1),L.read(E,this.currentMeasure,s,r.clone(),l.length)}}}else if(E.name==="barline"){this.repetitionInstructionReader&&this.repetitionInstructionReader.handleLineRepetitionInstructions(E)&&(this.currentMeasure.HasEndLine=!0);const C=E.attribute("location");if(T===x.length-1||C&&C.value==="right"){const I=(S=E.element("bar-style"))==null?void 0:S.value;if(I&&(this.currentMeasure.endingBarStyleXml=I,this.currentMeasure.endingBarStyleEnum=Wc.xmlBarlineStyleToSystemLinesEnum(I),(b=this.currentGradualChangeMeasure)!=null&&b.speedInfo)){const{endXmlNoteIndex:F,resetXmlNoteIndex:L,endMeasureListIndex:k}=this.currentGradualChangeMeasure.speedInfo;L===0&&(this.currentGradualChangeMeasure.speedInfo=os(be({},this.currentGradualChangeMeasure.speedInfo),{endXmlNoteIndex:F||this.xmlNotes.length,endMeasureListIndex:k||this.currentXmlMeasureIndex,resetXmlNoteIndex:this.xmlNotes.length,resetMeasureListIndex:this.currentXmlMeasureIndex})),this.currentGradualChangeMeasure=void 0,this.xmlNotes=[]}}}else if(E.name==="sound")try{if(E.attribute("tempo")){const C=parseFloat(E.attribute("tempo").value);E.element("offset")&&(this.soundTempos.has(this.currentXmlMeasureIndex)||this.soundTempos.set(this.currentXmlMeasureIndex,[]),this.soundTempos.get(this.currentXmlMeasureIndex).push(C)),this.currentXmlMeasureIndex===0&&(this.musicSheet.DefaultStartTempoInBpm=C,this.musicSheet.HasBPMInfo=!0)}}catch(C){j.debug("InstrumentReader.readTempoInstruction",C)}else E.name==="harmony"&&this.openChordSymbolContainers.push(Yu.readChordSymbol(E,this.musicSheet,this.activeKey))}for(const T in this.voiceGeneratorsDict)this.voiceGeneratorsDict.hasOwnProperty(T)&&this.voiceGeneratorsDict[T].checkForOpenBeam();if(this.currentXmlMeasureIndex===this.xmlMeasureList.length-1){for(let T=0;T{this.voiceGeneratorsDict[T].finalizeReadingMeasure()}),this.musicSheet.HasBPMInfo?t.TempoInBPM===0&&this.previousMeasure&&(this.currentMeasure.TempoInBPM=this.previousMeasure.TempoInBPM):this.currentMeasure.TempoInBPM=120,this.currentMeasure.TempoInBPM||(this.currentMeasure.TempoInBPM=this.musicSheet.DefaultStartTempoInBpm)}catch(y){if(o)throw new Ee(y.Message);const x=Tt.translateText("ReaderErrorMessages/MeasureError","Error while reading Measure.");this.musicSheet.SheetErrors.pushMeasureError(x),j.debug("InstrumentReader.readNextXmlMeasure",x,y)}return this.previousMeasure=this.currentMeasure,this.currentXmlMeasureIndex+=1,!0}parseXmlColor(t){if(!!t)return t.length===7?t:t.length===9?"#"+t.substr(3):void 0}doCalculationsAfterDurationHasBeenSet(){for(const t in this.voiceGeneratorsDict)this.voiceGeneratorsDict.hasOwnProperty(t)&&this.voiceGeneratorsDict[t].checkOpenTies()}getOrCreateVoiceGenerator(t,e){const i=this.instrument.Staves[e];let s=this.voiceGeneratorsDict[t];if(s)i.Voices.indexOf(s.GetVoice)===-1&&i.Voices.push(s.GetVoice);else{const r=this.staffMainVoiceGeneratorDict[e];r?(s=new ha(this.pluginManager,i,t,this.slurReader,r.GetVoice),i.Voices.push(s.GetVoice),this.voiceGeneratorsDict[t]=s):(s=new ha(this.pluginManager,i,t,this.slurReader),i.Voices.push(s.GetVoice),this.voiceGeneratorsDict[t]=s,this.staffMainVoiceGeneratorDict[e]=s)}return s}createExpressionGenerators(t){this.expressionReaders=new Array(t);for(let e=0;e0?e=this.musicSheet.SourceMeasures[0]:e=this.currentMeasure;const i=new Wt(Pt.G,0,2);let s;e.FirstInstructionsStaffEntries[t]?(s=e.FirstInstructionsStaffEntries[t],s.removeFirstInstructionOfTypeClefInstruction()):(s=new we(void 0,void 0),e.FirstInstructionsStaffEntries[t]=s),i.Parent=s,s.Instructions.splice(0,0,i)}createDefaultKeyInstruction(){let t;this.musicSheet.SourceMeasures.length>0?t=this.musicSheet.SourceMeasures[0]:t=this.currentMeasure;const e=new xe(void 0,0,bi.major);for(let i=this.inSourceMeasureInstrumentIndex;i0&&i[s-1].name==="backup")return!0;let r=-1;for(let o=0;o0||r<0}isAttributesNodeAtEndOfMeasure(t,e){const i=t.elements().slice();let s=0;for(let o=0;or}getNoteDurationFromTypeNode(t){const e=t.element("type");if(e){const i=e.value;return ws.getNoteDurationFromType(i)}return new W(0,4*this.divisions)}addAbstractInstruction(t,e,i,s){if(t.element("divisions")&&t.elements().length===1)return;const r=t.element("transpose");if(r){const l=r.element("chromatic");l&&(this.instrument.PlaybackTranspose=parseInt(l.value,10))}const o=t.elements("clef");let a;if(o.length>0)for(let l=0,h=o.length;l using default clef line."),this.musicSheet.SheetErrors.pushMeasureError(a),f=2,j.debug("InstrumentReader.addAbstractInstruction",a,y)}const m=c.element("sign");if(m)try{u=Pt[m.value],Wt.isSupportedClef(u)||(a=Tt.translateText("ReaderErrorMessages/ClefError","Unsupported clef found -> using default clef."),this.musicSheet.SheetErrors.pushMeasureError(a),u=Pt.G,f=2),u===Pt.TAB&&(p=-1)}catch(y){a=Tt.translateText("ReaderErrorMessages/ClefError","Invalid clef found -> using default clef."),this.musicSheet.SheetErrors.pushMeasureError(a),u=Pt.G,f=2,j.debug("InstrumentReader.addAbstractInstruction",a,y)}const S=c.element("clef-octave-change");if(S)try{p=parseInt(S.value,10)}catch{a=Tt.translateText("ReaderErrorMessages/ClefOctaveError","Invalid clef octave found -> using default clef octave."),this.musicSheet.SheetErrors.pushMeasureError(a),p=0}if(c.hasAttributes&&c.attribute("number"))try{d=parseInt(c.attribute("number").value,10),d>this.currentClefNumber&&(d=this.currentClefNumber),this.currentClefNumber=d+1}catch{a=Tt.translateText("ReaderErrorMessages/ClefError","Invalid clef found -> using default clef."),this.musicSheet.SheetErrors.pushMeasureError(a),d=1,this.currentClefNumber=d+1}const b=new Wt(u,p,f);this.abstractInstructions.push([d,b,s])}if(t.element("key")!==void 0&&this.instrument.MidiInstrumentId!==st.Percussion){let l=0;const h=t.element("key").element("fifths");if(h)try{l=parseInt(h.value,10)}catch(d){a=Tt.translateText("ReaderErrorMessages/KeyError","Invalid key found -> set to default."),this.musicSheet.SheetErrors.pushMeasureError(a),l=0,j.debug("InstrumentReader.addAbstractInstruction",a,d)}let c=bi.none,u=t.element("key");if(u&&(u=u.element("mode")),u)try{c=bi[u.value]}catch(d){a=Tt.translateText("ReaderErrorMessages/KeyError","Invalid key found -> set to default."),this.musicSheet.SheetErrors.pushMeasureError(a),c=bi.major,j.debug("InstrumentReader.addAbstractInstruction",a,d)}const f=new xe(void 0,l,c);this.abstractInstructions.push([1,f,s])}if(t.element("time")){const l=t.element("time");let h=ii.NONE,c=!0;if(l!==void 0&&l.hasAttributes){const S=l.attribute("symbol");S&&(S.value==="common"?h=ii.COMMON:S.value==="cut"&&(h=ii.CUT));const b=l.attribute("print-object");b&&b.value==="no"&&(c=!1)}let u=0,f=0;const d=l&&l.element("senza-misura")!==void 0,p=t.elements("time"),g=[],m=[];for(let S=0,b=p.length;S0&&m!==void 0&&g.length===m.length){const b=g.length,y=new Array(b);let x=0;for(let w=0;w set to default."),this.musicSheet.SheetErrors.pushMeasureError(a),u=4,f=4,j.debug("InstrumentReader.addAbstractInstruction",a,b)}const S=new Ae(new W(u,f,0,!1),h);S.PrintObject=c,this.abstractInstructions.push([1,S,s])}}}saveAbstractInstructionList(t,e){for(let i=this.abstractInstructions.length-1;i>=0;i--){const s=this.abstractInstructions[i],r=s[0],o=s[1],a=s[2];if(o instanceof Wt){const l=o;if(this.currentXmlMeasureIndex===0||r<=this.activeClefs.length&&l!==this.activeClefs[r-1])if(!e&&this.currentStaffEntry!==void 0&&!this.currentStaffEntry.hasNotes()&&r-1===this.instrument.Staves.indexOf(this.currentStaffEntry.ParentStaff)){const h=l,c=this.currentStaffEntry;if(a&&Math.abs(a.RealValue-c.Timestamp.RealValue)>.01)continue;h.Parent=c,c.removeFirstInstructionOfTypeClefInstruction(),c.Instructions.push(h),this.activeClefs[r-1]=l,this.abstractInstructions.splice(i,1)}else if(e){if(a.RealValue!==0)continue;let h;if(this.currentMeasure){const c=l,u=this.inSourceMeasureInstrumentIndex+r-1,f=this.currentMeasure.FirstInstructionsStaffEntries[u];if(this.currentXmlMeasureIndex===0)if(!f)h=new we(void 0,void 0),this.currentMeasure.FirstInstructionsStaffEntries[u]=h,c.Parent=h,h.Instructions.push(c),this.activeClefsHaveBeenInitialized[r-1]=!0;else if(this.currentMeasure.FirstInstructionsStaffEntries[u]!==void 0&&!(f.Instructions[0]instanceof Wt))h=f,c.Parent=h,h.removeFirstInstructionOfTypeClefInstruction(),h.Instructions.splice(0,0,c),this.activeClefsHaveBeenInitialized[r-1]=!0;else{const d=new we(void 0,void 0);this.currentMeasure.LastInstructionsStaffEntries[u]=d,c.Parent=d,d.Instructions.push(c)}else if(this.activeClefsHaveBeenInitialized[r-1]){let d=this.previousMeasure;this.followingMultirestMeasures>0&&this.currentMeasure.Rules.RenderMultipleRestMeasures&&(d=this.currentMultirestStartMeasure);const p=new we(void 0,void 0);d.LastInstructionsStaffEntries[u]=p,c.Parent=p,p.Instructions.push(c)}else{const d=this.musicSheet.SourceMeasures[0];d.FirstInstructionsStaffEntries[u]?(h=d.FirstInstructionsStaffEntries[u],h.removeFirstInstructionOfTypeClefInstruction()):h=new we(void 0,void 0),c.Parent=h,h.Instructions.splice(0,0,c),this.activeClefsHaveBeenInitialized[r-1]=!0}this.activeClefs[r-1]=l,this.abstractInstructions.splice(i,1)}}else{let h;const c=this.activeRhythm.Rhythm;c.RealValue>0&&a.RealValue/c.RealValue>.9&&(this.currentMeasure.LastInstructionsStaffEntries[r-1]||(this.currentMeasure.LastInstructionsStaffEntries[r-1]=new we(void 0,this.instrument.Staves[r-1])),h=this.currentMeasure.LastInstructionsStaffEntries[r-1]),h&&(l.Parent=h,h.Instructions.push(l),this.activeClefs[r-1]=l,this.abstractInstructions.splice(i,1))}else r<=this.activeClefs.length&&l===this.activeClefs[r-1]&&this.abstractInstructions.splice(i,1)}if(o instanceof xe){const l=o;if(!this.activeKey||this.activeKey.Key!==l.Key){this.activeKey=l,this.abstractInstructions.splice(i,1);let h;if(this.activeKeyHasBeenInitialized?h=this.currentMeasure:(this.activeKeyHasBeenInitialized=!0,this.currentXmlMeasureIndex>0?h=this.musicSheet.SourceMeasures[0]:h=this.currentMeasure),h)for(let c=this.inSourceMeasureInstrumentIndex;c=0;t--){const e=this.abstractInstructions[t][0],i=this.abstractInstructions[t][1];if(i instanceof Wt){const s=i;if(!this.activeClefs[e-1]||s.ClefType!==this.activeClefs[e-1].ClefType||s.ClefType===this.activeClefs[e-1].ClefType&&s.Line!==this.activeClefs[e-1].Line){const r=new we(void 0,void 0);this.currentMeasure.LastInstructionsStaffEntries[this.inSourceMeasureInstrumentIndex+e-1]=r;const o=s;o.Parent=r,r.Instructions.push(o),this.activeClefs[e-1]=s,this.abstractInstructions.splice(t,1)}}}}getNoteDurationForTuplet(t){let e=new W(0,1);const i=this.getNoteDurationFromTypeNode(t);if(t.element("time-modification")){const s=t.element("time-modification");if(s&&s.element("actual-notes")!==void 0&&s.element("normal-notes")){const r=s.element("actual-notes"),o=s.element("normal-notes");if(r!==void 0&&o){const a=parseInt(r.value,10),l=parseInt(o.value,10);e=new W(l*i.Numerator,a*i.Denominator)}}}return e}readExpressionStaffNumber(t){let e=1;if(t.element("staff")){const i=t.element("staff");if(i)try{e=parseInt(i.value,10)}catch(s){const r=Tt.translateText("ReaderErrorMessages/ExpressionStaffError","Invalid Expression staff number -> set to default.");this.musicSheet.SheetErrors.pushMeasureError(r),e=1,j.debug("InstrumentReader.readExpressionStaffNumber",r,s)}}return e}readDivisionsFromNotes(){let t=0,e=this.currentXmlMeasureIndex,i=!1;for(;!i;){const s=this.xmlMeasureList[e].elements();for(let r=0,o=s.length;r0){i=!0;break}}if(t===0&&(e++,e===this.xmlMeasureList.length)){const r=Tt.translateText("ReaderErrorMEssages/DivisionsError","Invalid divisions value at Instrument: ");throw new Ee(r+this.instrument.Name)}}return t}}const Gs=class{constructor(n){this.parentInstrument=n,this.fixedKey=-1,this.name=this.parseMidiInstrument(this.parentInstrument.Name),this.midiInstrumentID=Gs.midiInstrument[this.name],this.volume=1}get ParentInstrument(){return this.parentInstrument}static isPianoInstrument(n){return n===st.Acoustic_Grand_Piano||n===st.Bright_Acoustic_Piano||n===st.Electric_Grand_Piano||n===st.Electric_Piano_1||n===st.Electric_Piano_2}setMidiInstrument(n){this.midiInstrumentID=Gs.midiInstrument[this.parseMidiInstrument(n)]}parseMidiInstrument(n){try{if(n){let t=n.toLowerCase().trim();t=t.replace(/\s+/g,"_");for(const e in Gs.midiInstrument)if(t.indexOf(e)!==-1)return e}if(this.parentInstrument.Name){let t=this.parentInstrument.Name.toLowerCase().trim();t=t.replace(/\s+/g,"_");for(const e in Gs.midiInstrument)if(t.indexOf(e)!==-1)return e}}catch{j.error("Error parsing MIDI Instrument. Default to Grand Piano.")}return"unnamed"}};let Nr=Gs;Nr.midiInstrument={alto_saxophone:st.Alto_Sax,baritone_saxophone:st.Baritone_Sax,horn_in_f:st.French_Horn,english_horn:st.English_Horn,euphonium:st.Euphonium,clarinet_in_bb:st.clarinet_in_bb,clarinet_in_eb:st.clarinet_in_eb,clarinet:st.Clarinet,alto_clarinet:st.Alto_Clarinet,bass_clarinet:st.Bass_Clarinet,bassoon:st.Bassoon,bass_trombone:st.Bass_Trombone,alt:st.Synth_Voice,alto:st.Synth_Voice,banjo:st.Banjo,bariton:st.Synth_Voice,baritone:st.Synth_Voice,bass:st.Synth_Voice,blockfl\u00F6te:st.Recorder,brass:st.Trombone,bratsche:st.Viola,cello:st.Cello,contrabass:st.Contrabass,drums:st.Percussion,flute:st.Flute,fl\u00F6te:st.Flute,frenchhorn:st.French_Horn,gitarre:st.Acoustic_Guitar_nylon,guitar:st.Acoustic_Guitar_nylon,harfe:st.Orchestral_Harp,harp:st.Orchestral_Harp,klarinette:st.Clarinet,klavier:st.Acoustic_Grand_Piano,kontrabass:st.Contrabass,oboe:st.Oboe,organ:st.Church_Organ,orgel:st.Church_Organ,orgue:st.Church_Organ,percussion:st.Synth_Drum,\u5C0F\u519B\u9F13:st.Synth_Drum,snare_drum:st.Synth_Drum,bass_drum:st.Synth_Drum,side_drum:st.Synth_Drum,piano:st.Acoustic_Grand_Piano,piccolo:st.Piccolo,posaune:st.Trombone,recorder:st.Recorder,sax:st.Tenor_Sax,schlagwerk:st.Percussion,schlagzeug:st.Percussion,sopran:st.Synth_Voice,steeldrum:st.Steel_Drums,streicher:st.String_Ensemble_1,strings:st.String_Ensemble_1,tenor:st.Synth_Voice,tpt:st.Trumpet,trombone:st.Trombone,trompete:st.Trumpet,trumpet:st.Trumpet,tuba:st.Tuba,unnamed:st.Acoustic_Grand_Piano,viola:st.Viola,violin:st.Violin,"violon-c":st.Cello,"violon.":st.Violin,voice:st.Synth_Voice,woodblock:st.Woodblock,alto_clarinet_in_eb:st.AltoClarinetInEb,trumpet_in_bb:st.TrumpetInBb,tenor_saxophone:st.TenorSaxophone};class Ue{static StringContainsSeparatedWord(t,e,i=!1){return new RegExp("( |^)"+e+"([ .]|$)",i?"i":void 0).test(t)}}class Qu{set MusicSheet(t){this.musicSheet=t,this.xmlMeasureList=new Array(this.musicSheet.Instruments.length),this.repetitionInstructions=[]}prepareReadingMeasure(t,e){this.currentMeasureIndex=e}handleLineRepetitionInstructions(t){let e=!1;if(t.elements().length>0){let i="",s=!1,r="",o="",a="";const l=[],h=t.element("bar-style");h&&(a=h.value),t.attributes().length>0&&t.attribute("location")?i=t.attribute("location").value:i="right";const c=t.elements();for(let u=0,f=c.length;u0)if(i==="left"){if(o==="start"){const u=new It(this.currentMeasureIndex,q.Ending,Dt.Begin,void 0,l);this.addInstruction(this.repetitionInstructions,u)}if(r==="forward"){const u=new It(this.currentMeasureIndex,q.StartLine);this.addInstruction(this.repetitionInstructions,u)}}else{if(o==="stop"){const u=new It(this.currentMeasureIndex,q.Ending,Dt.End,void 0,l);this.addInstruction(this.repetitionInstructions,u)}if(r==="backward"){const u=new It(this.currentMeasureIndex,q.BackJumpLine);this.addInstruction(this.repetitionInstructions,u)}}}return e}handleRepetitionInstructionsFromWordsOrSymbols(t,e){const i=t.element("words"),s=this.currentMeasureIndex;if(i){const r="d\\s?\\.s\\.",o=i.value.trim().toLowerCase();if(Ue.StringContainsSeparatedWord(o,r+" al fine",!0)){const l=new It(s,q.DalSegnoAlFine);return this.addInstruction(this.repetitionInstructions,l),!0}if(Ue.StringContainsSeparatedWord(o,r+" al coda",!0)){const l=new It(s,q.DalSegnoAlCoda);return this.addInstruction(this.repetitionInstructions,l),!0}const a="d\\.\\s?c\\.";if(Ue.StringContainsSeparatedWord(o,a+" al fine",!0)){const l=new It(s,q.DaCapoAlFine);return this.addInstruction(this.repetitionInstructions,l),!0}if(Ue.StringContainsSeparatedWord(o,a+" al coda",!0)){const l=new It(s,q.DaCapoAlCoda);return this.addInstruction(this.repetitionInstructions,l),!0}if(Ue.StringContainsSeparatedWord(o,a)||Ue.StringContainsSeparatedWord(o,"da\\s?capo",!0)){const l=new It(s,q.DaCapo);return this.addInstruction(this.repetitionInstructions,l),!0}if(Ue.StringContainsSeparatedWord(o,r,!0)||Ue.StringContainsSeparatedWord(o,"dal\\s?segno",!0)){let l;return Ue.StringContainsSeparatedWord(o,"al\\s?coda",!0)?l=new It(s,q.DalSegnoAlCoda):l=new It(s,q.DalSegno),this.addInstruction(this.repetitionInstructions,l),!0}if(Ue.StringContainsSeparatedWord(o,"to\\s?coda",!0)||Ue.StringContainsSeparatedWord(o,"a (la )?coda",!0)){const l=new It(s,q.ToCoda);return this.addInstruction(this.repetitionInstructions,l),!0}if(Ue.StringContainsSeparatedWord(o,"fine",!0)){const l=new It(s,q.Fine);return this.addInstruction(this.repetitionInstructions,l),!0}if(Ue.StringContainsSeparatedWord(o,"coda",!0)){const l=new It(s,q.Coda);return this.addInstruction(this.repetitionInstructions,l),!0}if(Ue.StringContainsSeparatedWord(o,"segno",!0)){const l=new It(s,q.Segno);return this.addInstruction(this.repetitionInstructions,l),!0}}else if(t.element("segno")){const r=new It(s,q.Segno);return this.addInstruction(this.repetitionInstructions,r),!0}else if(t.element("coda")){const r=new It(s,q.Coda);return this.addInstruction(this.repetitionInstructions,r),!0}return!1}removeRedundantInstructions(){let t=0,e=0,i=0,s=0;for(let r=0;r0&&this.findInstructionInPreviousMeasure(r,o.measureIndex,q.ToCoda)&&(o.type=q.None),e===0&&i===0&&(o.type=q.ToCoda,o.alignment=Dt.End,o.measureIndex--);break;case q.Segno:if(t-s>0){let a=!1;for(let l=0,h=this.repetitionInstructions.length;l0?c.type=q.DalSegnoAlCoda:c.type=q.DalSegno,o.type=q.None,a=!0;break;case q.DalSegno:case q.DalSegnoAlFine:case q.DalSegnoAlCoda:o.type=q.None,a=!0;break}if(a)break}if(a)break;i-e>0?o.type=q.DalSegnoAlCoda:o.type=q.DalSegno,o.alignment=Dt.End,o.measureIndex--}break}if(this.backwardSearchForPreviousIdenticalInstruction(r,o)||o.type===q.None)this.repetitionInstructions.splice(r,1),r--;else switch(o.type){case q.Fine:break;case q.ToCoda:i++;break;case q.Coda:e++;break;case q.Segno:t++;break;case q.DalSegnoAlFine:case q.DalSegnoAlCoda:s++;break}}this.repetitionInstructions.sort(Mr.Compare)}findInstructionInPreviousMeasure(t,e,i){for(let s=t-1;s>=0;s--){const r=this.repetitionInstructions[s];if(e-r.measureIndex===1&&r.type===i)return!0}return!1}backwardSearchForPreviousIdenticalInstruction(t,e){for(let i=t-1;i>=0;i--)if(this.repetitionInstructions[i].equals(e))return!0;return!1}addInstruction(t,e){let i=!0;for(let s=0,r=t.length;s0;)try{const a=this.openRepetitions.last();if(a.RepetitonUnderConstruction.FromWords){if(a.WaitingForCoda){let l=a.RepetitonUnderConstruction.BackwardJumpInstructions.last().measureIndex+1;l>=this.musicSheet.SourceMeasures.length&&(l=-1),a.RepetitonUnderConstruction.setEndingStartIndex(2,l)}else if(a.RepetitonUnderConstruction.BackwardJumpInstructions.length===0){this.openRepetitions.splice(this.openRepetitions.length-1,1);continue}}else if(a.RepetitonUnderConstruction.BackwardJumpInstructions.length===0){const l=i.length-1,h=new It(l,q.BackJumpLine,Dt.End,a.RepetitonUnderConstruction);a.RepetitonUnderConstruction.BackwardJumpInstructions.push(h),i[l].LastRepetitionInstructions.push(h)}this.finalizeRepetition(this.openRepetitions.last())}catch{try{const l=this.openRepetitions.last().RepetitonUnderConstruction;for(const h of this.repetitionInstructions)h.parentRepetition===l&&(h.parentRepetition=void 0);this.openRepetitions.splice(this.openRepetitions.length-1,1)}catch(l){j.error("RepetitionCalculator: calculateRepetitions2",l)}}let s=!1;const r=0,o=this.musicSheet.SourceMeasures.length-1;for(const a of this.musicSheet.Repetitions)if(a.StartIndex===r&&a.EndIndex===o){s=!0;break}if(!s){const a=new Dn(this.musicSheet,!0);a.FromWords=!0,a.startMarker=new It(r,q.StartLine),a.startMarker.parentRepetition=a,this.musicSheet.SourceMeasures[r].FirstRepetitionInstructions.push(a.startMarker),a.endMarker=new It(o,q.BackJumpLine),a.endMarker.parentRepetition=a,a.BackwardJumpInstructions.push(a.endMarker),a.UserNumberOfRepetitions=a.DefaultNumberOfRepetitions,this.musicSheet.Repetitions.push(a)}for(let a=0,l=this.musicSheet.SourceMeasures.length;a1&&h.FirstRepetitionInstructions.sort(Mr.Compare),h.LastRepetitionInstructions.length>1&&h.LastRepetitionInstructions.sort(Mr.Compare)}}handleRepetitionInstructions(t){let e;switch(t.type){case q.StartLine:e=this.createNewRepetition(this.currentMeasureIndex),t.parentRepetition=e.RepetitonUnderConstruction,e.RepetitonUnderConstruction.FromWords=!1,e.RepetitonUnderConstruction.startMarker=t,this.currentMeasure.FirstRepetitionInstructions.push(t);break;case q.BackJumpLine:e=this.getOrCreateCurrentRepetition2(!1),t.parentRepetition=e.RepetitonUnderConstruction,e.RepetitonUnderConstruction.BackwardJumpInstructions.push(t),this.currentMeasure.LastRepetitionInstructions.push(t),e.RepetitonUnderConstruction.EndingParts.length===0&&this.finalizeRepetition(e);break;case q.Ending:if(e=this.getOrCreateCurrentRepetition(),t.parentRepetition=e.RepetitonUnderConstruction,t.endingIndices.contains(1)&&t.alignment===Dt.Begin){if(e.RepetitonUnderConstruction.BackwardJumpInstructions.length>0||e.RepetitonUnderConstruction.EndingIndexDict.hasOwnProperty(1)){e=void 0;for(let s=this.openRepetitions.length-1;s>=0;s--){const r=this.openRepetitions[s];if(r.RepetitonUnderConstruction.BackwardJumpInstructions.length===0)for(e=r;this.openRepetitions.length-1>s;){const o=this.openRepetitions.last();this.finalizeRepetition(o)}}e===void 0&&(e=this.createNewRepetition(0),e.RepetitonUnderConstruction.startMarker=new It(0,q.None))}e.RepetitonUnderConstruction.forwardJumpInstruction===void 0&&(e.RepetitonUnderConstruction.forwardJumpInstruction=new It(this.currentMeasureIndex-1,q.ForwardJump,Dt.End,e.RepetitonUnderConstruction),this.musicSheet.SourceMeasures[this.currentMeasureIndex-1].LastRepetitionInstructions.push(e.RepetitonUnderConstruction.forwardJumpInstruction))}if(t.alignment===Dt.Begin)e.RepetitonUnderConstruction.setEndingsStartIndex(t.endingIndices,this.currentMeasureIndex),this.currentMeasure.FirstRepetitionInstructions.push(t);else for(let s=0,r=t.endingIndices.length;s0&&Math.abs(e.RepetitonUnderConstruction.BackwardJumpInstructions.last().measureIndex-this.currentMeasureIndex)<=1||this.openRepetitions.length&&this.openRepetitions.find(s=>s.RepetitonUnderConstruction.startMarker.type===q.StartLine).RepetitonUnderConstruction.StartIndex===this.currentMeasureIndex)break;e=this.createNewRepetition(this.currentMeasureIndex),t.parentRepetition=e.RepetitonUnderConstruction,e.RepetitonUnderConstruction.FromWords=!0,e.SegnoFound=!0,e.RepetitonUnderConstruction.startMarker=t,this.currentMeasure.FirstRepetitionInstructions.push(t);break;case q.Fine:if(this.openRepetitions.length===0||(e=this.getCurrentRepetition(!0),e===void 0))break;t.parentRepetition=e.RepetitonUnderConstruction,e.RepetitonUnderConstruction.FromWords=!0,e.RepetitonUnderConstruction.forwardJumpInstruction===void 0?(e.FineFound=!0,e.RepetitonUnderConstruction.forwardJumpInstruction=t,e.RepetitonUnderConstruction.setEndingStartIndex(2,-2),this.currentMeasure.LastRepetitionInstructions.push(t)):this.currentMeasure.LastRepetitionInstructions.push(new It(this.currentMeasureIndex,q.Fine,Dt.End,void 0));break;case q.ToCoda:if(this.openRepetitions.length===0||(e=this.getCurrentRepetition(!0),e===void 0))break;e.RepetitonUnderConstruction.forwardJumpInstruction===void 0&&(t.parentRepetition=e.RepetitonUnderConstruction,e.RepetitonUnderConstruction.FromWords=!0,e.ToCodaFound=!0,e.RepetitonUnderConstruction.forwardJumpInstruction=t,this.currentMeasure.LastRepetitionInstructions.push(t));break;case q.Coda:if(this.openRepetitions.length===0)break;e=this.getOrCreateCurrentRepetition2(!0),t.parentRepetition=e.RepetitonUnderConstruction,e.WaitingForCoda?(e.CodaFound=!0,e.RepetitonUnderConstruction.setEndingStartIndex(2,this.currentMeasureIndex),this.currentMeasure.LastRepetitionInstructions.push(t),this.finalizeRepetition(e),this.currentMeasureIndex>0&&(this.musicSheet.SourceMeasures[this.currentMeasureIndex-1].printNewSystemXml=!0)):e.ToCodaFound||(e.RepetitonUnderConstruction.BackwardJumpInstructions.length===0?(e.ToCodaFound=!0,e.RepetitonUnderConstruction.forwardJumpInstruction=new It(this.currentMeasureIndex,q.ToCoda,Dt.End,e.RepetitonUnderConstruction),this.currentMeasure.LastRepetitionInstructions.push(e.RepetitonUnderConstruction.forwardJumpInstruction)):this.currentMeasure.LastRepetitionInstructions.push(new It(this.currentMeasureIndex,q.Coda,Dt.Begin,void 0)));break;case q.DaCapo:e=this.getOrCreateCurrentRepetition(),e.RepetitonUnderConstruction.BackwardJumpInstructions.length>0&&this.finalizeRepetition(e),e.RepetitonUnderConstruction.StartIndex!==0&&(e=this.createNewRepetition(0)),t.parentRepetition=e.RepetitonUnderConstruction,e.RepetitonUnderConstruction.FromWords=!0,e.RepetitonUnderConstruction.startMarker=new It(0,q.None,Dt.Begin,e.RepetitonUnderConstruction),e.RepetitonUnderConstruction.BackwardJumpInstructions.push(t),this.currentMeasure.LastRepetitionInstructions.push(t),e.RepetitonUnderConstruction.EndingParts.length===0&&this.finalizeRepetition(e);break;case q.DalSegno:if(e=this.getOrCreateCurrentRepetition2(!0),e.RepetitonUnderConstruction.BackwardJumpInstructions.length>0&&(this.finalizeRepetition(e),e=this.createNewRepetition(0),e.RepetitonUnderConstruction.FromWords=!0,e.RepetitonUnderConstruction.startMarker=new It(0,q.None,Dt.Begin,e.RepetitonUnderConstruction)),t.parentRepetition=e.RepetitonUnderConstruction,!e.SegnoFound){const s=this.findInstructionInMainListBackwards(q.Segno,t.measureIndex);s>=0&&(e.SegnoFound=!0,e.RepetitonUnderConstruction.startMarker=new It(s,q.Segno,Dt.Begin,e.RepetitonUnderConstruction),this.musicSheet.SourceMeasures[s].FirstRepetitionInstructions.splice(0,0,e.RepetitonUnderConstruction.startMarker))}e.RepetitonUnderConstruction.EndingIndexDict.hasOwnProperty(1)&&e.RepetitonUnderConstruction.setEndingEndIndex(1,this.currentMeasureIndex),e.RepetitonUnderConstruction.BackwardJumpInstructions.push(t),this.currentMeasure.LastRepetitionInstructions.push(t);break;case q.DalSegnoAlFine:if(this.openRepetitions.length===0)break;if(e=this.getOrCreateCurrentRepetition2(!0),t.parentRepetition=e.RepetitonUnderConstruction,!e.SegnoFound){const s=this.findInstructionInMainListBackwards(q.Segno,t.measureIndex);s>=0&&(e.SegnoFound=!0,e.RepetitonUnderConstruction.startMarker=new It(s,q.Segno,Dt.Begin,e.RepetitonUnderConstruction),this.musicSheet.SourceMeasures[s].FirstRepetitionInstructions.splice(0,0,e.RepetitonUnderConstruction.startMarker))}if(!e.FineFound){const s=this.findInstructionInMainListBackwards(q.Fine,t.measureIndex);s>=0&&(e.FineFound=!0,e.RepetitonUnderConstruction.forwardJumpInstruction=new It(s,q.Fine,Dt.Begin,e.RepetitonUnderConstruction),e.RepetitonUnderConstruction.setEndingStartIndex(2,-2),this.musicSheet.SourceMeasures[s].LastRepetitionInstructions.splice(0,0,e.RepetitonUnderConstruction.forwardJumpInstruction))}e.RepetitonUnderConstruction.EndingIndexDict.hasOwnProperty(1)||e.RepetitonUnderConstruction.setEndingEndIndex(1,this.currentMeasureIndex),e.RepetitonUnderConstruction.BackwardJumpInstructions.push(t),this.currentMeasure.LastRepetitionInstructions.push(t);break;case q.DaCapoAlFine:if(e=this.getOrCreateCurrentRepetition(),e.RepetitonUnderConstruction.BackwardJumpInstructions.length>0&&(this.finalizeRepetition(e),e=this.createNewRepetition(0)),e.RepetitonUnderConstruction.startMarker!==void 0&&e.RepetitonUnderConstruction.StartIndex!==0&&(e=this.createNewRepetition(0)),e.RepetitonUnderConstruction.startMarker=new It(0,q.None,Dt.Begin,e.RepetitonUnderConstruction),e.RepetitonUnderConstruction.FromWords=!0,t.parentRepetition=e.RepetitonUnderConstruction,!e.FineFound){const s=this.findInstructionInMainListBackwards(q.Fine,t.measureIndex);s>=0&&(e.FineFound=!0,e.RepetitonUnderConstruction.forwardJumpInstruction=new It(s,q.Fine,Dt.Begin,e.RepetitonUnderConstruction),e.RepetitonUnderConstruction.setEndingStartIndex(2,-2),this.musicSheet.SourceMeasures[s].LastRepetitionInstructions.splice(0,0,e.RepetitonUnderConstruction.forwardJumpInstruction))}e.RepetitonUnderConstruction.EndingIndexDict.hasOwnProperty(1)||e.RepetitonUnderConstruction.setEndingEndIndex(1,this.currentMeasureIndex),e.RepetitonUnderConstruction.BackwardJumpInstructions.push(t),this.currentMeasure.LastRepetitionInstructions.push(t);break;case q.DalSegnoAlCoda:if(this.openRepetitions.length===0)break;if(e=this.getOrCreateCurrentRepetition2(!0),t.parentRepetition=e.RepetitonUnderConstruction,!e.SegnoFound){const s=this.findInstructionInMainListBackwards(q.Segno,t.measureIndex);s>=0&&(e.SegnoFound=!0,e.RepetitonUnderConstruction.startMarker=new It(s,q.Segno,Dt.Begin,e.RepetitonUnderConstruction),this.musicSheet.SourceMeasures[s].FirstRepetitionInstructions.splice(0,0,e.RepetitonUnderConstruction.startMarker))}if(!e.ToCodaFound){const s=this.findInstructionInMainListBackwards(q.ToCoda,t.measureIndex);if(s>=0)e.RepetitonUnderConstruction.forwardJumpInstruction=new It(s,q.ToCoda,Dt.Begin,e.RepetitonUnderConstruction),this.musicSheet.SourceMeasures[s].LastRepetitionInstructions.splice(0,0,e.RepetitonUnderConstruction.forwardJumpInstruction),e.ToCodaFound=!0;else{const r=this.findInstructionInMainListBackwards(q.Coda,t.measureIndex);r>=0&&(e.RepetitonUnderConstruction.forwardJumpInstruction=new It(r,q.ToCoda,Dt.Begin,e.RepetitonUnderConstruction),this.musicSheet.SourceMeasures[r].LastRepetitionInstructions.splice(0,0,e.RepetitonUnderConstruction.forwardJumpInstruction),e.ToCodaFound=!0)}}e.ToCodaFound&&(e.WaitingForCoda=!0),e.RepetitonUnderConstruction.EndingIndexDict.hasOwnProperty(1)||e.RepetitonUnderConstruction.setEndingEndIndex(1,this.currentMeasureIndex),e.RepetitonUnderConstruction.BackwardJumpInstructions.push(t),this.currentMeasure.LastRepetitionInstructions.push(t);break;case q.DaCapoAlCoda:if(e=this.getOrCreateCurrentRepetition(),e.RepetitonUnderConstruction.BackwardJumpInstructions.length>0?(this.finalizeRepetition(e),e=this.createNewRepetition(0)):e.RepetitonUnderConstruction.EndingParts.length===0&&(this.finalizeRepetition(e),e=this.createNewRepetition(0)),e.RepetitonUnderConstruction.startMarker!==void 0&&e.RepetitonUnderConstruction.StartIndex!==0&&(e=this.createNewRepetition(0)),e.RepetitonUnderConstruction.startMarker=new It(0,q.None,Dt.Begin,e.RepetitonUnderConstruction),e.RepetitonUnderConstruction.FromWords=!0,t.parentRepetition=e.RepetitonUnderConstruction,!e.ToCodaFound){const s=this.findInstructionInMainListBackwards(q.ToCoda,t.measureIndex);if(s>=0)e.RepetitonUnderConstruction.forwardJumpInstruction=new It(s,q.ToCoda,Dt.Begin,e.RepetitonUnderConstruction),this.musicSheet.SourceMeasures[s].LastRepetitionInstructions.splice(0,0,e.RepetitonUnderConstruction.forwardJumpInstruction),e.ToCodaFound=!0;else{const r=this.findInstructionInMainListBackwards(q.Coda,t.measureIndex);r>=0&&(e.RepetitonUnderConstruction.forwardJumpInstruction=new It(r,q.ToCoda,Dt.Begin,e.RepetitonUnderConstruction),this.musicSheet.SourceMeasures[r].LastRepetitionInstructions.splice(0,0,e.RepetitonUnderConstruction.forwardJumpInstruction),e.ToCodaFound=!0)}}e.ToCodaFound&&(e.WaitingForCoda=!0),e.RepetitonUnderConstruction.EndingIndexDict.hasOwnProperty(1)||e.RepetitonUnderConstruction.setEndingEndIndex(1,this.currentMeasureIndex),e.RepetitonUnderConstruction.BackwardJumpInstructions.push(t),this.currentMeasure.LastRepetitionInstructions.push(t);break;case q.None:break;default:throw new Li("currentRepetitionInstruction")}return!0}findInstructionInMainListBackwards(t,e){for(let i=this.repetitionInstructions.length-1;i>=0;i--){const s=this.repetitionInstructions[i];if(s.measureIndex<=e&&s.type===t)return s.measureIndex}return-1}finalizeRepetition(t){const e=t.RepetitonUnderConstruction;if(e.BackwardJumpInstructions.length>0){let i=!0;const s=this.getLastFinalizedRepetition();if(s!==void 0&&e.coversIdenticalMeasures(s)){if(e.NumberOfEndings>s.NumberOfEndings){const r=this.musicSheet.Repetitions.indexOf(s,0);r>-1&&this.musicSheet.Repetitions.splice(r,1),s.removeFromRepetitionInstructions(),this.musicSheet.Repetitions.push(e)}i=!1,e.removeFromRepetitionInstructions()}else this.musicSheet.Repetitions.push(e);i&&(e.startMarker.type===q.None&&this.musicSheet.SourceMeasures[e.StartIndex].FirstRepetitionInstructions.push(e.startMarker),e.UserNumberOfRepetitions=e.DefaultNumberOfRepetitions)}this.openRepetitions.splice(this.openRepetitions.length-1,1)}getCurrentRepetition(t){let e;for(let i=this.openRepetitions.length-1;i>=0;i--)if(this.openRepetitions[i].RepetitonUnderConstruction.FromWords===t){for(e=this.openRepetitions[i];i0)return this.openRepetitions.last();const t=this.createNewRepetition(0);return t.RepetitonUnderConstruction.startMarker=new It(0,q.None,Dt.Begin,t.RepetitonUnderConstruction),t}getOrCreateCurrentRepetition2(t){let e;if(this.openRepetitions.length&&this.openRepetitions.last().RepetitonUnderConstruction.EndingParts.length<2){for(let s=this.openRepetitions.length-1;s>=0;s--)if(e=this.openRepetitions[s],e.RepetitonUnderConstruction.FromWords===t){for(;s0){const i=this.openRepetitions.last(),s=i.RepetitonUnderConstruction;if(s.BackwardJumpInstructions.length>0){const r=Object.keys(s.EndingIndexDict);(r.length===0||s.EndingIndexDict[r[r.length-1]].part.EndIndex>=0)&&this.finalizeRepetition(i)}}const e=new tf(this.musicSheet);return this.lastRepetitionCommonPartStartIndex=t,this.openRepetitions.push(e),e}getLastFinalizedRepetition(){if(this.musicSheet.Repetitions.length>0)return this.musicSheet.Repetitions.last()}}class tf{constructor(t){this.RepetitonUnderConstruction=new Dn(t)}}class ua{static createRepetitionInstructionReader(){return new Qu}static createRepetitionCalculator(){return new $u}}class ef{constructor(){this.voiceMeasureReadPlugins=[]}addVoiceMeasureReadPlugin(t){this.voiceMeasureReadPlugins.push(t)}processVoiceMeasureReadPlugins(t,e,i){for(const s of this.voiceMeasureReadPlugins)try{s.measureReadCalculations(t,e,i)}catch(r){j.info("VoiceGenerator.addSingleNote: ",r)}}}class Eo{constructor(t=void 0,e=new Ui){this.completeNumberOfStaves=0,this.pluginManager=new ef,t?this.afterSheetReadingModules=t:this.afterSheetReadingModules=[],this.repetitionInstructionReader=ua.createRepetitionInstructionReader(),this.repetitionCalculator=ua.createRepetitionCalculator(),this.rules=e}get PluginManager(){return this.pluginManager}get CompleteNumberOfStaves(){return this.completeNumberOfStaves}static doCalculationsAfterDurationHasBeenSet(t){for(const e of t)e.doCalculationsAfterDurationHasBeenSet()}createMusicSheet(t,e){try{return this._createMusicSheet(t,e)}catch(i){j.error("MusicSheetReader.CreateMusicSheet",i);return}}_removeFromArray(t,e){const i=t.indexOf(e);i!==-1&&t.splice(i,1)}trimString(t){return t.replace(/^\s+|\s+$/g,"")}_lastElement(t){return t[t.length-1]}_createMusicSheet(t,e){var u;const i=[];let s=0;if(this.musicSheet=new al,this.musicSheet.Path=e,this.musicSheet.Rules=this.rules,!t)throw new Ee("Undefined root element");this.pushSheetLabels(t,e);const r=t.element("part-list");if(!r)throw new Ee("Undefined partListNode");const o=t.elements("part"),a=r.elements();this.initializeReading(a,o,i);let l=!0;this.currentFraction=new W(0,1);let h=!1,c=t.element("identification");for(c&&(c=c.element("encoding")),c&&(c=c.element("software")),c!==void 0&&c.value==="Guitar Pro 5"&&(h=!0);l;){this.currentMeasure!==void 0&&this.currentMeasure.HasEndLine&&this.rules.NewPartAndSystemAfterFinalBarline&&(s=0),this.currentMeasure=new Yc(this.completeNumberOfStaves,this.musicSheet.Rules);for(const f of i)try{l=l&&f.readNextXmlMeasure(this.currentMeasure,this.currentFraction,h)}catch(d){const p=Tt.translateText("ReaderErrorMessages/InstrumentError","Error while reading instruments.");throw new Ee(p,d)}l&&(this.musicSheet.addMeasure(this.currentMeasure),this.checkIfRhythmInstructionsAreSetAndEqual(i),this.checkSourceMeasureForNullEntries(),s=this.setSourceMeasureDuration(i,s),Eo.doCalculationsAfterDurationHasBeenSet(i),this.currentMeasure.AbsoluteTimestamp=this.currentFraction.clone(),this.musicSheet.SheetErrors.finalizeMeasure(this.currentMeasure.MeasureNumber),this.currentFraction.Add(this.currentMeasure.Duration),this.previousMeasure=this.currentMeasure,this.musicSheet.SoundTempos=(u=i[0])==null?void 0:u.SoundTempos)}this.repetitionInstructionReader&&(this.repetitionInstructionReader.removeRedundantInstructions(),this.repetitionCalculator&&this.repetitionCalculator.calculateRepetitions(this.musicSheet,this.repetitionInstructionReader.repetitionInstructions)),this.musicSheet.DefaultStartTempoInBpm===0&&(this.musicSheet.DefaultStartTempoInBpm=100),this.musicSheet.checkForInstrumentWithNoVoice(),this.musicSheet.fillStaffList();for(let f=0,d=this.afterSheetReadingModules.length;fi){if(this.areRhythmInstructionsMixed(e)&&a.SymbolEnum!==ii.NONE)continue;i=a.Rhythm.RealValue,s=e.indexOf(a)}}if(e.length>0&&e.lengtht.Denominator){const i=e.Denominator/t.Denominator;t.expand(i)}}checkIfMeasureIsImplicit(t,e){return!this.previousMeasure&&t.lt(e)?!0:this.previousMeasure?W.plus(this.previousMeasure.Duration,t).Equals(e):!1}allInstrumentsHaveSameDuration(t,e){let i=0;for(let s=0,r=t.length;s=0;t--)for(let e=this.currentMeasure.VerticalSourceStaffEntryContainers[t].StaffEntries.length-1;e>=0;e--){const i=this.currentMeasure.VerticalSourceStaffEntryContainers[t].StaffEntries[e];if(i)for(let s=i.VoiceEntries.length-1;s>=0;s--){const r=i.VoiceEntries[s];r.Notes.length===0&&(this._removeFromArray(r.ParentVoice.VoiceEntries,r),this._removeFromArray(i.VoiceEntries,r))}i!==void 0&&i.VoiceEntries.length===0&&(this.currentMeasure.VerticalSourceStaffEntryContainers[t].StaffEntries[e]=void 0)}for(let t=this.currentMeasure.VerticalSourceStaffEntryContainers.length-1;t>=0;t--){let e=0;for(let i=0,s=this.currentMeasure.VerticalSourceStaffEntryContainers[t].StaffEntries.length;ie){if(!this.musicSheet.Title){const y=p.attribute("font-size").value,x=parseFloat(y);i0&&c.MidiInstrumentId!==st.Percussion&&(g.midiInstrumentID=Math.max(0,parseInt(y.value,10)-1));else if(y.name==="midi-unpitched")g.fixedKey=Math.max(0,parseInt(y.value,10));else if(y.name==="volume")try{const x=parseFloat(y.value);g.volume=x/127}catch(x){j.debug("ExpressionReader.readExpressionParameters","read volume",x)}else if(y.name==="pan")try{const x=parseFloat(y.value);g.pan=x/64}catch(x){j.debug("ExpressionReader.readExpressionParameters","read pan",x)}}catch(x){j.info("MusicSheetReader.createInstrumentGroups midi settings: ",x)}}}}catch(g){j.info("MusicSheetReader.createInstrumentGroups: ",g)}}if(c.SubInstruments.length===0){const f=new Nr(c);c.SubInstruments.push(f)}i[h]=c,s?(s.InstrumentalGroups.push(c),this.musicSheet.Instruments.push(c)):(this.musicSheet.InstrumentalGroups.push(c),this.musicSheet.Instruments.push(c))}else if(l.name==="part-group"&&l.attribute("type").value==="start"){const h=new Za("group",this.musicSheet,s);s?s.InstrumentalGroups.push(h):this.musicSheet.InstrumentalGroups.push(h),s=h}else if(l.name==="part-group"&&l.attribute("type").value==="stop"&&s){if(s.InstrumentalGroups.length===1){const h=s.InstrumentalGroups[0];s.Parent?(s.Parent.InstrumentalGroups.push(h),this._removeFromArray(s.Parent.InstrumentalGroups,s)):(this.musicSheet.InstrumentalGroups.push(h),this._removeFromArray(this.musicSheet.InstrumentalGroups,s))}s=s.Parent}}}catch(r){const o=Tt.translateText("ReaderErrorMessages/InstrumentError","Error while reading Instruments");throw new Ee(o,r)}for(let r=0,o=this.musicSheet.Instruments.length;r0){const r=s[0];if(r){let o=r.element("attributes");o&&(o=o.element("staves")),o?e+=parseInt(o.value,10):e++}}}if(isNaN(e)||e<=0){const i=Tt.translateText("ReaderErrorMessages/StaffError","Invalid number of staves.");throw new Ee(i)}return e}getInstrumentNumberOfStavesFromXml(t){let e=0;const i=t.element("measure");if(i){const s=i.element("attributes");let r;s&&(r=s.element("staves")),!s||!r?e=1:e=parseInt(r.value,10)}if(isNaN(e)||e<=0){const s=Tt.translateText("ReaderErrorMessages/StaffError","Invalid number of Staves.");throw new Ee(s)}return e}}var ll={exports:{}};/*! JSZip v3.7.1 - A JavaScript class for generating and reading zip files (c) 2009-2016 Stuart Knightley Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown. JSZip uses the library pako released under the MIT license : https://github.com/nodeca/pako/blob/master/LICENSE */(function(n,t){(function(e){n.exports=e()})(function(){return function e(i,s,r){function o(h,c){if(!s[h]){if(!i[h]){var u=typeof Oi=="function"&&Oi;if(!c&&u)return u(h,!0);if(a)return a(h,!0);var f=new Error("Cannot find module '"+h+"'");throw f.code="MODULE_NOT_FOUND",f}var d=s[h]={exports:{}};i[h][0].call(d.exports,function(p){var g=i[h][1][p];return o(g||p)},d,d.exports,e,i,s,r)}return s[h].exports}for(var a=typeof Oi=="function"&&Oi,l=0;l>2,d=(3&h)<<4|c>>4,p=1>6:64,g=2>4,c=(15&f)<<4|(d=a.indexOf(l.charAt(g++)))>>2,u=(3&d)<<6|(p=a.indexOf(l.charAt(g++))),b[m++]=h,d!==64&&(b[m++]=c),p!==64&&(b[m++]=u);return b}},{"./support":30,"./utils":32}],2:[function(e,i,s){var r=e("./external"),o=e("./stream/DataWorker"),a=e("./stream/Crc32Probe"),l=e("./stream/DataLengthProbe");function h(c,u,f,d,p){this.compressedSize=c,this.uncompressedSize=u,this.crc32=f,this.compression=d,this.compressedContent=p}h.prototype={getContentWorker:function(){var c=new o(r.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new l("data_length")),u=this;return c.on("end",function(){if(this.streamInfo.data_length!==u.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),c},getCompressedWorker:function(){return new o(r.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},h.createWorkerFrom=function(c,u,f){return c.pipe(new a).pipe(new l("uncompressedSize")).pipe(u.compressWorker(f)).pipe(new l("compressedSize")).withStreamInfo("compression",u)},i.exports=h},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,i,s){var r=e("./stream/GenericWorker");s.STORE={magic:"\0\0",compressWorker:function(o){return new r("STORE compression")},uncompressWorker:function(){return new r("STORE decompression")}},s.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,i,s){var r=e("./utils"),o=function(){for(var a,l=[],h=0;h<256;h++){a=h;for(var c=0;c<8;c++)a=1&a?3988292384^a>>>1:a>>>1;l[h]=a}return l}();i.exports=function(a,l){return a!==void 0&&a.length?r.getTypeOf(a)!=="string"?function(h,c,u,f){var d=o,p=f+u;h^=-1;for(var g=f;g>>8^d[255&(h^c[g])];return-1^h}(0|l,a,a.length,0):function(h,c,u,f){var d=o,p=f+u;h^=-1;for(var g=f;g>>8^d[255&(h^c.charCodeAt(g))];return-1^h}(0|l,a,a.length,0):0}},{"./utils":32}],5:[function(e,i,s){s.base64=!1,s.binary=!1,s.dir=!1,s.createFolders=!0,s.date=null,s.compression=null,s.compressionOptions=null,s.comment=null,s.unixPermissions=null,s.dosPermissions=null},{}],6:[function(e,i,s){var r=null;r=typeof Promise!="undefined"?Promise:e("lie"),i.exports={Promise:r}},{lie:37}],7:[function(e,i,s){var r=typeof Uint8Array!="undefined"&&typeof Uint16Array!="undefined"&&typeof Uint32Array!="undefined",o=e("pako"),a=e("./utils"),l=e("./stream/GenericWorker"),h=r?"uint8array":"array";function c(u,f){l.call(this,"FlateWorker/"+u),this._pako=null,this._pakoAction=u,this._pakoOptions=f,this.meta={}}s.magic="\b\0",a.inherits(c,l),c.prototype.processChunk=function(u){this.meta=u.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(h,u.data),!1)},c.prototype.flush=function(){l.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},c.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this._pako=null},c.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var u=this;this._pako.onData=function(f){u.push({data:f,meta:u.meta})}},s.compressWorker=function(u){return new c("Deflate",u)},s.uncompressWorker=function(){return new c("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,i,s){function r(d,p){var g,m="";for(g=0;g>>=8;return m}function o(d,p,g,m,S,b){var y,x,w=d.file,T=d.compression,E=b!==h.utf8encode,C=a.transformTo("string",b(w.name)),P=a.transformTo("string",h.utf8encode(w.name)),I=w.comment,F=a.transformTo("string",b(I)),L=a.transformTo("string",h.utf8encode(I)),k=P.length!==w.name.length,v=L.length!==I.length,G="",et="",H="",nt=w.dir,K=w.date,lt={crc32:0,compressedSize:0,uncompressedSize:0};p&&!g||(lt.crc32=d.crc32,lt.compressedSize=d.compressedSize,lt.uncompressedSize=d.uncompressedSize);var A=0;p&&(A|=8),E||!k&&!v||(A|=2048);var B=0,ot=0;nt&&(B|=16),S==="UNIX"?(ot=798,B|=function(J,ct){var Nt=J;return J||(Nt=ct?16893:33204),(65535&Nt)<<16}(w.unixPermissions,nt)):(ot=20,B|=function(J){return 63&(J||0)}(w.dosPermissions)),y=K.getUTCHours(),y<<=6,y|=K.getUTCMinutes(),y<<=5,y|=K.getUTCSeconds()/2,x=K.getUTCFullYear()-1980,x<<=4,x|=K.getUTCMonth()+1,x<<=5,x|=K.getUTCDate(),k&&(et=r(1,1)+r(c(C),4)+P,G+="up"+r(et.length,2)+et),v&&(H=r(1,1)+r(c(F),4)+L,G+="uc"+r(H.length,2)+H);var rt="";return rt+=` \0`,rt+=r(A,2),rt+=T.magic,rt+=r(y,2),rt+=r(x,2),rt+=r(lt.crc32,4),rt+=r(lt.compressedSize,4),rt+=r(lt.uncompressedSize,4),rt+=r(C.length,2),rt+=r(G.length,2),{fileRecord:u.LOCAL_FILE_HEADER+rt+C+G,dirRecord:u.CENTRAL_FILE_HEADER+r(ot,2)+rt+r(F.length,2)+"\0\0\0\0"+r(B,4)+r(m,4)+C+G+F}}var a=e("../utils"),l=e("../stream/GenericWorker"),h=e("../utf8"),c=e("../crc32"),u=e("../signature");function f(d,p,g,m){l.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=p,this.zipPlatform=g,this.encodeFileName=m,this.streamFiles=d,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(f,l),f.prototype.push=function(d){var p=d.meta.percent||0,g=this.entriesCount,m=this._sources.length;this.accumulate?this.contentBuffer.push(d):(this.bytesWritten+=d.data.length,l.prototype.push.call(this,{data:d.data,meta:{currentFile:this.currentFile,percent:g?(p+100*(g-m-1))/g:100}}))},f.prototype.openedSource=function(d){this.currentSourceOffset=this.bytesWritten,this.currentFile=d.file.name;var p=this.streamFiles&&!d.file.dir;if(p){var g=o(d,p,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:g.fileRecord,meta:{percent:0}})}else this.accumulate=!0},f.prototype.closedSource=function(d){this.accumulate=!1;var p=this.streamFiles&&!d.file.dir,g=o(d,p,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(g.dirRecord),p)this.push({data:function(m){return u.DATA_DESCRIPTOR+r(m.crc32,4)+r(m.compressedSize,4)+r(m.uncompressedSize,4)}(d),meta:{percent:100}});else for(this.push({data:g.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},f.prototype.flush=function(){for(var d=this.bytesWritten,p=0;p=this.index;l--)h=(h<<8)+this.byteAt(l);return this.index+=a,h},readString:function(a){return r.transformTo("string",this.readData(a))},readData:function(a){},lastIndexOfSignature:function(a){},readAndCheckSignature:function(a){},readDate:function(){var a=this.readInt(4);return new Date(Date.UTC(1980+(a>>25&127),(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1))}},i.exports=o},{"../utils":32}],19:[function(e,i,s){var r=e("./Uint8ArrayReader");function o(a){r.call(this,a)}e("../utils").inherits(o,r),o.prototype.readData=function(a){this.checkOffset(a);var l=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},i.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,i,s){var r=e("./DataReader");function o(a){r.call(this,a)}e("../utils").inherits(o,r),o.prototype.byteAt=function(a){return this.data.charCodeAt(this.zero+a)},o.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)-this.zero},o.prototype.readAndCheckSignature=function(a){return a===this.readData(4)},o.prototype.readData=function(a){this.checkOffset(a);var l=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},i.exports=o},{"../utils":32,"./DataReader":18}],21:[function(e,i,s){var r=e("./ArrayReader");function o(a){r.call(this,a)}e("../utils").inherits(o,r),o.prototype.readData=function(a){if(this.checkOffset(a),a===0)return new Uint8Array(0);var l=this.data.subarray(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},i.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(e,i,s){var r=e("../utils"),o=e("../support"),a=e("./ArrayReader"),l=e("./StringReader"),h=e("./NodeBufferReader"),c=e("./Uint8ArrayReader");i.exports=function(u){var f=r.getTypeOf(u);return r.checkSupport(f),f!=="string"||o.uint8array?f==="nodebuffer"?new h(u):o.uint8array?new c(r.transformTo("uint8array",u)):new a(r.transformTo("array",u)):new l(u)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,i,s){s.LOCAL_FILE_HEADER="PK",s.CENTRAL_FILE_HEADER="PK",s.CENTRAL_DIRECTORY_END="PK",s.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",s.ZIP64_CENTRAL_DIRECTORY_END="PK",s.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(e,i,s){var r=e("./GenericWorker"),o=e("../utils");function a(l){r.call(this,"ConvertWorker to "+l),this.destType=l}o.inherits(a,r),a.prototype.processChunk=function(l){this.push({data:o.transformTo(this.destType,l.data),meta:l.meta})},i.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(e,i,s){var r=e("./GenericWorker"),o=e("../crc32");function a(){r.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}e("../utils").inherits(a,r),a.prototype.processChunk=function(l){this.streamInfo.crc32=o(l.data,this.streamInfo.crc32||0),this.push(l)},i.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,i,s){var r=e("../utils"),o=e("./GenericWorker");function a(l){o.call(this,"DataLengthProbe for "+l),this.propName=l,this.withStreamInfo(l,0)}r.inherits(a,o),a.prototype.processChunk=function(l){if(l){var h=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=h+l.data.length}o.prototype.processChunk.call(this,l)},i.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(e,i,s){var r=e("../utils"),o=e("./GenericWorker");function a(l){o.call(this,"DataWorker");var h=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,l.then(function(c){h.dataIsReady=!0,h.data=c,h.max=c&&c.length||0,h.type=r.getTypeOf(c),h.isPaused||h._tickAndRepeat()},function(c){h.error(c)})}r.inherits(a,o),a.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,r.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(r.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var l=null,h=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":l=this.data.substring(this.index,h);break;case"uint8array":l=this.data.subarray(this.index,h);break;case"array":case"nodebuffer":l=this.data.slice(this.index,h)}return this.index=h,this.push({data:l,meta:{percent:this.max?this.index/this.max*100:0}})},i.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(e,i,s){function r(o){this.name=o||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}r.prototype={push:function(o){this.emit("data",o)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(o){this.emit("error",o)}return!0},error:function(o){return!this.isFinished&&(this.isPaused?this.generatedError=o:(this.isFinished=!0,this.emit("error",o),this.previous&&this.previous.error(o),this.cleanUp()),!0)},on:function(o,a){return this._listeners[o].push(a),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(o,a){if(this._listeners[o])for(var l=0;l "+o:o}},i.exports=r},{}],29:[function(e,i,s){var r=e("../utils"),o=e("./ConvertWorker"),a=e("./GenericWorker"),l=e("../base64"),h=e("../support"),c=e("../external"),u=null;if(h.nodestream)try{u=e("../nodejs/NodejsStreamOutputAdapter")}catch{}function f(p,g){return new c.Promise(function(m,S){var b=[],y=p._internalType,x=p._outputType,w=p._mimeType;p.on("data",function(T,E){b.push(T),g&&g(E)}).on("error",function(T){b=[],S(T)}).on("end",function(){try{var T=function(E,C,P){switch(E){case"blob":return r.newBlob(r.transformTo("arraybuffer",C),P);case"base64":return l.encode(C);default:return r.transformTo(E,C)}}(x,function(E,C){var P,I=0,F=null,L=0;for(P=0;P>>6:(m<65536?g[y++]=224|m>>>12:(g[y++]=240|m>>>18,g[y++]=128|m>>>12&63),g[y++]=128|m>>>6&63),g[y++]=128|63&m);return g}(d)},s.utf8decode=function(d){return o.nodebuffer?r.transformTo("nodebuffer",d).toString("utf-8"):function(p){var g,m,S,b,y=p.length,x=new Array(2*y);for(g=m=0;g>10&1023,x[m++]=56320|1023&S)}return x.length!==m&&(x.subarray?x=x.subarray(0,m):x.length=m),r.applyFromCharCode(x)}(d=r.transformTo(o.uint8array?"uint8array":"array",d))},r.inherits(u,l),u.prototype.processChunk=function(d){var p=r.transformTo(o.uint8array?"uint8array":"array",d.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var g=p;(p=new Uint8Array(g.length+this.leftOver.length)).set(this.leftOver,0),p.set(g,this.leftOver.length)}else p=this.leftOver.concat(p);this.leftOver=null}var m=function(b,y){var x;for((y=y||b.length)>b.length&&(y=b.length),x=y-1;0<=x&&(192&b[x])==128;)x--;return x<0||x===0?y:x+h[b[x]]>y?x:y}(p),S=p;m!==p.length&&(o.uint8array?(S=p.subarray(0,m),this.leftOver=p.subarray(m,p.length)):(S=p.slice(0,m),this.leftOver=p.slice(m,p.length))),this.push({data:s.utf8decode(S),meta:d.meta})},u.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:s.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},s.Utf8DecodeWorker=u,r.inherits(f,l),f.prototype.processChunk=function(d){this.push({data:s.utf8encode(d.data),meta:d.meta})},s.Utf8EncodeWorker=f},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,i,s){var r=e("./support"),o=e("./base64"),a=e("./nodejsUtils"),l=e("set-immediate-shim"),h=e("./external");function c(m){return m}function u(m,S){for(var b=0;b>8;this.dir=!!(16&this.externalFileAttributes),d==0&&(this.dosPermissions=63&this.externalFileAttributes),d==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(d){if(this.extraFields[1]){var p=r(this.extraFields[1].value);this.uncompressedSize===o.MAX_VALUE_32BITS&&(this.uncompressedSize=p.readInt(8)),this.compressedSize===o.MAX_VALUE_32BITS&&(this.compressedSize=p.readInt(8)),this.localHeaderOffset===o.MAX_VALUE_32BITS&&(this.localHeaderOffset=p.readInt(8)),this.diskNumberStart===o.MAX_VALUE_32BITS&&(this.diskNumberStart=p.readInt(4))}},readExtraFields:function(d){var p,g,m,S=d.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});d.index+4>>6:(d<65536?f[m++]=224|d>>>12:(f[m++]=240|d>>>18,f[m++]=128|d>>>12&63),f[m++]=128|d>>>6&63),f[m++]=128|63&d);return f},s.buf2binstring=function(u){return c(u,u.length)},s.binstring2buf=function(u){for(var f=new r.Buf8(u.length),d=0,p=f.length;d>10&1023,b[p++]=56320|1023&g)}return c(b,p)},s.utf8border=function(u,f){var d;for((f=f||u.length)>u.length&&(f=u.length),d=f-1;0<=d&&(192&u[d])==128;)d--;return d<0||d===0?f:d+l[u[d]]>f?d:f}},{"./common":41}],43:[function(e,i,s){i.exports=function(r,o,a,l){for(var h=65535&r|0,c=r>>>16&65535|0,u=0;a!==0;){for(a-=u=2e3>>1:o>>>1;a[l]=o}return a}();i.exports=function(o,a,l,h){var c=r,u=h+l;o^=-1;for(var f=h;f>>8^c[255&(o^a[f])];return-1^o}},{}],46:[function(e,i,s){var r,o=e("../utils/common"),a=e("./trees"),l=e("./adler32"),h=e("./crc32"),c=e("./messages"),u=0,f=4,d=0,p=-2,g=-1,m=4,S=2,b=8,y=9,x=286,w=30,T=19,E=2*x+1,C=15,P=3,I=258,F=I+P+1,L=42,k=113,v=1,G=2,et=3,H=4;function nt(_,Z){return _.msg=c[Z],Z}function K(_){return(_<<1)-(4<_?9:0)}function lt(_){for(var Z=_.length;0<=--Z;)_[Z]=0}function A(_){var Z=_.state,Y=Z.pending;Y>_.avail_out&&(Y=_.avail_out),Y!==0&&(o.arraySet(_.output,Z.pending_buf,Z.pending_out,Y,_.next_out),_.next_out+=Y,Z.pending_out+=Y,_.total_out+=Y,_.avail_out-=Y,Z.pending-=Y,Z.pending===0&&(Z.pending_out=0))}function B(_,Z){a._tr_flush_block(_,0<=_.block_start?_.block_start:-1,_.strstart-_.block_start,Z),_.block_start=_.strstart,A(_.strm)}function ot(_,Z){_.pending_buf[_.pending++]=Z}function rt(_,Z){_.pending_buf[_.pending++]=Z>>>8&255,_.pending_buf[_.pending++]=255&Z}function J(_,Z){var Y,N,R=_.max_chain_length,D=_.strstart,Q=_.prev_length,$=_.nice_match,U=_.strstart>_.w_size-F?_.strstart-(_.w_size-F):0,it=_.window,mt=_.w_mask,at=_.prev,Mt=_.strstart+I,ee=it[D+Q-1],Ut=it[D+Q];_.prev_length>=_.good_match&&(R>>=2),$>_.lookahead&&($=_.lookahead);do if(it[(Y=Z)+Q]===Ut&&it[Y+Q-1]===ee&&it[Y]===it[D]&&it[++Y]===it[D+1]){D+=2,Y++;do;while(it[++D]===it[++Y]&&it[++D]===it[++Y]&&it[++D]===it[++Y]&&it[++D]===it[++Y]&&it[++D]===it[++Y]&&it[++D]===it[++Y]&&it[++D]===it[++Y]&&it[++D]===it[++Y]&&DU&&--R!=0);return Q<=_.lookahead?Q:_.lookahead}function ct(_){var Z,Y,N,R,D,Q,$,U,it,mt,at=_.w_size;do{if(R=_.window_size-_.lookahead-_.strstart,_.strstart>=at+(at-F)){for(o.arraySet(_.window,_.window,at,at,0),_.match_start-=at,_.strstart-=at,_.block_start-=at,Z=Y=_.hash_size;N=_.head[--Z],_.head[Z]=at<=N?N-at:0,--Y;);for(Z=Y=at;N=_.prev[--Z],_.prev[Z]=at<=N?N-at:0,--Y;);R+=at}if(_.strm.avail_in===0)break;if(Q=_.strm,$=_.window,U=_.strstart+_.lookahead,it=R,mt=void 0,mt=Q.avail_in,it=P)for(D=_.strstart-_.insert,_.ins_h=_.window[D],_.ins_h=(_.ins_h<<_.hash_shift^_.window[D+1])&_.hash_mask;_.insert&&(_.ins_h=(_.ins_h<<_.hash_shift^_.window[D+P-1])&_.hash_mask,_.prev[D&_.w_mask]=_.head[_.ins_h],_.head[_.ins_h]=D,D++,_.insert--,!(_.lookahead+_.insert=P&&(_.ins_h=(_.ins_h<<_.hash_shift^_.window[_.strstart+P-1])&_.hash_mask,Y=_.prev[_.strstart&_.w_mask]=_.head[_.ins_h],_.head[_.ins_h]=_.strstart),Y!==0&&_.strstart-Y<=_.w_size-F&&(_.match_length=J(_,Y)),_.match_length>=P)if(N=a._tr_tally(_,_.strstart-_.match_start,_.match_length-P),_.lookahead-=_.match_length,_.match_length<=_.max_lazy_match&&_.lookahead>=P){for(_.match_length--;_.strstart++,_.ins_h=(_.ins_h<<_.hash_shift^_.window[_.strstart+P-1])&_.hash_mask,Y=_.prev[_.strstart&_.w_mask]=_.head[_.ins_h],_.head[_.ins_h]=_.strstart,--_.match_length!=0;);_.strstart++}else _.strstart+=_.match_length,_.match_length=0,_.ins_h=_.window[_.strstart],_.ins_h=(_.ins_h<<_.hash_shift^_.window[_.strstart+1])&_.hash_mask;else N=a._tr_tally(_,0,_.window[_.strstart]),_.lookahead--,_.strstart++;if(N&&(B(_,!1),_.strm.avail_out===0))return v}return _.insert=_.strstart=P&&(_.ins_h=(_.ins_h<<_.hash_shift^_.window[_.strstart+P-1])&_.hash_mask,Y=_.prev[_.strstart&_.w_mask]=_.head[_.ins_h],_.head[_.ins_h]=_.strstart),_.prev_length=_.match_length,_.prev_match=_.match_start,_.match_length=P-1,Y!==0&&_.prev_length<_.max_lazy_match&&_.strstart-Y<=_.w_size-F&&(_.match_length=J(_,Y),_.match_length<=5&&(_.strategy===1||_.match_length===P&&4096<_.strstart-_.match_start)&&(_.match_length=P-1)),_.prev_length>=P&&_.match_length<=_.prev_length){for(R=_.strstart+_.lookahead-P,N=a._tr_tally(_,_.strstart-1-_.prev_match,_.prev_length-P),_.lookahead-=_.prev_length-1,_.prev_length-=2;++_.strstart<=R&&(_.ins_h=(_.ins_h<<_.hash_shift^_.window[_.strstart+P-1])&_.hash_mask,Y=_.prev[_.strstart&_.w_mask]=_.head[_.ins_h],_.head[_.ins_h]=_.strstart),--_.prev_length!=0;);if(_.match_available=0,_.match_length=P-1,_.strstart++,N&&(B(_,!1),_.strm.avail_out===0))return v}else if(_.match_available){if((N=a._tr_tally(_,0,_.window[_.strstart-1]))&&B(_,!1),_.strstart++,_.lookahead--,_.strm.avail_out===0)return v}else _.match_available=1,_.strstart++,_.lookahead--}return _.match_available&&(N=a._tr_tally(_,0,_.window[_.strstart-1]),_.match_available=0),_.insert=_.strstart_.pending_buf_size-5&&(Y=_.pending_buf_size-5);;){if(_.lookahead<=1){if(ct(_),_.lookahead===0&&Z===u)return v;if(_.lookahead===0)break}_.strstart+=_.lookahead,_.lookahead=0;var N=_.block_start+Y;if((_.strstart===0||_.strstart>=N)&&(_.lookahead=_.strstart-N,_.strstart=N,B(_,!1),_.strm.avail_out===0)||_.strstart-_.block_start>=_.w_size-F&&(B(_,!1),_.strm.avail_out===0))return v}return _.insert=0,Z===f?(B(_,!0),_.strm.avail_out===0?et:H):(_.strstart>_.block_start&&(B(_,!1),_.strm.avail_out),v)}),new dt(4,4,8,4,Nt),new dt(4,5,16,8,Nt),new dt(4,6,32,32,Nt),new dt(4,4,16,16,pt),new dt(8,16,32,32,pt),new dt(8,16,128,128,pt),new dt(8,32,128,256,pt),new dt(32,128,258,1024,pt),new dt(32,258,258,4096,pt)],s.deflateInit=function(_,Z){return ce(_,Z,b,15,8,0)},s.deflateInit2=ce,s.deflateReset=me,s.deflateResetKeep=Ht,s.deflateSetHeader=function(_,Z){return _&&_.state?_.state.wrap!==2?p:(_.state.gzhead=Z,d):p},s.deflate=function(_,Z){var Y,N,R,D;if(!_||!_.state||5>8&255),ot(N,N.gzhead.time>>16&255),ot(N,N.gzhead.time>>24&255),ot(N,N.level===9?2:2<=N.strategy||N.level<2?4:0),ot(N,255&N.gzhead.os),N.gzhead.extra&&N.gzhead.extra.length&&(ot(N,255&N.gzhead.extra.length),ot(N,N.gzhead.extra.length>>8&255)),N.gzhead.hcrc&&(_.adler=h(_.adler,N.pending_buf,N.pending,0)),N.gzindex=0,N.status=69):(ot(N,0),ot(N,0),ot(N,0),ot(N,0),ot(N,0),ot(N,N.level===9?2:2<=N.strategy||N.level<2?4:0),ot(N,3),N.status=k);else{var Q=b+(N.w_bits-8<<4)<<8;Q|=(2<=N.strategy||N.level<2?0:N.level<6?1:N.level===6?2:3)<<6,N.strstart!==0&&(Q|=32),Q+=31-Q%31,N.status=k,rt(N,Q),N.strstart!==0&&(rt(N,_.adler>>>16),rt(N,65535&_.adler)),_.adler=1}if(N.status===69)if(N.gzhead.extra){for(R=N.pending;N.gzindex<(65535&N.gzhead.extra.length)&&(N.pending!==N.pending_buf_size||(N.gzhead.hcrc&&N.pending>R&&(_.adler=h(_.adler,N.pending_buf,N.pending-R,R)),A(_),R=N.pending,N.pending!==N.pending_buf_size));)ot(N,255&N.gzhead.extra[N.gzindex]),N.gzindex++;N.gzhead.hcrc&&N.pending>R&&(_.adler=h(_.adler,N.pending_buf,N.pending-R,R)),N.gzindex===N.gzhead.extra.length&&(N.gzindex=0,N.status=73)}else N.status=73;if(N.status===73)if(N.gzhead.name){R=N.pending;do{if(N.pending===N.pending_buf_size&&(N.gzhead.hcrc&&N.pending>R&&(_.adler=h(_.adler,N.pending_buf,N.pending-R,R)),A(_),R=N.pending,N.pending===N.pending_buf_size)){D=1;break}D=N.gzindexR&&(_.adler=h(_.adler,N.pending_buf,N.pending-R,R)),D===0&&(N.gzindex=0,N.status=91)}else N.status=91;if(N.status===91)if(N.gzhead.comment){R=N.pending;do{if(N.pending===N.pending_buf_size&&(N.gzhead.hcrc&&N.pending>R&&(_.adler=h(_.adler,N.pending_buf,N.pending-R,R)),A(_),R=N.pending,N.pending===N.pending_buf_size)){D=1;break}D=N.gzindexR&&(_.adler=h(_.adler,N.pending_buf,N.pending-R,R)),D===0&&(N.status=103)}else N.status=103;if(N.status===103&&(N.gzhead.hcrc?(N.pending+2>N.pending_buf_size&&A(_),N.pending+2<=N.pending_buf_size&&(ot(N,255&_.adler),ot(N,_.adler>>8&255),_.adler=0,N.status=k)):N.status=k),N.pending!==0){if(A(_),_.avail_out===0)return N.last_flush=-1,d}else if(_.avail_in===0&&K(Z)<=K(Y)&&Z!==f)return nt(_,-5);if(N.status===666&&_.avail_in!==0)return nt(_,-5);if(_.avail_in!==0||N.lookahead!==0||Z!==u&&N.status!==666){var $=N.strategy===2?function(U,it){for(var mt;;){if(U.lookahead===0&&(ct(U),U.lookahead===0)){if(it===u)return v;break}if(U.match_length=0,mt=a._tr_tally(U,0,U.window[U.strstart]),U.lookahead--,U.strstart++,mt&&(B(U,!1),U.strm.avail_out===0))return v}return U.insert=0,it===f?(B(U,!0),U.strm.avail_out===0?et:H):U.last_lit&&(B(U,!1),U.strm.avail_out===0)?v:G}(N,Z):N.strategy===3?function(U,it){for(var mt,at,Mt,ee,Ut=U.window;;){if(U.lookahead<=I){if(ct(U),U.lookahead<=I&&it===u)return v;if(U.lookahead===0)break}if(U.match_length=0,U.lookahead>=P&&0U.lookahead&&(U.match_length=U.lookahead)}if(U.match_length>=P?(mt=a._tr_tally(U,1,U.match_length-P),U.lookahead-=U.match_length,U.strstart+=U.match_length,U.match_length=0):(mt=a._tr_tally(U,0,U.window[U.strstart]),U.lookahead--,U.strstart++),mt&&(B(U,!1),U.strm.avail_out===0))return v}return U.insert=0,it===f?(B(U,!0),U.strm.avail_out===0?et:H):U.last_lit&&(B(U,!1),U.strm.avail_out===0)?v:G}(N,Z):r[N.level].func(N,Z);if($!==et&&$!==H||(N.status=666),$===v||$===et)return _.avail_out===0&&(N.last_flush=-1),d;if($===G&&(Z===1?a._tr_align(N):Z!==5&&(a._tr_stored_block(N,0,0,!1),Z===3&&(lt(N.head),N.lookahead===0&&(N.strstart=0,N.block_start=0,N.insert=0))),A(_),_.avail_out===0))return N.last_flush=-1,d}return Z!==f?d:N.wrap<=0?1:(N.wrap===2?(ot(N,255&_.adler),ot(N,_.adler>>8&255),ot(N,_.adler>>16&255),ot(N,_.adler>>24&255),ot(N,255&_.total_in),ot(N,_.total_in>>8&255),ot(N,_.total_in>>16&255),ot(N,_.total_in>>24&255)):(rt(N,_.adler>>>16),rt(N,65535&_.adler)),A(_),0=Y.w_size&&(D===0&&(lt(Y.head),Y.strstart=0,Y.block_start=0,Y.insert=0),it=new o.Buf8(Y.w_size),o.arraySet(it,Z,mt-Y.w_size,Y.w_size,0),Z=it,mt=Y.w_size),Q=_.avail_in,$=_.next_in,U=_.input,_.avail_in=mt,_.next_in=0,_.input=Z,ct(Y);Y.lookahead>=P;){for(N=Y.strstart,R=Y.lookahead-(P-1);Y.ins_h=(Y.ins_h<>>=P=C>>>24,y-=P,(P=C>>>16&255)===0)G[c++]=65535&C;else{if(!(16&P)){if((64&P)==0){C=x[(65535&C)+(b&(1<>>=P,y-=P),y<15&&(b+=v[l++]<>>=P=C>>>24,y-=P,!(16&(P=C>>>16&255))){if((64&P)==0){C=w[(65535&C)+(b&(1<>>=P,y-=P,(P=c-u)>3,b&=(1<<(y-=I<<3))-1,r.next_in=l,r.next_out=c,r.avail_in=l>>24&255)+(L>>>8&65280)+((65280&L)<<8)+((255&L)<<24)}function b(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function y(L){var k;return L&&L.state?(k=L.state,L.total_in=L.total_out=k.total=0,L.msg="",k.wrap&&(L.adler=1&k.wrap),k.mode=p,k.last=0,k.havedict=0,k.dmax=32768,k.head=null,k.hold=0,k.bits=0,k.lencode=k.lendyn=new r.Buf32(g),k.distcode=k.distdyn=new r.Buf32(m),k.sane=1,k.back=-1,f):d}function x(L){var k;return L&&L.state?((k=L.state).wsize=0,k.whave=0,k.wnext=0,y(L)):d}function w(L,k){var v,G;return L&&L.state?(G=L.state,k<0?(v=0,k=-k):(v=1+(k>>4),k<48&&(k&=15)),k&&(k<8||15=H.wsize?(r.arraySet(H.window,k,v-H.wsize,H.wsize,0),H.wnext=0,H.whave=H.wsize):(G<(et=H.wsize-H.wnext)&&(et=G),r.arraySet(H.window,k,v-G,et,H.wnext),(G-=et)?(r.arraySet(H.window,k,v-G,G,0),H.wnext=G,H.whave=H.wsize):(H.wnext+=et,H.wnext===H.wsize&&(H.wnext=0),H.whave>>8&255,v.check=a(v.check,D,2,0),B=A=0,v.mode=2;break}if(v.flags=0,v.head&&(v.head.done=!1),!(1&v.wrap)||(((255&A)<<8)+(A>>8))%31){L.msg="incorrect header check",v.mode=30;break}if((15&A)!=8){L.msg="unknown compression method",v.mode=30;break}if(B-=4,_=8+(15&(A>>>=4)),v.wbits===0)v.wbits=_;else if(_>v.wbits){L.msg="invalid window size",v.mode=30;break}v.dmax=1<<_,L.adler=v.check=1,v.mode=512&A?10:12,B=A=0;break;case 2:for(;B<16;){if(K===0)break t;K--,A+=G[H++]<>8&1),512&v.flags&&(D[0]=255&A,D[1]=A>>>8&255,v.check=a(v.check,D,2,0)),B=A=0,v.mode=3;case 3:for(;B<32;){if(K===0)break t;K--,A+=G[H++]<>>8&255,D[2]=A>>>16&255,D[3]=A>>>24&255,v.check=a(v.check,D,4,0)),B=A=0,v.mode=4;case 4:for(;B<16;){if(K===0)break t;K--,A+=G[H++]<>8),512&v.flags&&(D[0]=255&A,D[1]=A>>>8&255,v.check=a(v.check,D,2,0)),B=A=0,v.mode=5;case 5:if(1024&v.flags){for(;B<16;){if(K===0)break t;K--,A+=G[H++]<>>8&255,v.check=a(v.check,D,2,0)),B=A=0}else v.head&&(v.head.extra=null);v.mode=6;case 6:if(1024&v.flags&&(K<(J=v.length)&&(J=K),J&&(v.head&&(_=v.head.extra_len-v.length,v.head.extra||(v.head.extra=new Array(v.head.extra_len)),r.arraySet(v.head.extra,G,H,J,_)),512&v.flags&&(v.check=a(v.check,G,J,H)),K-=J,H+=J,v.length-=J),v.length))break t;v.length=0,v.mode=7;case 7:if(2048&v.flags){if(K===0)break t;for(J=0;_=G[H+J++],v.head&&_&&v.length<65536&&(v.head.name+=String.fromCharCode(_)),_&&J>9&1,v.head.done=!0),L.adler=v.check=0,v.mode=12;break;case 10:for(;B<32;){if(K===0)break t;K--,A+=G[H++]<>>=7&B,B-=7&B,v.mode=27;break}for(;B<3;){if(K===0)break t;K--,A+=G[H++]<>>=1)){case 0:v.mode=14;break;case 1:if(I(v),v.mode=20,k!==6)break;A>>>=2,B-=2;break t;case 2:v.mode=17;break;case 3:L.msg="invalid block type",v.mode=30}A>>>=2,B-=2;break;case 14:for(A>>>=7&B,B-=7&B;B<32;){if(K===0)break t;K--,A+=G[H++]<>>16^65535)){L.msg="invalid stored block lengths",v.mode=30;break}if(v.length=65535&A,B=A=0,v.mode=15,k===6)break t;case 15:v.mode=16;case 16:if(J=v.length){if(K>>=5,B-=5,v.ndist=1+(31&A),A>>>=5,B-=5,v.ncode=4+(15&A),A>>>=4,B-=4,286>>=3,B-=3}for(;v.have<19;)v.lens[Q[v.have++]]=0;if(v.lencode=v.lendyn,v.lenbits=7,Y={bits:v.lenbits},Z=h(0,v.lens,0,19,v.lencode,0,v.work,Y),v.lenbits=Y.bits,Z){L.msg="invalid code lengths set",v.mode=30;break}v.have=0,v.mode=19;case 19:for(;v.have>>16&255,Ct=65535&R,!((pt=R>>>24)<=B);){if(K===0)break t;K--,A+=G[H++]<>>=pt,B-=pt,v.lens[v.have++]=Ct;else{if(Ct===16){for(N=pt+2;B>>=pt,B-=pt,v.have===0){L.msg="invalid bit length repeat",v.mode=30;break}_=v.lens[v.have-1],J=3+(3&A),A>>>=2,B-=2}else if(Ct===17){for(N=pt+3;B>>=pt)),A>>>=3,B-=3}else{for(N=pt+7;B>>=pt)),A>>>=7,B-=7}if(v.have+J>v.nlen+v.ndist){L.msg="invalid bit length repeat",v.mode=30;break}for(;J--;)v.lens[v.have++]=_}}if(v.mode===30)break;if(v.lens[256]===0){L.msg="invalid code -- missing end-of-block",v.mode=30;break}if(v.lenbits=9,Y={bits:v.lenbits},Z=h(c,v.lens,0,v.nlen,v.lencode,0,v.work,Y),v.lenbits=Y.bits,Z){L.msg="invalid literal/lengths set",v.mode=30;break}if(v.distbits=6,v.distcode=v.distdyn,Y={bits:v.distbits},Z=h(u,v.lens,v.nlen,v.ndist,v.distcode,0,v.work,Y),v.distbits=Y.bits,Z){L.msg="invalid distances set",v.mode=30;break}if(v.mode=20,k===6)break t;case 20:v.mode=21;case 21:if(6<=K&&258<=lt){L.next_out=nt,L.avail_out=lt,L.next_in=H,L.avail_in=K,v.hold=A,v.bits=B,l(L,rt),nt=L.next_out,et=L.output,lt=L.avail_out,H=L.next_in,G=L.input,K=L.avail_in,A=v.hold,B=v.bits,v.mode===12&&(v.back=-1);break}for(v.back=0;dt=(R=v.lencode[A&(1<>>16&255,Ct=65535&R,!((pt=R>>>24)<=B);){if(K===0)break t;K--,A+=G[H++]<>Ht)])>>>16&255,Ct=65535&R,!(Ht+(pt=R>>>24)<=B);){if(K===0)break t;K--,A+=G[H++]<>>=Ht,B-=Ht,v.back+=Ht}if(A>>>=pt,B-=pt,v.back+=pt,v.length=Ct,dt===0){v.mode=26;break}if(32&dt){v.back=-1,v.mode=12;break}if(64&dt){L.msg="invalid literal/length code",v.mode=30;break}v.extra=15&dt,v.mode=22;case 22:if(v.extra){for(N=v.extra;B>>=v.extra,B-=v.extra,v.back+=v.extra}v.was=v.length,v.mode=23;case 23:for(;dt=(R=v.distcode[A&(1<>>16&255,Ct=65535&R,!((pt=R>>>24)<=B);){if(K===0)break t;K--,A+=G[H++]<>Ht)])>>>16&255,Ct=65535&R,!(Ht+(pt=R>>>24)<=B);){if(K===0)break t;K--,A+=G[H++]<>>=Ht,B-=Ht,v.back+=Ht}if(A>>>=pt,B-=pt,v.back+=pt,64&dt){L.msg="invalid distance code",v.mode=30;break}v.offset=Ct,v.extra=15&dt,v.mode=24;case 24:if(v.extra){for(N=v.extra;B>>=v.extra,B-=v.extra,v.back+=v.extra}if(v.offset>v.dmax){L.msg="invalid distance too far back",v.mode=30;break}v.mode=25;case 25:if(lt===0)break t;if(J=rt-lt,v.offset>J){if((J=v.offset-J)>v.whave&&v.sane){L.msg="invalid distance too far back",v.mode=30;break}ct=J>v.wnext?(J-=v.wnext,v.wsize-J):v.wnext-J,J>v.length&&(J=v.length),Nt=v.window}else Nt=et,ct=nt-v.offset,J=v.length;for(ltE?(P=ct[Nt+m[k]],B[ot+m[k]]):(P=96,0),b=1<>nt)+(y-=b)]=C<<24|P<<16|I|0,y!==0;);for(b=1<>=1;if(b!==0?(A&=b-1,A+=b):A=0,k++,--rt[L]==0){if(L===G)break;L=u[f+m[k]]}if(et>>7)]}function ot(R,D){R.pending_buf[R.pending++]=255&D,R.pending_buf[R.pending++]=D>>>8&255}function rt(R,D,Q){R.bi_valid>S-Q?(R.bi_buf|=D<>S-R.bi_valid,R.bi_valid+=Q-S):(R.bi_buf|=D<>>=1,Q<<=1,0<--D;);return Q>>>1}function Nt(R,D,Q){var $,U,it=new Array(m+1),mt=0;for($=1;$<=m;$++)it[$]=mt=mt+Q[$-1]<<1;for(U=0;U<=D;U++){var at=R[2*U+1];at!==0&&(R[2*U]=ct(it[at]++,at))}}function pt(R){var D;for(D=0;D>1;1<=Q;Q--)Ht(R,it,Q);for(U=Mt;Q=R.heap[1],R.heap[1]=R.heap[R.heap_len--],Ht(R,it,1),$=R.heap[1],R.heap[--R.heap_max]=Q,R.heap[--R.heap_max]=$,it[2*U]=it[2*Q]+it[2*$],R.depth[U]=(R.depth[Q]>=R.depth[$]?R.depth[Q]:R.depth[$])+1,it[2*Q+1]=it[2*$+1]=U,R.heap[1]=U++,Ht(R,it,1),2<=R.heap_len;);R.heap[--R.heap_max]=R.heap[1],function(Ut,qe){var Ts,ui,Cs,ge,cn,rr,yi=qe.dyn_tree,Io=qe.max_code,Cl=qe.stat_desc.static_tree,Rl=qe.stat_desc.has_stree,Nl=qe.stat_desc.extra_bits,ko=qe.stat_desc.extra_base,Rs=qe.stat_desc.max_length,un=0;for(ge=0;ge<=m;ge++)Ut.bl_count[ge]=0;for(yi[2*Ut.heap[Ut.heap_max]+1]=0,Ts=Ut.heap_max+1;Ts>=7;U>>=1)if(1&ee&&at.dyn_ltree[2*Mt]!==0)return o;if(at.dyn_ltree[18]!==0||at.dyn_ltree[20]!==0||at.dyn_ltree[26]!==0)return a;for(Mt=32;Mt>>3,(it=R.static_len+3+7>>>3)<=U&&(U=it)):U=it=Q+5,Q+4<=U&&D!==-1?N(R,D,Q,$):R.strategy===4||it===U?(rt(R,2+($?1:0),3),me(R,F,L)):(rt(R,4+($?1:0),3),function(at,Mt,ee,Ut){var qe;for(rt(at,Mt-257,5),rt(at,ee-1,5),rt(at,Ut-4,4),qe=0;qe>>8&255,R.pending_buf[R.d_buf+2*R.last_lit+1]=255&D,R.pending_buf[R.l_buf+R.last_lit]=255&Q,R.last_lit++,D===0?R.dyn_ltree[2*Q]++:(R.matches++,D--,R.dyn_ltree[2*(v[Q]+u+1)]++,R.dyn_dtree[2*B(D)]++),R.last_lit===R.lit_bufsize-1},s._tr_align=function(R){rt(R,2,3),J(R,y,F),function(D){D.bi_valid===16?(ot(D,D.bi_buf),D.bi_buf=0,D.bi_valid=0):8<=D.bi_valid&&(D.pending_buf[D.pending++]=255&D.bi_buf,D.bi_buf>>=8,D.bi_valid-=8)}(R)}},{"../utils/common":41}],53:[function(e,i,s){i.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(e,i,s){i.exports=typeof setImmediate=="function"?setImmediate:function(){var r=[].slice.apply(arguments);r.splice(1,0,0),setTimeout.apply(null,r)}},{}]},{},[10])(10)})})(ll);var fa=ll.exports;class sf{static MXLtoIXmlElement(t){const e=new fa;return e.loadAsync(t).then(r=>e.file("META-INF/container.xml").async("text"),r=>{throw r}).then(r=>{const l=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("rootfile")[0].getAttribute("full-path");return e.file(l).async("text")},r=>{throw r}).then(r=>{const a=new DOMParser().parseFromString(r,"text/xml"),l=new Ks(a.documentElement);return Promise.resolve(l)},r=>{throw r}).then(r=>r,r=>{throw new Error("extractSheetFromMxl: "+r.message)})}static MXLtoXMLstring(t){const e=new fa;return e.loadAsync(t).then(i=>e.file("META-INF/container.xml").async("text"),i=>{throw j.error(i),i}).then(i=>{const o=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("rootfile")[0].getAttribute("full-path");return e.file(o).async("text")},i=>{throw i})}}class Mo{calculate(t){const e=new Ss(t);for(;!e.EndReached;){const i=e.CurrentEnrolledTimestamp,s=e.CurrentAudibleVoiceEntries();for(const r of s)this.handleVoiceEntry(t,r,i);e.moveToNext()}}handleVoiceEntry(t,e,i){if(e.IsGrace)return;const s=e.ParentVoice;let r;t.PlaybackDataDict.containsKey(s)?r=t.PlaybackDataDict.getValue(s):(r=[],t.PlaybackDataDict.setValue(s,r));for(const o of e.PlaybackEntries)if(o.HasNotes){for(const l of o.Notes)l.setLength();const a=W.plus(i,o.TimestampShift);Mo.addEntrySorted(r,o,a)}}static addEntrySorted(t,e,i){if(t.length===0)t.push({enrolledTimestamp:i,playbackEntry:e});else for(let s=t.length-1;s>=0;s--){const r=t[s];if(i.RealValue>r.enrolledTimestamp.RealValue)if(s===t.length-1){t.push({enrolledTimestamp:i,playbackEntry:e});break}else{t.splice(s+1,0,{enrolledTimestamp:i,playbackEntry:e});break}}}}class Fn{constructor(t,e,i,s){this.psi=new le(void 0),this.displaySizeInPixel=t,this.RelativeDisplaySize=e,this.RelativeDisplayPosition=i,this.WidthInUnits=s}static createWithRelativeDefaults(t,e){return new Fn(t,new $e(1,1),new O(0,0),e)}static createWithDefaults(){return new Fn(new $e(1,1),new $e(1,1),new O(0,0),1)}get UpperLeftPositionInUnits(){return this.psi.AbsolutePosition}set UpperLeftPositionInUnits(t){this.psi.AbsolutePosition=t}get DisplaySizeInPixel(){return this.displaySizeInPixel}set DisplaySizeInPixel(t){this.displaySizeInPixel=t,this.regionSizeInPixel=new $e(this.displaySizeInPixel.width*this.relativeRegionSize.width,this.displaySizeInPixel.height*this.relativeRegionSize.height),this.recalculateDependentVariables()}get RelativeDisplaySize(){return this.relativeRegionSize}set RelativeDisplaySize(t){this.relativeRegionSize=t,this.regionSizeInPixel=new $e(this.displaySizeInPixel.width*this.relativeRegionSize.width,this.displaySizeInPixel.height*this.relativeRegionSize.height),this.recalculateDependentVariables()}get RegionSizeInPixel(){return this.regionSizeInPixel}get WidthInUnits(){return this.psi.BorderRight}set WidthInUnits(t){this.psi.BorderRight=t,this.recalculateDependentVariables()}get ViewRegionInUnits(){return new $e(this.psi.BorderRight,this.psi.BorderBottom)}isVisible(t,e){const i=this.psi.collisionDetection(t);return this.psi.liesInsideBorders(t),i}isInsideDisplayArea(t,e){return this.RelativeDisplayPosition.x<=t&&t<=this.RelativeDisplayPosition.x+this.RelativeDisplaySize.width&&this.RelativeDisplayPosition.y<=e&&e<=this.RelativeDisplayPosition.y+this.RelativeDisplaySize.height}transformToUnitCoordinates(t){return new O(this.UpperLeftPositionInUnits.x+this.ViewRegionInUnits.width*((t.x-this.RelativeDisplayPosition.x)/this.RelativeDisplaySize.width),this.UpperLeftPositionInUnits.y+this.ViewRegionInUnits.height*((t.y-this.RelativeDisplayPosition.y)/this.RelativeDisplaySize.height))}transformLengthXToUnitCoordinates(t){return t/this.horizontalUnitToPixelRatio}transformLengthYToUnitCoordinates(t){return t/this.verticalUnitToPixelRatio}recalculateDependentVariables(){const t=this.regionSizeInPixel.width/this.regionSizeInPixel.height;this.psi.BorderBottom=this.psi.BorderRight/t,this.horizontalUnitToPixelRatio=this.regionSizeInPixel.width/this.ViewRegionInUnits.width,this.verticalUnitToPixelRatio=this.regionSizeInPixel.height/this.ViewRegionInUnits.height}}class nf{constructor(t){this.aspectRatio=1,this.zoomViews=[],this.mouseZoomMode=!1,this.autoScrollY=!0,this.displayInteractionManager=t,this.displayInteractionManager.addListener(this),this.offsetXMin=Number.MIN_VALUE,this.offsetYMin=Number.MIN_VALUE,this.rangeXMin=1,this.rangeYMin=1,this.offsetXMax=Number.MAX_VALUE,this.offsetYMax=Number.MAX_VALUE,this.rangeXMax=1e9,this.rangeYMax=1e9,this.XScrollingEnabled=!1,this.YScrollingEnabled=!0}positionTouched(t,e){if(!this.convertToUnitsReady())return;const i=this.getPositionInUnits(t,e);this.unitPosTouched(i,t,e)}get TouchActive(){return this.displayInteractionManager.TouchActive}get TouchMoving(){return this.displayInteractionManager.TouchMoving}positionDoubleTouched(t,e){if(!this.convertToUnitsReady())return;const i=this.getPositionInUnits(t,e);this.unitPosDoubleTouched(i,t,e)}get UsesManuallyControlledZoomMode(){return this.usesManuallyControlledZoomMode}set UsesManuallyControlledZoomMode(t){this.usesManuallyControlledZoomMode=t}mouseDown(t,e,i=!1){if(!this.convertToUnitsReady())return;this.selectScrollControllerY(!1),this.lastRangeX=Math.max(1,this.RangeX),this.lastRangeY=Math.max(1,this.RangeY),this.lastOffsetX=this.OffsetX,this.lastOffsetY=this.OffsetY;const s=this.getPositionInUnits(t,e);this.unitPosTouchDown(s,t,e),this.usesManuallyControlledZoomMode||(i?this.mouseZoomMode=!0:this.mouseZoomMode=!1)}mouseUp(t,e){const i=this.getPositionInUnits(t,e);this.unitPosTouchUp(i,t,e)}mouseMove(t,e,i,s){this.mouseZoomMode?(Math.abs(i-0)>1e-8&&(this.RangeX=Math.abs(this.lastRangeX/(1+i))),!this.lockRanges&&Math.abs(s-0)>1e-8&&(this.RangeY=Math.abs(this.lastRangeY/(1-s)))):(Math.abs(i-0)>1e-8&&(this.OffsetX=this.lastOffsetX-i*this.RangeX),Math.abs(s-0)>1e-8&&(this.OffsetY=this.lastOffsetY-s*this.RangeY));const r=this.getPositionInUnits(t,e);this.unitPosMove(r,t,e)}zoom(t){this.RangeX=Math.abs(this.lastRangeX/t)}addZoomView(t){this.zoomViews.push(t)}get OffsetX(){return this.offsetX}set OffsetX(t){this.offsetX=Math.min(this.offsetXMax,Math.max(this.offsetXMin,t));for(const e of this.zoomViews)e.viewportXChanged(this.offsetX,this.RangeX)}get OffsetY(){return this.offsetY}set OffsetY(t){this.offsetY=t,this.offsetY>this.offsetYMax?this.offsetY=this.offsetYMax:this.offsetY(n[n.SingleTouch=0]="SingleTouch",n[n.DoubleTouch=1]="DoubleTouch",n[n.TouchUp=2]="TouchUp",n[n.TouchDown=3]="TouchDown",n[n.Move=4]="Move",n))(Ve||{});class rf{constructor(t){this.renderingManager=t}userDisplayInteraction(t,e,i){var s,r;switch(i){case Ve.TouchDown:case Ve.SingleTouch:case Ve.DoubleTouch:{const o=this.renderingManager.GraphicalMusicSheet.GetNearestVoiceEntry(e);o&&o.parentStaffEntry.parentVerticalContainer!==void 0&&((s=o.notes[0])==null?void 0:s.sourceNote.Pitch)!==void 0&&((r=this.renderingManager.PlaybackManager)==null||r.playVoiceEntry(o.parentVoiceEntry));break}}}}class of extends nf{constructor(t,e){super(t),this.mainViewingRegion=Fn.createWithDefaults(),this.tryAgainToRenderCount=0,this.yOffsetMouseDown=Number.MIN_VALUE,this.unlockCursorDistancePixel=50,this.relativeTopPosition=.06,this.internalPreviewImageScale=3,this.listeners=[],this.LockDisplayToCursor=!0,this.ZoomActive=!1,this.rules=e,this.addZoomView(this),this.lockRanges=!0,this.TopBarHeightInPixel=70,this.BottomBarHeightInPixel=0,this.rules.UseDefaultVoiceInteractionListener&&this.listeners.push(new rf(this))}addListener(t){this.listeners.push(t)}get Listeners(){return this.listeners}convertToUnitsReady(){return this.graphicalMusicSheet!==void 0}unitPosTouched(t,e,i){if(!this.SingleTouchDisabled){const s=new O(e,i);this.handleUserDisplayInteraction(s,t,Ve.SingleTouch)}}unitPosDoubleTouched(t,e,i){if(!this.DoubleTouchDisabled){const s=new O(e,i);this.handleUserDisplayInteraction(s,t,Ve.DoubleTouch)}}unitPosTouchDown(t,e,i){const s=new O(e,i);this.handleUserDisplayInteraction(s,t,Ve.TouchDown),this.yOffsetMouseDown=t.y}unitPosTouchUp(t,e,i){const s=new O(e,i);this.handleUserDisplayInteraction(s,t,Ve.TouchUp),this.displayInteractionManager.WasZoomGestureActive===!1&&this.unlockFromCursorIfNecessary(t),this.yOffsetMouseDown=Number.MIN_VALUE}unitPosMove(t,e,i){const s=new O(e,i);this.handleUserDisplayInteraction(s,t,Ve.Move),this.unlockFromCursorIfNecessary(t)}get MainViewingRegion(){return this.mainViewingRegion}setMusicSheet(t){this.graphicalMusicSheet=t,this.adaptDisplayLimitsToSheet(),this.setYOffset(0,!0)}viewportXChanged(t,e){this.graphicalMusicSheet!==void 0&&this.horizontalViewportChanged(t,e)}viewportYChanged(t,e){this.graphicalMusicSheet!==void 0&&(this.yOffsetMouseDown<=Number.MIN_VALUE+.5&&(this.yOffsetMouseDown=t),this.verticalViewportChanged(t,e))}displaySizeChanged(t,e){super.viewSizeChanged(t,e),!(Math.abs(t-0)<1e-7||Math.abs(e-0)<1e-7)&&(this.graphicalMusicSheet!==void 0&&this.graphicalMusicSheet.EnforceRedrawOfMusicSystems(),this.mainViewingRegion.DisplaySizeInPixel=new $e(t,e),this.adaptDisplayLimitsToSheet())}calcDisplayYPosition(t){return t.PositionAndShape.AbsolutePosition.y+t.PositionAndShape.BorderMarginTop-this.topBarHeightInUnits()-this.relativeTopPosition*this.heightWithoutTopBottomBarsInUnits()}yPositionForLastSystem(t){return t.PositionAndShape.AbsolutePosition.y+t.PositionAndShape.BorderMarginBottom-this.topBarHeightInUnits()-(1-this.relativeTopPosition)*this.heightWithoutTopBottomBarsInUnits()}scorePositionChanged(t,e,i,s,r,o){const a=this.calcDisplayYPosition(s);this.setYPosition(a,o)}setXPosition(t,e){this.LockDisplayToCursor&&this.setXOffset(t,e)}setYPosition(t,e){this.LockDisplayToCursor&&this.setYOffset(t,e)}get DrawingParameters(){return this.musicSheetDrawer.drawingParameters}topBarHeightInUnits(){return this.mainViewingRegion.transformLengthYToUnitCoordinates(this.TopBarHeightInPixel)}bottomBarHeightInUnits(){return this.mainViewingRegion.transformLengthYToUnitCoordinates(this.BottomBarHeightInPixel)}heightWithoutTopBottomBarsInUnits(){return this.mainViewingRegion.ViewRegionInUnits.height-this.topBarHeightInUnits()-this.bottomBarHeightInUnits()}activePositionToBottomBarHeight(){return(this.mainViewingRegion.ViewRegionInUnits.height-this.topBarHeightInUnits()-this.bottomBarHeightInUnits())*(1-2*this.relativeTopPosition)}getClickPosition(t,e){return this.mainViewingRegion.transformToUnitCoordinates(new O(t,e))}graphicalObjectIsVisible(t){return this.mainViewingRegion.isVisible(t,!1)}adaptDisplayLimitsToSheet(){if(this.graphicalMusicSheet===void 0||this.graphicalMusicSheet.MusicPages.length===0||this.graphicalMusicSheet.MusicPages[0].MusicSystems.length===0)return;this.offsetXMin=0,this.rangeXMin=this.graphicalMusicSheet.MinAllowedSystemWidth,this.rangeXMax=300,this.offsetYMin=-.3*this.RangeY;const t=this.graphicalMusicSheet.MusicPages.last().PositionAndShape;this.offsetYMax=Math.max(0,t.BorderMarginBottom-.7*this.RangeY),this.OffsetY>this.offsetYMax&&this.setYOffset(this.offsetYMax,!0)}horizontalViewportChanged(t,e){this.mainViewingRegion.WidthInUnits!==e&&(this.mainViewingRegion.WidthInUnits=e)}verticalViewportChanged(t,e){this.mainViewingRegion.UpperLeftPositionInUnits=new O(this.mainViewingRegion.UpperLeftPositionInUnits.x,t)}unlockFromCursorIfNecessary(t){if(this.LockDisplayToCursor===!1||this.ZoomActive||this.displayInteractionManager.ZoomGestureActive||this.displayInteractionManager.WasZoomGestureActive)return;Math.abs((t.y-this.yOffsetMouseDown)*this.mainViewingRegion.RegionSizeInPixel.height/this.mainViewingRegion.ViewRegionInUnits.height)>this.unlockCursorDistancePixel&&(this.LockDisplayToCursor=!1)}getPositionInUnits(t,e){return this.mainViewingRegion.transformToUnitCoordinates(new O(t,e))}handleUserDisplayInteraction(t,e,i){switch(i){case Ve.TouchDown:case Ve.SingleTouch:case Ve.DoubleTouch:{const s=this.graphicalMusicSheet.GetNearestVoiceEntry(e);if(s){const r=new CustomEvent("note-click",{detail:os(be({},s),{setAvtivePlay:()=>{var o,a;if(s.parentStaffEntry.parentVerticalContainer!==void 0){const l=s.parentStaffEntry.parentVerticalContainer.AbsoluteTimestamp;this.setStartPosition(l),((o=s.notes[0])==null?void 0:o.sourceNote.Pitch)!==void 0&&(console.log("playback clicked note",s.parentVoiceEntry),(a=this.PlaybackManager)==null||a.playVoiceEntry(s.parentVoiceEntry))}}})});window.dispatchEvent(r)}}case Ve.TouchUp:case Ve.TouchDown:case Ve.Move:for(const s of this.listeners)s.userDisplayInteraction(t,e,i);break;default:throw new Error("type")}}setStartPosition(t){var e;this.graphicalMusicSheet!==void 0&&(this.graphicalMusicSheet.ParentMusicSheet.SelectionStart=t,(e=this.PlaybackManager)==null||e.reset())}get GraphicalMusicSheet(){return this.graphicalMusicSheet}}class af extends of{mouseMove(t,e,i,s){const r=this.getPositionInUnits(t,e);this.unitPosMove(r,t,e)}}class lf{constructor(){this.listeners=[],this.zoomGestureActive=!1,this.touchCount=0,this.touchActive=!1,this.touchMoving=!1,this.displayWidth=1,this.displayHeight=1,this.displayDpi=96,this.maxNumerOfFingers=2,this.movementThreshInch=.075,this.interactionWasZoomGesture=!1}addListener(t){this.listeners.push(t)}get ZoomGestureActive(){return this.zoomGestureActive}get WasZoomGestureActive(){return this.interactionWasZoomGesture}displaySizeChanged(t,e){this.displayWidth=t,this.displayHeight=e;for(const i of this.listeners)i.displaySizeChanged(this.displayWidth,this.displayHeight)}Dispose(){this.dispose()}Initialize(){this.initialize()}get DisplayDpi(){return this.displayDpi}get TouchActive(){return this.touchActive}get TouchMoving(){return this.touchMoving}touchDown(t,e,i){this.interactionWasZoomGesture=!1;const s=t/this.displayWidth,r=e/this.displayHeight;this.lastRelPosX=s,this.lastRelPosY=r,this.lastPixelX=t,this.lastPixelY=e,this.touchActive=!0,this.touchMoving=!1,this.touchCount=Math.min(this.touchCount+1,this.maxNumerOfFingers);for(const o of this.listeners)o.mouseDown(s,r,!i)}move(t,e){if(this.touchActive&&!this.zoomGestureActive){const i=t/this.displayWidth,s=e/this.displayHeight,r=i-this.lastRelPosX,o=s-this.lastRelPosY;this.touchMoving=!0;for(const a of this.listeners)a.mouseMove(i,s,r,o)}}zoomGestureStarted(){this.zoomGestureActive=!0}zoomGestureCompleted(){this.zoomGestureActive=!1,this.interactionWasZoomGesture=!0}zoomGestureMove(t){this.zoomGestureActive&&this.listeners.forEach(function(e){e.zoom(t)})}touchUp(t,e){this.touchActive=!1,this.touchMoving=!1,this.touchCount=Math.max(0,this.touchCount-1);const i=t/this.displayWidth,s=e/this.displayHeight;for(const r of this.listeners)r.mouseUp(i,s)}click(t,e){if(!this.mouseDidMove(this.lastPixelX,t,this.lastPixelY,e)&&!this.ZoomGestureActive){const i=t/this.displayWidth,s=e/this.displayHeight;for(const r of this.listeners)r.positionTouched(i,s)}}doubleClick(t,e){if(!this.mouseDidMove(this.lastPixelX,t,this.lastPixelY,e)&&!this.ZoomGestureActive){const i=t/this.displayWidth,s=e/this.displayHeight;for(const r of this.listeners)r.positionDoubleTouched(i,s)}}mouseDidMove(t,e,i,s){const r=Math.abs(t-e)/this.displayDpi,o=Math.abs(i-s)/this.displayDpi;return r>this.movementThreshInch||o>this.movementThreshInch}}class On extends lf{constructor(t){super(),this.fullOffsetLeft=0,this.fullOffsetTop=0,this.fullScrollTop=0,this.fullScrollLeft=0,this.parentScrollMap=new Map,this.scrollCallbackMap=new Map,this.timeout=void 0,this.resizeObserver=void 0,this.EventCallbackMap=new Ye,this.DOUBLE_CLICK_WINDOW=200,this.lastClick=0,this.osmdSheetMusicContainer=t,this.listenForInteractions()}get FullOffsetTop(){return this.fullOffsetTop}get FullScrollTop(){return this.fullScrollTop}get FullOffsetLeft(){return this.fullOffsetLeft}get FullScrollLeft(){return this.fullScrollLeft}static resizeCallback(t,e){clearTimeout(e.timeout),e.timeout=setTimeout(()=>{e.fullOffsetLeft=0,e.fullOffsetTop=0;let i=e.osmdSheetMusicContainer;for(;i;)e.fullOffsetLeft+=i.offsetLeft,e.fullOffsetTop+=i.offsetTop,i=i.offsetParent;e.resizeEventListener(),e.deregisterScrollOffsets(),e.registerScrollOffsets()},500)}registerScrollOffsets(){let t=this.osmdSheetMusicContainer;this.fullScrollTop=0,this.fullScrollLeft=0;const e=this;for(;t&&t!==document.documentElement;){if(this.parentScrollMap.set(t,[t.scrollTop,t.scrollLeft]),this.fullScrollLeft+=t.scrollLeft,this.fullScrollTop+=t.scrollTop,t.scrollHeight>t.clientHeight){const i=function(s){const r=e.parentScrollMap.get(this),o=r[0],a=r[1];e.fullScrollTop=e.fullScrollTop-o+this.scrollTop,e.fullScrollLeft=e.fullScrollLeft-a+this.scrollLeft,e.parentScrollMap.set(this,[this.scrollTop,this.scrollLeft])};this.scrollCallbackMap.set(t,i),t.addEventListener("scroll",i)}t=t.parentElement}}deregisterScrollOffsets(){for(const t of this.scrollCallbackMap.keys())t.removeEventListener("scroll",this.scrollCallbackMap.get(t));this.scrollCallbackMap.clear()}initialize(){this.fullOffsetLeft=0,this.fullOffsetTop=0;let t=this.osmdSheetMusicContainer;const e=[],i=this;for(window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(s=>{On.resizeCallback(s,i)}));t;)this.fullOffsetLeft+=t.offsetLeft,this.fullOffsetTop+=t.offsetTop,this.resizeObserver?this.resizeObserver.observe(t):e.push(t),t=t.offsetParent;if(this.resizeObserver)this.disposeResizeListener=()=>{i.resizeObserver.disconnect(),i.resizeObserver=void 0};else{let s=()=>{On.resizeCallback(e,i)};window.addEventListener("resize",s),this.disposeResizeListener=()=>{window.removeEventListener("resize",s),s=void 0}}i.registerScrollOffsets()}dispose(){this.disposeResizeListener();for(const t of this.EventCallbackMap.keys()){const e=this.EventCallbackMap.getValue(t);e[0].removeEventListener(t,e[1])}this.EventCallbackMap.clear(),this.deregisterScrollOffsets(),this.scrollCallbackMap.clear(),this.parentScrollMap.clear()}isTouch(){if("ontouchstart"in window||window.DocumentTouch)return!0;if(!window.matchMedia)return!1;const e=["(",["-webkit-","-moz-","-o-","-ms-"].join("touch-enabled),("),"heartz",")"].join("");return window.matchMedia(e).matches}get downEventName(){return this.isTouch()?"touchstart":"mousedown"}get moveEventName(){return this.isTouch()?"touchmove":"mousemove"}listenForInteractions(){const t=this.downEventListener.bind(this),e=this.touchEndEventListener.bind(this),i=this.moveEventListener.bind(this);this.osmdSheetMusicContainer.addEventListener("mousedown",t),this.osmdSheetMusicContainer.addEventListener("touchend",e),document.addEventListener(this.moveEventName,i),this.EventCallbackMap.setValue("mousedown",[this.osmdSheetMusicContainer,t]),this.EventCallbackMap.setValue("touchend",[this.osmdSheetMusicContainer,e]),this.EventCallbackMap.setValue(this.moveEventName,[document,i])}downEventListener(t){const e=new Date().getTime(),i=e-this.lastClick;clearTimeout(this.clickTimeout);let s=0,r=0;this.isTouch()&&t instanceof TouchEvent?(s=t.touches[0].pageX,r=t.touches[0].pageY):t instanceof MouseEvent&&(s=t.pageX,r=t.pageY);const o=this.getOffsetCoordinates(s,r);if(i0)this.doubleClick(o.x,o.y);else{const a=this;this.clickTimeout=setTimeout(function(){clearTimeout(this.clickTimeout),a.isTouch()?a.touchDown(o.x,o.y,void 0):a.click(o.x,o.y)},this.DOUBLE_CLICK_WINDOW)}this.lastClick=e}moveEventListener(t){let e=0,i=0;if(this.isTouch()&&t instanceof TouchEvent){let r;t.touches&&t.touches.length>0?r=t.touches[0]:t.changedTouches&&t.changedTouches.length>0&&(r=t.changedTouches[0]),e=r==null?void 0:r.clientX,i=r==null?void 0:r.clientY}else t instanceof MouseEvent&&(e=t.clientX,i=t.clientY);const s=this.getOffsetCoordinates(e,i);this.move(s.x,s.y)}touchEndEventListener(t){let e;t.touches&&t.touches.length>0?e=t.touches[0]:t.changedTouches&&t.changedTouches.length>0&&(e=t.changedTouches[0]);const i=this.getOffsetCoordinates(e==null?void 0:e.pageX,e==null?void 0:e.pageY);this.touchUp(i.x,i.y)}resizeEventListener(){this.displaySizeChanged(this.osmdSheetMusicContainer.clientWidth,this.osmdSheetMusicContainer.clientHeight)}getOffsetCoordinates(t,e){const i=t-this.fullOffsetLeft+this.fullScrollLeft,s=e-this.fullOffsetTop+this.fullScrollTop;return new O(i,s)}}class Vn{static fillDynamicsList(t,e,i){for(let s=0;s=0&&i[l].push(new Pi(a.InstantaneousDynamic,l))}if(a.StartingContinuousDynamic!==void 0){i[s].push(new Pi(a.StartingContinuousDynamic,a.StaffNumber));const l=this.getOtherStaffIndexIfLinkedStavesAreDetected(t,s,a.StartingContinuousDynamic.Placement);l>=0&&i[l].push(new Pi(a.StartingContinuousDynamic,l))}}}}static getOtherStaffIndexIfLinkedStavesAreDetected(t,e,i){const s=t.getStaffFromIndex(e),r=s.ParentInstrument.Staves.indexOf(s),o=s.ParentInstrument.Staves.length;return o>1&&r===0&&i===z.Below?e+1:o>1&&r===1&&i===z.Above?e-1:-1}static fillDynamicExpressions(t){const e=t.DynListStaves,i=t.getCompleteNumberOfStaves(),s=t.TimestampSortedDynamicExpressionsList;for(let r=0;r{t(this.processStringXml(i))},i=>{j.error(new Error("[OSMD] Invalid MXL file: "+i)),e(new Error("[OSMD] Invalid MXL file: "+i))})}processStringXml(n){const t=new DOMParser;if(n.substr(0,3)==="\uF7EF\uF7BB\uF7BF")return j.debug("[OSMD] UTF with BOM detected, truncate first three bytes and pass along: "+n),t.parseFromString(n.substr(3),"application/xml");if(n.substr(0,6).includes("{e.isMxl(u)?e.processMxl(u,a,l):a(e.processStringXml(u))},u=>{throw l(u),u});else{const u=new Error("[OSMD] osmd.load(string): Could not process string. Did not find {t.init(this.sheet.MusicPartManager,this.graphic)}),this.renderingManager.setMusicSheet(this.graphic),this.interactionManager.Initialize()}render(){var t;if(!this.graphic)throw new Error("OpenSheetMusicDisplay: Before rendering a music sheet, please load a MusicXML file");(t=this.drawer)==null||t.clear();let n=this.container.offsetWidth;this.rules.RenderSingleHorizontalStaffline&&(n=this.rules.SheetMaximumWidth),this.sheet.pageWidth=n/this.zoom/10,this.renderingManager.MainViewingRegion.WidthInUnits=this.sheet.pageWidth,this.rules.PageFormat&&!this.rules.PageFormat.IsUndefined?(this.rules.PageHeight=this.sheet.pageWidth/this.rules.PageFormat.aspectRatio,j.debug("[OSMD] PageHeight: "+this.rules.PageHeight)):(j.debug("[OSMD] endless/undefined pageformat, id: "+this.rules.PageFormat.idString),this.rules.PageHeight=100001),this.graphic.reCalculate(),this.drawingParameters.drawCursors&&(this.graphic.Cursors.length=0),this.createOrRefreshRenderBackend(),this.needBackendUpdate=!1,this.drawer.setZoom(this.zoom),this.drawer.drawSheet(this.graphic),this.enableOrDisableCursors(this.drawingParameters.drawCursors),this.drawingParameters.drawCursors&&this.cursors.forEach(e=>{e.update()}),this.zoomUpdated=!1,this.interactionManager.displaySizeChanged(this.container.clientWidth,this.container.clientHeight)}createOrRefreshRenderBackend(){this.drawer&&this.drawer.Backends&&(this.drawer.Backends[0]&&this.drawer.Backends[0].removeAllChildrenFromContainer(this.container),this.drawer.Backends.clear()),this.drawingParameters.Rules=this.rules,this.drawer=new su(this.drawingParameters),this.drawer.drawableBoundingBoxElement=this.DrawBoundingBox,this.drawer.bottomLineVisible=this.drawBottomLine,this.drawer.skyLineVisible=this.drawSkyLine;let n=this.container.offsetWidth;this.rules.RenderSingleHorizontalStaffline&&(n=this.graphic.MusicPages[0].PositionAndShape.Size.width*10*this.zoom);let t;const e=32767;for(const i of this.graphic.MusicPages){if(i.PageNumber>this.rules.MaxPageToDrawNumber)break;const s=this.createBackend(this.backendType,i),r=" exceeds CanvasBackend limit of 32767. Cutting off score.";s.getOSMDBackendType()===$i.Canvas&&n>e&&(j.warn("[OSMD] Warning: width of "+n+r),n=e),this.rules.PageFormat&&!this.rules.PageFormat.IsUndefined?t=n/this.rules.PageFormat.aspectRatio:(t=i.PositionAndShape.Size.height,t+=this.rules.PageBottomMargin,t+=this.rules.CompactMode?this.rules.PageTopMarginNarrow:this.rules.PageTopMargin,this.rules.RenderTitle&&(t+=this.rules.TitleTopDistance),t*=this.zoom*10),s.getOSMDBackendType()===$i.Canvas&&t>e&&(j.warn("[OSMD] Warning: height of "+t+r),t=Math.min(t,e)),s.resize(n,t),s.clear(),this.drawer.Backends.push(s),this.graphic.drawer=this.drawer}}exportSVG(){var n;for(const t of(n=this.drawer)==null?void 0:n.Backends)t instanceof Rr&&t.export()}IsReadyToRender(){return this.graphic!==void 0}clear(){var n;(n=this.drawer)==null||n.clear(),this.reset()}dispose(){this.disposeResizeListener&&this.disposeResizeListener(),this.InteractionManager&&this.InteractionManager.Dispose()}setOptions(n){if(this.rules||(this.rules=new Ui),this.drawingParameters||(this.drawingParameters=new Ja,this.drawingParameters.Rules=this.rules),n==null){j.warn(`warning: osmd.setOptions() called without an options parameter, has no effect. example usage: osmd.setOptions({drawCredits: false, drawPartNames: false})`);return}this.OnXMLRead=function(s){return s},n.onXMLRead&&(this.OnXMLRead=n.onXMLRead),n.drawingParameters&&(this.drawingParameters.DrawingParametersEnum=vo[n.drawingParameters.toLowerCase()]);let e=!this.drawer||!this.drawer.Backends||this.drawer.Backends.length<1;if(n.backend!==void 0){const s=ea.BackendTypeFromString(n.backend);e=e||this.backendType!==s,this.backendType=s}this.needBackendUpdate=e,n.autoBeam!==void 0&&(this.rules.AutoBeamNotes=n.autoBeam);const i=n.autoBeamOptions;if(i&&(i.maintain_stem_directions===void 0&&(i.maintain_stem_directions=!1),this.rules.AutoBeamOptions=i,i.groups&&i.groups.length)){for(const s of i.groups)if(s.length!==2)throw new Error("Each fraction in autoBeamOptions.groups must be of length 2, e.g. [3,4] for beaming three fourths")}n.percussionOneLineCutoff!==void 0&&(this.rules.PercussionOneLineCutoff=n.percussionOneLineCutoff),this.rules.PercussionOneLineCutoff!==0&&n.percussionForceVoicesOneLineCutoff!==void 0&&(this.rules.PercussionForceVoicesOneLineCutoff=n.percussionForceVoicesOneLineCutoff),n.alignRests!==void 0&&(this.rules.AlignRests=n.alignRests),n.coloringMode!==void 0&&this.setColoringMode(n),n.coloringEnabled!==void 0&&(this.rules.ColoringEnabled=n.coloringEnabled),n.colorStemsLikeNoteheads!==void 0&&(this.rules.ColorStemsLikeNoteheads=n.colorStemsLikeNoteheads),n.disableCursor&&(this.drawingParameters.drawCursors=!1),n.drawHiddenNotes&&(this.drawingParameters.drawHiddenNotes=!0),n.drawCredits!==void 0&&(this.drawingParameters.DrawCredits=n.drawCredits),n.drawComposer!==void 0&&(this.drawingParameters.DrawComposer=n.drawComposer),n.drawTitle!==void 0&&(this.drawingParameters.DrawTitle=n.drawTitle),n.drawSubtitle!==void 0&&(this.drawingParameters.DrawSubtitle=n.drawSubtitle),n.drawLyricist!==void 0&&(this.drawingParameters.DrawLyricist=n.drawLyricist),n.drawMetronomeMarks!==void 0&&(this.rules.MetronomeMarksDrawn=n.drawMetronomeMarks),n.drawPartNames!==void 0&&(this.drawingParameters.DrawPartNames=n.drawPartNames,n.drawPartAbbreviations||(this.rules.RenderPartAbbreviations=n.drawPartNames)),n.drawPartAbbreviations!==void 0&&(this.rules.RenderPartAbbreviations=n.drawPartAbbreviations),n.drawFingerings===!1&&(this.rules.RenderFingerings=!1),n.drawMeasureNumbers!==void 0&&(this.rules.RenderMeasureNumbers=n.drawMeasureNumbers),n.drawMeasureNumbersOnlyAtSystemStart&&(this.rules.RenderMeasureNumbersOnlyAtSystemStart=n.drawMeasureNumbersOnlyAtSystemStart),n.drawLyrics!==void 0&&(this.rules.RenderLyrics=n.drawLyrics),n.drawTimeSignatures!==void 0&&(this.rules.RenderTimeSignatures=n.drawTimeSignatures),n.drawSlurs!==void 0&&(this.rules.RenderSlurs=n.drawSlurs),n.measureNumberInterval!==void 0&&(this.rules.MeasureNumberLabelOffset=n.measureNumberInterval),n.useXMLMeasureNumbers!==void 0&&(this.rules.UseXMLMeasureNumbers=n.useXMLMeasureNumbers),n.fingeringPosition!==void 0&&(this.rules.FingeringPosition=Ii.PlacementEnumFromString(n.fingeringPosition)),n.fingeringInsideStafflines!==void 0&&(this.rules.FingeringInsideStafflines=n.fingeringInsideStafflines),n.newSystemFromXML!==void 0&&(this.rules.NewSystemAtXMLNewSystemAttribute=n.newSystemFromXML),n.newPageFromXML!==void 0&&(this.rules.NewPageAtXMLNewPageAttribute=n.newPageFromXML),n.fillEmptyMeasuresWithWholeRest!==void 0&&(this.rules.FillEmptyMeasuresWithWholeRest=n.fillEmptyMeasuresWithWholeRest),n.followCursor!==void 0&&(this.FollowCursor=n.followCursor),n.setWantedStemDirectionByXml!==void 0&&(this.rules.SetWantedStemDirectionByXml=n.setWantedStemDirectionByXml),n.darkMode?(this.rules.applyDefaultColorMusic("#FFFFFF"),this.rules.PageBackgroundColor="#000000"):n.darkMode===!1&&(this.rules.applyDefaultColorMusic("#000000"),this.rules.PageBackgroundColor=void 0),n.defaultColorMusic&&this.rules.applyDefaultColorMusic(n.defaultColorMusic),n.defaultColorNotehead&&(this.rules.DefaultColorNotehead=n.defaultColorNotehead),n.defaultColorRest&&(this.rules.DefaultColorRest=n.defaultColorRest),n.defaultColorStem&&(this.rules.DefaultColorStem=n.defaultColorStem),n.defaultColorLabel&&(this.rules.DefaultColorLabel=n.defaultColorLabel),n.defaultColorTitle&&(this.rules.DefaultColorTitle=n.defaultColorTitle),n.defaultFontFamily&&(this.rules.DefaultFontFamily=n.defaultFontFamily),n.defaultFontStyle&&(this.rules.DefaultFontStyle=n.defaultFontStyle),n.drawUpToMeasureNumber&&(this.rules.MaxMeasureToDrawIndex=n.drawUpToMeasureNumber-1),n.drawFromMeasureNumber&&(this.rules.MinMeasureToDrawIndex=n.drawFromMeasureNumber-1),n.drawUpToPageNumber&&(this.rules.MaxPageToDrawNumber=n.drawUpToPageNumber),n.drawUpToSystemNumber&&(this.rules.MaxSystemToDrawNumber=n.drawUpToSystemNumber),n.tupletsRatioed&&(this.rules.TupletsRatioed=!0),n.tupletsBracketed&&(this.rules.TupletsBracketed=!0),n.tripletsBracketed&&(this.rules.TripletsBracketed=!0),n.autoResize?(this.resizeHandlerAttached||this.autoResize(),this.autoResizeEnabled=!0):n.autoResize===!1&&(this.autoResizeEnabled=!1),n.pageFormat!==void 0&&this.setPageFormat(n.pageFormat),n.pageBackgroundColor!==void 0&&(this.rules.PageBackgroundColor=n.pageBackgroundColor),n.performanceMode!==void 0&&(this.rules.PerformanceMode=n.performanceMode),n.renderSingleHorizontalStaffline!==void 0&&(this.rules.RenderSingleHorizontalStaffline=n.renderSingleHorizontalStaffline),n.spacingFactorSoftmax!==void 0&&(this.rules.SoftmaxFactorVexFlow=n.spacingFactorSoftmax),n.spacingBetweenTextLines!==void 0&&(this.rules.SpacingBetweenTextLines=n.spacingBetweenTextLines),n.stretchLastSystemLine!==void 0&&(this.rules.StretchLastSystemLine=n.stretchLastSystemLine),n.autoGenerateMutipleRestMeasuresFromRestMeasures!==void 0&&(this.rules.AutoGenerateMutipleRestMeasuresFromRestMeasures=n.autoGenerateMutipleRestMeasuresFromRestMeasures),n.cursorsOptions!==void 0?this.cursorsOptions=n.cursorsOptions:this.cursorsOptions=[{type:0,color:this.EngravingRules.DefaultColorCursor,alpha:.5,follow:!0}]}setColoringMode(n){if(n.coloringMode===Ci.XML){this.rules.ColoringMode=Ci.XML;return}const t=[ut.C,ut.D,ut.E,ut.F,ut.G,ut.A,ut.B,-1];let e;if(n.coloringMode===Ci.CustomColorSet){if(!n.coloringSetCustom||n.coloringSetCustom.length!==8)throw new Error("Invalid amount of colors: With coloringModes.customColorSet, you have to provide a coloringSetCustom parameter with 8 strings (C to B, rest note).");for(const s of n.coloringSetCustom)if(!/^\#[0-9a-fA-F]{6}$/.test(s))throw new Error(`One of the color strings in options.coloringSetCustom was not a valid HTML Hex color: `+s);e=n.coloringSetCustom}else if(n.coloringMode===Ci.AutoColoring){e=[];const s=Object.keys(wr);for(let r=0;r{n.hide()}),this.sheet=void 0,this.graphic=void 0,this.zoom=1}autoResize(){const n=this;this.handleResize(()=>{},()=>{var t;((t=this.graphic)==null?void 0:t.GetCalculator)instanceof Sr&&(this.graphic.GetCalculator.beamsNeedUpdate=!0),n.IsReadyToRender()&&n.render()})}handleResize(n,t){let e,i;const r=this;function o(){!r.AutoResizeEnabled||(e=new Date().getTime(),i||(n(),e=new Date().getTime(),i=window.setTimeout(a,200)))}function a(){i=void 0,window.clearTimeout(i),new Date().getTime()-e<200?i=window.setTimeout(a,200):t()}window.attachEvent?window.attachEvent("onresize",o):window.addEventListener("resize",o),this.disposeResizeListener=()=>{window.detachEvent?window.detachEvent("onresize",o):window.removeEventListener("resize",o),this.resizeHandlerAttached=!1},this.resizeHandlerAttached=!0,window.setTimeout(n,0),window.setTimeout(t,1)}enableOrDisableCursors(n){var t,e,i,s,r,o;if(this.drawingParameters.drawCursors=n,n){for(let a=0;a{a.hide()})}createBackend(n,t){let e;return n===void 0||n===$i.SVG?e=new Rr(this.rules):e=new il(this.rules),e.graphicalMusicPage=t,e.initialize(this.container,this.zoom),e.getContext().setFillStyle(this.rules.DefaultColorMusic),e.getContext().setStrokeStyle(this.rules.DefaultColorMusic),e}static StringToPageFormat(n){let t=Ce.UndefinedPageFormat;if(n.match("^[0-9]+x[0-9]+$")){const e=n.split("x"),i=Number.parseInt(e[0],10),s=Number.parseInt(e[1],10);i>0&&i<32768&&s>0&&s<32768&&(t=new Ce(i,s,`customPageFormat${n}`))}return n=n.replace(" ","_"),n=n.replace("Landscape","L"),n=n.replace("Portrait","P"),Mn.PageFormatStandards.hasOwnProperty(n)&&(t=Mn.PageFormatStandards[n]),t}setPageFormat(n){const t=Mn.StringToPageFormat(n);this.needBackendUpdate=!t.Equals(this.rules.PageFormat),this.rules.PageFormat=t}setCustomPageFormat(n,t){if(n>0&&t>0){const e=new Ce(n,t);this.rules.PageFormat=e}}set DrawSkyLine(n){this.drawSkyLine=n,this.drawer&&(this.drawer.skyLineVisible=n)}get DrawSkyLine(){return this.drawer.skyLineVisible}set DrawBottomLine(n){this.drawBottomLine=n,this.drawer&&(this.drawer.bottomLineVisible=n)}get DrawBottomLine(){return this.drawer.bottomLineVisible}set DrawBoundingBox(n){this.setDrawBoundingBox(n,!0)}get DrawBoundingBox(){return this.drawBoundingBox}setDrawBoundingBox(n,t=!1){this.drawBoundingBox=n,this.drawer&&(this.drawer.drawableBoundingBoxElement=n),t&&this.render()}get AutoResizeEnabled(){return this.autoResizeEnabled}set AutoResizeEnabled(n){this.autoResizeEnabled=n}get Zoom(){return this.zoom}set Zoom(n){var t;this.zoom=n,this.zoomUpdated=!0,((t=this.graphic)==null?void 0:t.GetCalculator)instanceof Sr&&(this.graphic.GetCalculator.beamsNeedUpdate=this.zoomUpdated)}set FollowCursor(n){this.followCursor=n}get FollowCursor(){return this.followCursor}set TransposeCalculator(n){Lt.transposeCalculator=n}get TransposeCalculator(){return Lt.transposeCalculator}get Sheet(){return this.sheet}get Drawer(){return this.drawer}get GraphicSheet(){return this.graphic}get DrawingParameters(){return this.drawingParameters}get EngravingRules(){return this.rules}get InteractionManager(){return this.interactionManager}get Version(){return this.version}};let hf=Mn;hf.PageFormatStandards={A3_L:new Ce(420,297,"A3_L"),A3_P:new Ce(297,420,"A3_P"),A4_L:new Ce(297,210,"A4_L"),A4_P:new Ce(210,297,"A4_P"),A5_L:new Ce(210,148,"A5_L"),A5_P:new Ce(148,210,"A5_P"),A6_L:new Ce(148,105,"A6_L"),A6_P:new Ce(105,148,"A6_P"),Endless:Ce.UndefinedPageFormat,Letter_L:new Ce(279.4,215.9,"Letter_L"),Letter_P:new Ce(215.9,279.4,"Letter_P")};var da={exports:{}},Ar={exports:{}},ni={},ne={};ne.__esModule=!0;ne.extend=hl;ne.indexOf=pf;ne.escapeExpression=mf;ne.isEmpty=gf;ne.createFrame=bf;ne.blockParams=Sf;ne.appendContextPath=yf;var cf={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`","=":"="},uf=/[&<>"'`=]/g,ff=/[&<>"'`=]/;function df(n){return cf[n]}function hl(n){for(var t=1;t0?(r.ids&&(r.ids=[r.name]),i.helpers.each(s,r)):o(this);if(r.data&&r.ids){var l=e.createFrame(r.data);l.contextPath=e.appendContextPath(r.data.contextPath,r.name),r={data:l}}return a(s,r)})},n.exports=t.default})(kr,kr.exports);var Br={exports:{}};(function(n,t){t.__esModule=!0;function e(o){return o&&o.__esModule?o:{default:o}}var i=ne,s=je.exports,r=e(s);t.default=function(o){o.registerHelper("each",function(a,l){if(!l)throw new r.default("Must pass iterator to #each");var h=l.fn,c=l.inverse,u=0,f="",d=void 0,p=void 0;l.data&&l.ids&&(p=i.appendContextPath(l.data.contextPath,l.ids[0])+"."),i.isFunction(a)&&(a=a.call(this)),l.data&&(d=i.createFrame(l.data));function g(x,w,T){d&&(d.key=x,d.index=w,d.first=w===0,d.last=!!T,p&&(d.contextPath=p+x)),f=f+h(a[x],{data:d,blockParams:i.blockParams([a[x],x],[p+x,null])})}if(a&&typeof a=="object")if(i.isArray(a))for(var m=a.length;u=0?r=o:r=parseInt(r,10)}return r},log:function(r){if(r=i.lookupLevel(r),typeof console!="undefined"&&i.lookupLevel(i.level)<=r){var o=i.methodMap[r];console[o]||(o="log");for(var a=arguments.length,l=Array(a>1?a-1:0),h=1;h= 2.0.0-beta.1",7:">= 4.0.0 <4.3.0",8:">= 4.3.0"};ni.REVISION_CHANGES=sd;var xr="[object Object]";function Ur(n,t,e){this.helpers=n||{},this.partials=t||{},this.decorators=e||{},Jf.registerDefaultHelpers(this),Zf.registerDefaultDecorators(this)}Ur.prototype={constructor:Ur,logger:Un.default,log:Un.default.log,registerHelper:function(t,e){if(Ji.toString.call(t)===xr){if(e)throw new yr.default("Arg not supported with multiple helpers");Ji.extend(this.helpers,t)}else this.helpers[t]=e},unregisterHelper:function(t){delete this.helpers[t]},registerPartial:function(t,e){if(Ji.toString.call(t)===xr)Ji.extend(this.partials,t);else{if(typeof e=="undefined")throw new yr.default('Attempting to register a partial called "'+t+'" as undefined');this.partials[t]=e}},unregisterPartial:function(t){delete this.partials[t]},registerDecorator:function(t,e){if(Ji.toString.call(t)===xr){if(e)throw new yr.default("Arg not supported with multiple decorators");Ji.extend(this.decorators,t)}else this.decorators[t]=e},unregisterDecorator:function(t){delete this.decorators[t]},resetLoggedPropertyAccesses:function(){$f.resetLoggedProperties()}};var nd=Un.default.log;ni.log=nd;ni.createFrame=Ji.createFrame;ni.logger=Un.default;var zr={exports:{}};(function(n,t){t.__esModule=!0;function e(i){this.string=i}e.prototype.toString=e.prototype.toHTML=function(){return""+this.string},t.default=e,n.exports=t.default})(zr,zr.exports);var Hi={},Co={};Co.__esModule=!0;Co.wrapHelper=rd;function rd(n,t){if(typeof n!="function")return n;var e=function(){var s=arguments[arguments.length-1];return arguments[arguments.length-1]=t(s),n.apply(this,arguments)};return e}Hi.__esModule=!0;Hi.checkRevision=ud;Hi.template=fd;Hi.wrapProgram=Pn;Hi.resolvePartial=dd;Hi.invokePartial=pd;Hi.noop=fl;function od(n){return n&&n.__esModule?n:{default:n}}function ad(n){if(n&&n.__esModule)return n;var t={};if(n!=null)for(var e in n)Object.prototype.hasOwnProperty.call(n,e)&&(t[e]=n[e]);return t.default=n,t}var ld=ne,wi=ad(ld),hd=je.exports,Ei=od(hd),Mi=ni,ga=on,cd=Co,ba=Ls;function ud(n){var t=n&&n[0]||1,e=Mi.COMPILER_REVISION;if(!(t>=Mi.LAST_COMPATIBLE_COMPILER_REVISION&&t<=Mi.COMPILER_REVISION))if(t2&&F.push("'"+this.terminals_[C]+"'");this.lexer.showPosition?L="Parse error on line "+(p+1)+`: `+this.lexer.showPosition()+` Expecting `+F.join(", ")+", got '"+(this.terminals_[y]||y)+"'":L="Parse error on line "+(p+1)+": Unexpected "+(y==1?"end of input":"'"+(this.terminals_[y]||y)+"'"),this.parseError(L,{text:this.lexer.match,token:this.terminals_[y]||y,line:this.lexer.yylineno,loc:m,expected:F})}}if(w[0]instanceof Array&&w.length>1)throw new Error("Parse Error: multiple actions possible at state: "+x+", token: "+y);switch(w[0]){case 1:h.push(y),c.push(this.lexer.yytext),u.push(this.lexer.yylloc),h.push(w[1]),y=null,g=this.lexer.yyleng,d=this.lexer.yytext,p=this.lexer.yylineno,m=this.lexer.yylloc;break;case 2:if(P=this.productions_[w[1]][1],E.$=c[c.length-P],E._$={first_line:u[u.length-(P||1)].first_line,last_line:u[u.length-1].last_line,first_column:u[u.length-(P||1)].first_column,last_column:u[u.length-1].last_column},S&&(E._$.range=[u[u.length-(P||1)].range[0],u[u.length-1].range[1]]),T=this.performAction.call(E,d,g,p,this.yy,w[1],c,u),typeof T!="undefined")return T;P&&(h=h.slice(0,-1*P*2),c=c.slice(0,-1*P),u=u.slice(0,-1*P)),h.push(this.productions_[w[1]][0]),c.push(E.$),u.push(E._$),I=f[h[h.length-2]][h[h.length-1]],h.push(I);break;case 3:return!0}}return!0}},s=function(){var o={EOF:1,parseError:function(l,h){if(this.yy.parser)this.yy.parser.parseError(l,h);else throw new Error(l)},setInput:function(l){return this._input=l,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var l=this._input[0];this.yytext+=l,this.yyleng++,this.offset++,this.match+=l,this.matched+=l;var h=l.match(/(?:\r\n?|\n).*/g);return h?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),l},unput:function(l){var h=l.length,c=l.split(/(?:\r\n?|\n)/g);this._input=l+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-h-1),this.offset-=h;var u=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),c.length-1&&(this.yylineno-=c.length-1);var f=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===u.length?this.yylloc.first_column:0)+u[u.length-c.length].length-c[0].length:this.yylloc.first_column-h},this.options.ranges&&(this.yylloc.range=[f[0],f[0]+this.yyleng-h]),this},more:function(){return this._more=!0,this},less:function(l){this.unput(this.match.slice(l))},pastInput:function(){var l=this.matched.substr(0,this.matched.length-this.match.length);return(l.length>20?"...":"")+l.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var l=this.match;return l.length<20&&(l+=this._input.substr(0,20-l.length)),(l.substr(0,20)+(l.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var l=this.pastInput(),h=new Array(l.length+1).join("-");return l+this.upcomingInput()+` `+h+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var l,h,c,u,f;this._more||(this.yytext="",this.match="");for(var d=this._currentRules(),p=0;ph[0].length)&&(h=c,u=p,!this.options.flex)));p++);return h?(f=h[0].match(/(?:\r\n?|\n).*/g),f&&(this.yylineno+=f.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:f?f[f.length-1].length-f[f.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+h[0].length},this.yytext+=h[0],this.match+=h[0],this.matches=h,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(h[0].length),this.matched+=h[0],l=this.performAction.call(this,this.yy,this,d[u],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),l||void 0):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. `+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var l=this.next();return typeof l!="undefined"?l:this.lex()},begin:function(l){this.conditionStack.push(l)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(l){this.begin(l)}};return o.options={},o.performAction=function(l,h,c,u){function f(d,p){return h.yytext=h.yytext.substring(d,h.yyleng-p+d)}switch(c){case 0:if(h.yytext.slice(-2)==="\\\\"?(f(0,1),this.begin("mu")):h.yytext.slice(-1)==="\\"?(f(0,1),this.begin("emu")):this.begin("mu"),h.yytext)return 15;break;case 1:return 15;case 2:return this.popState(),15;case 3:return this.begin("raw"),15;case 4:return this.popState(),this.conditionStack[this.conditionStack.length-1]==="raw"?15:(f(5,9),"END_RAW_BLOCK");case 5:return 15;case 6:return this.popState(),14;case 7:return 65;case 8:return 68;case 9:return 19;case 10:return this.popState(),this.begin("raw"),23;case 11:return 55;case 12:return 60;case 13:return 29;case 14:return 47;case 15:return this.popState(),44;case 16:return this.popState(),44;case 17:return 34;case 18:return 39;case 19:return 51;case 20:return 48;case 21:this.unput(h.yytext),this.popState(),this.begin("com");break;case 22:return this.popState(),14;case 23:return 48;case 24:return 73;case 25:return 72;case 26:return 72;case 27:return 87;case 28:break;case 29:return this.popState(),54;case 30:return this.popState(),33;case 31:return h.yytext=f(1,2).replace(/\\"/g,'"'),80;case 32:return h.yytext=f(1,2).replace(/\\'/g,"'"),80;case 33:return 85;case 34:return 82;case 35:return 82;case 36:return 83;case 37:return 84;case 38:return 81;case 39:return 75;case 40:return 77;case 41:return 72;case 42:return h.yytext=h.yytext.replace(/\\([\\\]])/g,"$1"),72;case 43:return"INVALID";case 44:return 5}},o.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{(?=[^\/]))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]+?(?=(\{\{\{\{)))/,/^(?:[\s\S]*?--(~)?\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#>)/,/^(?:\{\{(~)?#\*?)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{(~)?!--)/,/^(?:\{\{(~)?![\s\S]*?\}\})/,/^(?:\{\{(~)?\*?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)|])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:undefined(?=([~}\s)])))/,/^(?:null(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:as\s+\|)/,/^(?:\|)/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/,/^(?:\[(\\\]|[^\]])*\])/,/^(?:.)/,/^(?:$)/],o.conditions={mu:{rules:[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[6],inclusive:!1},raw:{rules:[3,4,5],inclusive:!1},INITIAL:{rules:[0,1,44],inclusive:!0}},o}();i.lexer=s;function r(){this.yy={}}return r.prototype=i,i.Parser=r,new r}();t.default=e,n.exports=t.default})(Hr,Hr.exports);var Xr={exports:{}},Xn={exports:{}};(function(n,t){t.__esModule=!0;function e(h){return h&&h.__esModule?h:{default:h}}var i=je.exports,s=e(i);function r(){this.parents=[]}r.prototype={constructor:r,mutating:!1,acceptKey:function(c,u){var f=this.accept(c[u]);if(this.mutating){if(f&&!r.prototype[f.type])throw new s.default('Unexpected node type "'+f.type+'" found when accepting '+u+" on "+c.type);c[u]=f}},acceptRequired:function(c,u){if(this.acceptKey(c,u),!c[u])throw new s.default(c.type+" requires "+u)},acceptArray:function(c){for(var u=0,f=c.length;u0)throw new Ro.default("Invalid path: "+i,{loc:e});l===".."&&r++}else s.push(l)}return{type:"PathExpression",data:n,depth:r,parts:s,original:i,loc:e}}function Md(n,t,e,i,s,r){var o=i.charAt(3)||i.charAt(2),a=o!=="{"&&o!=="&",l=/\*/.test(i);return{type:l?"Decorator":"MustacheStatement",path:n,params:t,hash:e,escaped:a,strip:s,loc:this.locInfo(r)}}function Pd(n,t,e,i){No(n,e),i=this.locInfo(i);var s={type:"Program",body:t,strip:{},loc:i};return{type:"BlockStatement",path:n.path,params:n.params,hash:n.hash,program:s,openStrip:{},inverseStrip:{},closeStrip:{},loc:i}}function Ld(n,t,e,i,s,r){i&&i.path&&No(n,i);var o=/\*/.test(n.open);t.blockParams=n.blockParams;var a=void 0,l=void 0;if(e){if(o)throw new Ro.default("Unexpected inverse block on decorator",e);e.chain&&(e.program.body[0].closeStrip=i.strip),l=e.strip,a=e.program}return s&&(s=a,a=t,t=s),{type:o?"DecoratorBlock":"BlockStatement",path:n.path,params:n.params,hash:n.hash,program:t,inverse:a,openStrip:n.strip,inverseStrip:l,closeStrip:i&&i.strip,loc:this.locInfo(r)}}function Td(n,t){if(!t&&n.length){var e=n[0].loc,i=n[n.length-1].loc;e&&i&&(t={source:e.source,start:{line:e.start.line,column:e.start.column},end:{line:i.end.line,column:i.end.column}})}return{type:"Program",body:n,strip:{},loc:t}}function Cd(n,t,e,i){return No(n,e),{type:"PartialBlockStatement",name:n.path,params:n.params,hash:n.hash,program:t,openStrip:n.strip,closeStrip:e&&e.strip,loc:this.locInfo(i)}}an.__esModule=!0;an.parseWithoutProcessing=ml;an.parse=Fd;function Rd(n){if(n&&n.__esModule)return n;var t={};if(n!=null)for(var e in n)Object.prototype.hasOwnProperty.call(n,e)&&(t[e]=n[e]);return t.default=n,t}function pl(n){return n&&n.__esModule?n:{default:n}}var Nd=Hr.exports,Yr=pl(Nd),Ad=Xr.exports,Id=pl(Ad),kd=ri,Bd=Rd(kd),Dd=ne;an.parser=Yr.default;var Ln={};Dd.extend(Ln,Bd);function ml(n,t){if(n.type==="Program")return n;Yr.default.yy=Ln,Ln.locInfo=function(i){return new Ln.SourceLocation(t&&t.srcName,i)};var e=Yr.default.parse(n);return e}function Fd(n,t){var e=ml(n,t),i=new Id.default(t);return i.accept(e)}var ln={};ln.__esModule=!0;ln.Compiler=jr;ln.precompile=Wd;ln.compile=Ud;function gl(n){return n&&n.__esModule?n:{default:n}}var Od=je.exports,Xs=gl(Od),Js=ne,Vd=Hn.exports,Ds=gl(Vd),Gd=[].slice;function jr(){}jr.prototype={compiler:jr,equals:function(t){var e=this.opcodes.length;if(t.opcodes.length!==e)return!1;for(var i=0;i1)throw new Xs.default("Unsupported number of partial arguments: "+i.length,t);i.length||(this.options.explicitPartialContext?this.opcode("pushLiteral","undefined"):i.push({type:"PathExpression",parts:[],depth:0}));var s=t.name.original,r=t.name.type==="SubExpression";r&&this.accept(t.name),this.setupFullMustacheParams(t,e,void 0,!0);var o=t.indent||"";this.options.preventIndent&&o&&(this.opcode("appendContent",o),o=""),this.opcode("invokePartial",r,s,o),this.opcode("append")},PartialBlockStatement:function(t){this.PartialStatement(t)},MustacheStatement:function(t){this.SubExpression(t),t.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},Decorator:function(t){this.DecoratorBlock(t)},ContentStatement:function(t){t.value&&this.opcode("appendContent",t.value)},CommentStatement:function(){},SubExpression:function(t){Sa(t);var e=this.classifySexpr(t);e==="simple"?this.simpleSexpr(t):e==="helper"?this.helperSexpr(t):this.ambiguousSexpr(t)},ambiguousSexpr:function(t,e,i){var s=t.path,r=s.parts[0],o=e!=null||i!=null;this.opcode("getContext",s.depth),this.opcode("pushProgram",e),this.opcode("pushProgram",i),s.strict=!0,this.accept(s),this.opcode("invokeAmbiguous",r,o)},simpleSexpr:function(t){var e=t.path;e.strict=!0,this.accept(e),this.opcode("resolvePossibleLambda")},helperSexpr:function(t,e,i){var s=this.setupFullMustacheParams(t,e,i),r=t.path,o=r.parts[0];if(this.options.knownHelpers[o])this.opcode("invokeKnownHelper",s.length,o);else{if(this.options.knownHelpersOnly)throw new Xs.default("You specified knownHelpersOnly, but used the unknown helper "+o,t);r.strict=!0,r.falsy=!0,this.accept(r),this.opcode("invokeHelper",s.length,r.original,Ds.default.helpers.simpleId(r))}},PathExpression:function(t){this.addDepth(t.depth),this.opcode("getContext",t.depth);var e=t.parts[0],i=Ds.default.helpers.scopedId(t),s=!t.depth&&!i&&this.blockParamIndex(e);s?this.opcode("lookupBlockParam",s,t.parts):e?t.data?(this.options.data=!0,this.opcode("lookupData",t.depth,t.parts,t.strict)):this.opcode("lookupOnContext",t.parts,t.falsy,t.strict,i):this.opcode("pushContext")},StringLiteral:function(t){this.opcode("pushString",t.value)},NumberLiteral:function(t){this.opcode("pushLiteral",t.value)},BooleanLiteral:function(t){this.opcode("pushLiteral",t.value)},UndefinedLiteral:function(){this.opcode("pushLiteral","undefined")},NullLiteral:function(){this.opcode("pushLiteral","null")},Hash:function(t){var e=t.pairs,i=0,s=e.length;for(this.opcode("pushHash");i=0)return[e,r]}}};function Wd(n,t,e){if(n==null||typeof n!="string"&&n.type!=="Program")throw new Xs.default("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+n);t=t||{},"data"in t||(t.data=!0),t.compat&&(t.useDepths=!0);var i=e.parse(n,t),s=new e.Compiler().compile(i,t);return new e.JavaScriptCompiler().compile(s,t)}function Ud(n,t,e){if(t===void 0&&(t={}),n==null||typeof n!="string"&&n.type!=="Program")throw new Xs.default("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+n);t=Js.extend({},t),"data"in t||(t.data=!0),t.compat&&(t.useDepths=!0);var i=void 0;function s(){var o=e.parse(n,t),a=new e.Compiler().compile(o,t),l=new e.JavaScriptCompiler().compile(a,t,void 0,!0);return e.template(l)}function r(o,a){return i||(i=s()),i.call(this,o,a)}return r._setup=function(o){return i||(i=s()),i._setup(o)},r._child=function(o,a,l,h){return i||(i=s()),i._child(o,a,l,h)},r}function bl(n,t){if(n===t)return!0;if(Js.isArray(n)&&Js.isArray(t)&&n.length===t.length){for(var e=0;e0&&(g+=", "+m.join(", "));var S=0;Object.keys(this.aliases).forEach(function(x){var w=p.aliases[x];w.children&&w.referenceCount>1&&(g+=", alias"+ ++S+"="+x,w.children[0]="alias"+S)}),this.lookupPropertyFunctionIsUsed&&(g+=", "+this.lookupPropertyFunctionVarDeclaration());var b=["container","depth0","helpers","partials","data"];(this.useBlockParams||this.useDepths)&&b.push("blockParams"),this.useDepths&&b.push("depths");var y=this.mergeSource(g);return d?(b.push(y),Function.apply(this,b)):this.source.wrap(["function(",b.join(","),`) { `,y,"}"])},mergeSource:function(d){var p=this.environment.isSimple,g=!this.forceBuffer,m=void 0,S=void 0,b=void 0,y=void 0;return this.source.each(function(x){x.appendToBuffer?(b?x.prepend(" + "):b=x,y=x):(b&&(S?b.prepend("buffer += "):m=!0,y.add(";"),b=y=void 0),S=!0,p||(g=!1))}),g?b?(b.prepend("return "),y.add(";")):S||this.source.push('return "";'):(d+=", buffer = "+(m?"":this.initializeBuffer()),b?(b.prepend("return buffer + "),y.add(";")):this.source.push("return buffer;")),d&&this.source.prepend("var "+d.substring(2)+(m?"":`; `)),this.source.merge()},lookupPropertyFunctionVarDeclaration:function(){return` lookupProperty = container.lookupProperty || function(parent, propertyName) { if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { return parent[propertyName]; } return undefined } `.trim()},blockValue:function(d){var p=this.aliasable("container.hooks.blockHelperMissing"),g=[this.contextName(0)];this.setupHelperArgs(d,0,g);var m=this.popStack();g.splice(1,0,m),this.push(this.source.functionCall(p,"call",g))},ambiguousBlockValue:function(){var d=this.aliasable("container.hooks.blockHelperMissing"),p=[this.contextName(0)];this.setupHelperArgs("",0,p,!0),this.flushInline();var g=this.topStack();p.splice(1,0,g),this.pushSource(["if (!",this.lastHelper,") { ",g," = ",this.source.functionCall(d,"call",p),"}"])},appendContent:function(d){this.pendingContent?d=this.pendingContent+d:this.pendingLocation=this.source.currentLocation,this.pendingContent=d},append:function(){if(this.isInline())this.replaceStack(function(p){return[" != null ? ",p,' : ""']}),this.pushSource(this.appendToBuffer(this.popStack()));else{var d=this.popStack();this.pushSource(["if (",d," != null) { ",this.appendToBuffer(d,void 0,!0)," }"]),this.environment.isSimple&&this.pushSource(["else { ",this.appendToBuffer("''",void 0,!0)," }"])}},appendEscaped:function(){this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"),"(",this.popStack(),")"]))},getContext:function(d){this.lastContext=d},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(d,p,g,m){var S=0;!m&&this.options.compat&&!this.lastContext?this.push(this.depthedLookup(d[S++])):this.pushContext(),this.resolvePath("context",d,S,p,g)},lookupBlockParam:function(d,p){this.useBlockParams=!0,this.push(["blockParams[",d[0],"][",d[1],"]"]),this.resolvePath("context",p,1)},lookupData:function(d,p,g){d?this.pushStackLiteral("container.data(data, "+d+")"):this.pushStackLiteral("data"),this.resolvePath("data",p,0,!0,g)},resolvePath:function(d,p,g,m,S){var b=this;if(this.options.strict||this.options.assumeObjects){this.push(u(this.options.strict&&S,this,p,d));return}for(var y=p.length;gthis.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var d=this.inlineStack;this.inlineStack=[];for(var p=0,g=d.length;pn!==null&&n.isSecureContext,Hd=n=>n===null?null:n.hasOwnProperty("AudioBuffer")?n.AudioBuffer:null,Xd=n=>n===null?null:n.hasOwnProperty("AudioContext")?n.AudioContext:n.hasOwnProperty("webkitAudioContext")?n.webkitAudioContext:null,Yd=n=>n===null?null:n.hasOwnProperty("AudioWorkletNode")?n.AudioWorkletNode:null,jd=n=>n===null?null:n.hasOwnProperty("OfflineAudioContext")?n.OfflineAudioContext:n.hasOwnProperty("webkitOfflineAudioContext")?n.webkitOfflineAudioContext:null,Kd=()=>typeof window=="undefined"?null:window,hn=Kd();jd(hn);Xd(hn);Yd(hn);Hd(hn);zd(hn);var qd={exports:{}},Sl={exports:{}};function Jd(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}function Zd(n,t){for(var e=n.replace(/[^A-Za-z0-9\+\/]/g,""),i=e.length,s=t?Math.ceil((i*3+1>>2)/t)*t:i*3+1>>2,r=new Uint8Array(s),o,a,l=0,h=0,c=0;c>>(16>>>o&24)&255;l=0}return r}var Qd={decode:Zd},$d=function(n,t){return new Promise(function(e,i){var s=new XMLHttpRequest;t&&(s.responseType=t),s.open("GET",n),s.onload=function(){s.status===200?e(s.response):i(Error(s.statusText))},s.onerror=function(){i(Error("Network Error"))},s.send()})};(function(n){var t=Qd,e=$d;function i(E){return function(C){return typeof C=="string"&&E.test(C)}}function s(E,C){return typeof E=="string"?E+C:typeof E=="function"?E(C):C}function r(E,C,P,I){var F=o(C)?a:l(C)?h:c(C)?u:f(C)?d:p(C)?g:m(C)?S:b(C)?y:x(C)?w:null,L=P||{};return F?F(E,C,L):I?Promise.resolve(I):Promise.reject("Source not valid ("+C+")")}r.fetch=e;function o(E){return E instanceof ArrayBuffer}function a(E,C,P){return new Promise(function(I,F){E.decodeAudioData(C,function(L){I(L)},function(){F("Can't decode audio data ("+C.slice(0,30)+"...)")})})}var l=i(/\.(mp3|wav|ogg)(\?.*)?$/i);function h(E,C,P){var I=s(P.from,C);return r(E,r.fetch(I,"arraybuffer"),P)}function c(E){return E&&typeof E.then=="function"}function u(E,C,P){return C.then(function(I){return r(E,I,P)})}var f=Array.isArray;function d(E,C,P){return Promise.all(C.map(function(I){return r(E,I,P,I)}))}function p(E){return E&&typeof E=="object"}function g(E,C,P){var I={},F=Object.keys(C).map(function(L){if(P.only&&P.only.indexOf(L)===-1)return null;var k=C[L];return r(E,k,P,k).then(function(v){I[L]=v})});return Promise.all(F).then(function(){return I})}var m=i(/\.json(\?.*)?$/i);function S(E,C,P){var I=s(P.from,C);return r(E,r.fetch(I,"text").then(JSON.parse),P)}var b=i(/^data:audio/);function y(E,C,P){var I=C.indexOf(",");return r(E,t.decode(C.slice(I+1)).buffer,P)}var x=i(/\.js(\?.*)?$/i);function w(E,C,P){var I=s(P.from,C);return r(E,r.fetch(I,"text").then(T),P)}function T(E){var C=E.indexOf("MIDI.Soundfont.");if(C<0)throw Error("Invalid MIDI.js Soundfont format");C=E.indexOf("=",C)+2;var P=E.lastIndexOf(",");return JSON.parse(E.slice(C,P)+"}")}n.exports&&(n.exports=r),typeof window!="undefined"&&(window.loadAudio=r)})(Sl);var yl={exports:{}},t1=e1;function e1(n){var t=n.createGain(),e=t._voltage=n1(n),i=hs(e),s=hs(e),r=hs(e);return t._startAmount=hs(s),t._endAmount=hs(r),t._multiplier=hs(i),t._multiplier.connect(t),t._startAmount.connect(t),t._endAmount.connect(t),t.value=i.gain,t.startValue=s.gain,t.endValue=r.gain,t.startValue.value=0,t.endValue.value=0,Object.defineProperties(t,i1),t}var i1={attack:{value:0,writable:!0},decay:{value:0,writable:!0},sustain:{value:1,writable:!0},release:{value:0,writable:!0},getReleaseDuration:{value:function(){return this.release}},start:{value:function(n){var t=this._multiplier.gain,e=this._startAmount.gain,i=this._endAmount.gain;this._voltage.start(n),this._decayFrom=this._decayFrom=n+this.attack,this._startedAt=n;var s=this.sustain;t.cancelScheduledValues(n),e.cancelScheduledValues(n),i.cancelScheduledValues(n),i.setValueAtTime(0,n),this.attack?(t.setValueAtTime(0,n),t.linearRampToValueAtTime(1,n+this.attack),e.setValueAtTime(1,n),e.linearRampToValueAtTime(0,n+this.attack)):(t.setValueAtTime(1,n),e.setValueAtTime(0,n)),this.decay&&t.setTargetAtTime(s,this._decayFrom,ya(this.decay))}},stop:{value:function(n,t){t&&(n=n-this.release);var e=n+this.release;if(this.release){var i=this._multiplier.gain,s=this._startAmount.gain,r=this._endAmount.gain;i.cancelScheduledValues(n),s.cancelScheduledValues(n),r.cancelScheduledValues(n);var o=ya(this.release);if(this.attack&&n=t&&(h=t),h}var o1=t1,a1={},l1={gain:1,attack:.01,decay:.1,sustain:.9,release:.3,loop:!1,cents:0,loopStart:0,loopEnd:0};function h1(n,t,e){var i=!1,s=0,r={},o=n.createGain();o.gain.value=1;var a=Object.assign({},l1,e),l={context:n,out:o,opts:a};return t instanceof AudioBuffer?l.buffer=t:l.buffers=t,l.start=function(u,f,d){if(l.buffer&&u!==null)return l.start(null,u,f);var p=u?l.buffers[u]:l.buffer;if(p){if(!i){console.warn("SamplePlayer not connected to any node.");return}}else{console.warn("Buffer "+u+" not found.");return}var g=d||a1;f=Math.max(n.currentTime,f||0),l.emit("start",f,u,g);var m=c(u,p,g);return m.id=h(u,m),m.env.start(f),m.source.start(f),l.emit("started",f,m.id,m),g.duration&&m.stop(f+g.duration),m},l.play=function(u,f,d){return l.start(u,f,d)},l.stop=function(u,f){var d;return f=f||Object.keys(r),f.map(function(p){return d=r[p],d?(d.stop(u),d.id):null})},l.connect=function(u){return i=!0,o.connect(u),l},l.emit=function(u,f,d,p){l.onevent&&l.onevent(u,f,d,p);var g=l["on"+u];g&&g(f,d,p)},l;function h(u,f){return f.id=s++,r[f.id]=f,f.source.onended=function(){var d=n.currentTime;f.source.disconnect(),f.env.disconnect(),f.disconnect(),l.emit("ended",d,f.id,f)},f.id}function c(u,f,d){var p=n.createGain();return p.gain.value=0,p.connect(o),p.env=u1(n,d,a),p.env.connect(p.gain),p.source=n.createBufferSource(),p.source.buffer=f,p.source.connect(p),p.source.loop=d.loop||a.loop,p.source.playbackRate.value=f1(d.cents||a.cents),p.source.loopStart=d.loopStart||a.loopStart,p.source.loopEnd=d.loopEnd||a.loopEnd,p.stop=function(g){var m=g||n.currentTime;l.emit("stop",m,u);var S=p.env.stop(m);p.source.stop(S)},p}}function xa(n){return typeof n=="number"}var c1=["attack","decay","sustain","release"];function u1(n,t,e){var i=o1(n),s=t.adsr||e.adsr;return c1.forEach(function(r,o){s?i[r]=s[o]:i[r]=t[r]||e[r]}),i.value.value=xa(t.gain)?t.gain:xa(e.gain)?e.gain:1,i}function f1(n){return n?Math.pow(2,n/1200):1}var d1=h1,p1=function(n){return n.on=function(t,e){if(arguments.length===1&&typeof t=="function")return n.on("event",t);var i="on"+t,s=n[i];return n[i]=s?m1(s,e):e,n},n};function m1(n,t){return function(e,i,s,r){n(e,i,s,r),t(e,i,s,r)}}var xl=/^([a-gA-G])(#{1,}|b{1,}|x{1,}|)(-?\d*)\s*(.*)\s*$/;function g1(){return xl}var b1=[0,2,4,5,7,9,11];function vl(n,t,e){if(typeof n!="string")return null;var i=xl.exec(n);if(!i||!t&&i[4])return null;var s={letter:i[1].toUpperCase(),acc:i[2].replace(/x/g,"##")};return s.pc=s.letter+s.acc,s.step=(s.letter.charCodeAt(0)+3)%7,s.alt=s.acc[0]==="b"?-s.acc.length:s.acc.length,s.chroma=b1[s.step]+s.alt,i[3]&&(s.oct=+i[3],s.midi=s.chroma+12*(s.oct+1),s.freq=_l(s.midi,e)),t&&(s.tonicOf=i[4]),s}function _l(n,t){return Math.pow(2,(n-69)/12)*(t||440)}var wl={parse:vl,regex:g1,midiToFreq:_l},S1=["letter","acc","pc","step","alt","chroma","oct","midi","freq"];S1.forEach(function(n){wl[n]=function(t){var e=vl(t);return e&&typeof e[n]!="undefined"?e[n]:null}});var y1=wl,x1=y1,v1=function(n){return n!==null&&n!==[]&&n>=0&&n<129},_1=function(n){return v1(n)?+n:x1.midi(n)},w1=function(n){if(n.buffers){var t=n.opts.map,e=typeof t=="function"?t:_1,i=function(r){return r?e(r)||r:null};n.buffers=E1(n.buffers,i);var s=n.start;n.start=function(r,o,a){var l=i(r),h=l%1;return h&&(l=Math.floor(l),a=Object.assign(a||{},{cents:Math.floor(h*100)})),s(l,o,a)}}return n};function E1(n,t){return Object.keys(n).reduce(function(e,i){return e[t(i)]=n[i],e},{})}var M1=Array.isArray,P1=function(n){return n&&typeof n=="object"},L1={},T1=function(n){return n.schedule=function(t,e){var i=n.context.currentTime,s=t6?null:B1.charAt(n)+D1(t)+F1(e)}function Tl(n){if((Ao(n)||N1(n))&&n>=0&&n<128)return+n;var t=ki(n);return t&&A1(t.midi)?t.midi:null}function O1(n,t){var e=Tl(n);return e===null?null:Ml(e,t)}function V1(n){return(ki(n)||{}).letter}function G1(n){return(ki(n)||{}).acc}function W1(n){return(ki(n)||{}).pc}function U1(n){return(ki(n)||{}).step}function z1(n){return(ki(n)||{}).alt}function H1(n){return(ki(n)||{}).chroma}function X1(n){return(ki(n)||{}).oct}var Y1=Object.freeze(Object.defineProperty({__proto__:null,regex:I1,parse:ki,build:Ll,midi:Tl,freq:O1,letter:V1,acc:G1,pc:W1,step:U1,alt:z1,chroma:H1,oct:X1},Symbol.toStringTag,{value:"Module"})),j1=Fl(Y1),Jr=j1;function Si(n,t){if(console.warn("new Soundfont() is deprected"),console.log("Please use Soundfont.instrument() instead of new Soundfont().instrument()"),!(this instanceof Si))return new Si(n);this.nameToUrl=t||Si.nameToUrl,this.ctx=n,this.instruments={},this.promises=[]}Si.prototype.onready=function(n){console.warn("deprecated API"),console.log("Please use Promise.all(Soundfont.instrument(), Soundfont.instrument()).then() instead of new Soundfont().onready()"),Promise.all(this.promises).then(n)};Si.prototype.instrument=function(n,t){console.warn("new Soundfont().instrument() is deprecated."),console.log("Please use Soundfont.instrument() instead.");var e=this.ctx;if(n=n||"default",n in this.instruments)return this.instruments[n];var i={name:n,play:q1(e,t)};if(this.instruments[n]=i,n!=="default"){var s=Si.instrument(e,n,t).then(function(r){return i.play=r.play,i});this.promises.push(s),i.onready=function(r){console.warn("onready is deprecated. Use Soundfont.instrument().then()"),s.then(r)}}else i.onready=function(r){console.warn("onready is deprecated. Use Soundfont.instrument().then()"),r()};return i};function K1(n,t,e){return console.warn("Soundfont.loadBuffers is deprecate."),console.log("Use Soundfont.instrument(..) and get buffers properties from the result."),Si.instrument(n,t,e).then(function(i){return i.buffers})}Si.loadBuffers=K1;function q1(n,t){return t=t||{},function(e,i,s,r){console.warn("The oscillator player is deprecated."),console.log("Starting with version 0.9.0 you will have to wait until the soundfont is loaded to play sounds.");var o=e>0&&e<129?+e:Jr.midi(e),a=o?Jr.midiToFreq(o,440):null;if(!!a){s=s||.2,r=r||{};var l=r.destination||t.destination||n.destination,h=r.vcoType||t.vcoType||"sine",c=r.gain||t.gain||.4,u=n.createOscillator();u.type=h,u.frequency.value=a;var f=n.createGain();return f.gain.value=c,u.connect(f),f.connect(l),u.start(i),s>0&&u.stop(i+s),u}}}Si.noteToMidi=Jr.midi;var J1=Si;(function(n){var t=Sl.exports,e=yl.exports;function i(a,l,h){if(arguments.length===1)return function(p,g){return i(a,p,g)};var c=h||{},u=c.isSoundfontURL||s,f=c.nameToUrl||r,d=u(l)?l:f(l,c.soundfont,c.format);return t(a,d,{only:c.only||c.notes}).then(function(p){var g=e(a,p,c).connect(c.destination?c.destination:a.destination);return g.url=d,g.name=l,g})}function s(a){return/\.js(\?.*)?$/i.test(a)}function r(a,l,h){return h=h==="ogg"?h:"mp3",l=l==="FluidR3_GM"?l:"MusyngKite","https://gleitz.github.io/midi-js-soundfonts/"+l+"/"+a+"-"+h+".js"}var o=J1;o.instrument=i,o.nameToUrl=r,n.exports&&(n.exports=o),typeof window!="undefined"&&(window.Soundfont=o)})(qd);ut.C,ut.D,ut.E,ut.F,ut.G,ut.A,ut.B;export{Ui as E,W as F,$1 as G,hf as O,Ce as P,Ue as S,M as V,ps as a,tp as b,Ha as i};