\n'; output += '\n'; // var blob = new Blob([output], {type: 'text/plain;charset=utf-8'}); var blob = new Blob([output], {type: 'text/plain'}); saveAs(blob, filename); } ////////////////////////////// // // loadBuffer -- load the text contents from a local buffer, but if the // shift key is pressed, delete the current contents of the buffer instead. // function loadBuffer(number, event) { if (number < 1 || number > 9) { return; } if (event && event.shiftKey) { // clear contents of given buffer. var key = "SAVE" + number; delete localStorage[key]; var title = key + "-TITLE"; delete localStorage[title]; var selement = document.querySelector("#save-" + number); if (selement) { selement.classList.remove("filled"); } var lelement = document.querySelector("#load-" + number); if (lelement) { lelement.classList.remove("filled"); } } else { // store contents of text editor in given buffer. MENU.loadFromBuffer(number); } } ////////////////////////////// // // prepareBufferStates -- // function prepareBufferStates() { var saves = document.querySelectorAll("[id^=save-]"); var loads = document.querySelectorAll("[id^=load-]"); var i; var id; var num = 0; var value; var matches; var skey; var lkey; var tkey; for (i=0; i 9) { return; } if (event && event.shiftKey) { // clear contents of given buffer. var key = "SAVE" + number; delete localStorage[key]; var title = key + "-TITLE"; delete localStorage[title]; var selement = document.querySelector("#save-" + number); if (selement) { selement.classList.remove("filled"); } var lelement = document.querySelector("#load-" + number); if (lelement) { lelement.classList.remove("filled"); } } else { // store contents of text editor in given buffer. MENU.saveToBuffer(number); } } ////////////////////////////// // // saveEditorContentsLocally -- Save the editor contents to localStorage. // function saveEditorContentsLocally() { var target = InterfaceSingleNumber; if (!target) { target = 1; } key = "SAVE" + target; var value = getTextFromEditorRaw(); var filled = false; var encodedcontents = ""; if (value.match(/^\s*$/)) { encodedcontents = ""; filled = false; } else { encodedcontents = encodeURIComponent(value); filled = true; } localStorage.setItem(key, encodedcontents); var telement = document.querySelector("#title-info"); var title = ""; if (telement) { title = telement.textContent.replace(/^\s+/, "").replace(/\s+$/, ""); } localStorage.setItem(key + "-TITLE", title); var selement = document.querySelector("#save-" + target); if (selement) { selement.title = title; if (filled) { selement.classList.add("filled"); } else { selement.classList.remove("filled"); } } var lelement = document.querySelector("#load-" + target); if (lelement) { lelement.title = title; if (filled) { lelement.classList.add("filled"); } else { lelement.classList.remove("filled"); } } InterfaceSingleNumber = 0; } ////////////////////////////// // // saveSvgData -- // function saveSvgData() { if (ShowingIndex) { return; } var options = JSON.parse(JSON.stringify(OPTIONS)); console.log("SVG PRINTING OPTIONS", options); var data = getTextFromEditor(); if (data.match(/^\s*$/)) { return; }; var humdrum = dataIsHumdrum(data); if (humdrum && GLOBALFILTER) { if (data.charAt[data.length-1] !== "\n") { data += "\n"; } data += "!!!filter: " + GLOBALFILTER + "\n"; } var page = vrvWorker.page; var force = true; // vrvWorker.renderPage(vrvWorker.page) vrvWorker.renderData(options, data, page, force) .then(function(data) { var filename = SAVEFILENAME; var size = EDITOR.session.getLength(); var matches; var line; for (var i=0; i=0; i--) { if (ftext.charAt(i) === "|") { pstart = i+1; break; } } let text = ftext; if (pstart >= 0) { text = text.substring(pstart); } text = text.replace(/\|.*/, ""); return text; } ////////////////////////////// // // hideFilterLinkIcon -- Make sure that the filter link icon is hidden. // function hideFilterLinkIcon() { var element = document.querySelector("#filter-link"); if (element) { element.style.display = "none"; } // also deactivate the filter in the toolbar detachGlobalFilter(); } ////////////////////////////// // // loadFilter -- // function loadFilter(element) { let filterElement = document.querySelector("#filter"); if (!filterElement) { return; } let filterText = filterElement.value || ""; if (filterText) { filterText = encodeURIComponent(filterText); } let elementFilter = element.dataset.filter; if (elementFilter === filterText) { // Filter is currently active with matching filter, so disable it: filterElement.value = ""; applyGlobalFilter(); } else { let filter = decodeURIComponent(elementFilter); if (filter) { filterElement.value = filter; } applyGlobalFilter(true); } } ////////////////////////////// // // removeStrings -- Used to remove option strings for filter commands // so that pipe characters in strings are not confused with // pipe special characters. // function removeStrings(input) { let output = ""; let singleQuote = 0; let doubleQuote = 0; let lastchar = ""; let currchar = ""; for (let i=0; i=0; i--) { let matches = humdrum[i].match(regex); if (matches) { info.iiifbase = matches[1]; callback(event, info); return; } } getIiifManifestInfo(info, event, callback); } function getIiifBoundingBoxInfo(path) { // search for a token in the form: // *xywh-label:#,#,#,# // Then search for a single IIIF image with the given label, // or a IIIF manifest which should contain the label information. let line = -1; let field = -1; for (let i=0; i=0; i--) { matches = lines[i].match(/^!!xywh-([^:]+):(.*)$/); if (matches) { output.label = matches[1]; output.xywh = matches[2]; break; } if (!lines[i].match(/^\*/)) { continue; } let ismanipulator = isManipulator(lines[i]); if (ismanipulator) { cfield = getNewFieldIndex(cfield, lines[i]); } let fields = lines[i].split(/\t+/); matches = fields[cfield].match(/^\*xywh-([^:]+):(.*)$/); if (matches) { output.label = matches[1]; output.xywh = matches[2]; break; } matches = fields[cfield].match(/^\*xywh:(.*)$/); if (matches) { output.xywh = matches[1]; } matches = fields[cfield].match(/^\*iiif:([^:]+)/); if (matches) { output.label = matches[1]; break; } } if (output.label === "") { return null; } return output; } var DATA = "XXX"; function getIiifManifestInfo(info, event, callback) { console.warn("GETIIIFMANIFEST INFO", info); let humdrum = info.humdrum; if (!humdrum) { console.error("NO HUMDRUM DATA IN", info); return; } if (!info.label) { console.error("NO IMAGE LABEL IN", info); return; } let label = info.label; let skey = `^!!!IIIF:\\s*([^\\s]+)`; let regex = new RegExp(skey); for (let i=humdrum.length - 1; i>=0; i--) { let matches = humdrum[i].match(regex); if (matches) { let manifest = matches[1]; let mobj = IIIF_MANIFEST[manifest]; if (mobj) { info.manifest = mobj; let imi = mobj.images; for (let j=0; j results.json()) .then(data => { let items = data.items; let version = 3; if (!items) { // Assume IIIF version 2 (better check can be done). version = 2; items = data.sequences[0].canvases; } let maninfo = {}; maninfo.images = []; maninfo.manifest = manifest; for (let i=0; i 0) { label = lobj[keys[0]][0]; } } if (!label) { label = items[i].label; } if (label) { entry.label = label; } if (label === info.label) { info.iiifbase = entry.iiifbase; } maninfo.images.push(entry); } info.manifest = maninfo; if (!info.iiifbase) { // 0-indexed image number: let matches = info.label.match(/^#z(\d+)/); if (matches) { info.iiifbase = info.manifest.images[parseInt(matches[1])].iiifbase; } // 1-indexed image number: matches = info.label.match(/^#(\d+)/); if (matches) { info.iiifbase = info.manifest.images[parseInt(matches[1]) - 1].iiifbase; } } IIIF_MANIFEST[manifest] = maninfo; callback(event, info); }) .catch(error => { console.error(error); }); break; } } } function iiifCallback(event, info) { if (!info.iiifbase) { console.error("NO IIIF URL BASE IN", info); return; } if (!info.xywh) { console.error("NO XYWH PARAMETER IN", info); return; } if (info.xywh === "0,0,0,0") { console.error("EMPTY XYWH PARAMETER IN", info); return; } let iiifbase = info.iiifbase; let xywh = info.xywh; let options = "popup=yes"; let scale = window.devicePixelRatio; if (!scale) { scale = 1; } let scwidth = parseInt(window.screen.width); let scheight = parseInt(window.screen.height); if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) { // display full page let infourl = `${iiifbase}/info.json`; let url = `${iiifbase}/full/,${scheight}/0/default.jpg`; options += `,top=0`; options += `,left=0`; options += `,height=${scheight}`; fetch(infourl) .then(res => res.json()) .then(data => { let imgwidth = data.width; let imgheight = data.height; // console.warn("IW", imgwidth, "IH", imgheight); let aspect = imgwidth / imgheight; let newwidth = scheight * aspect; options += `,width=${newwidth}`; window.open(url, "_blank", options); }) .catch(err => { window.open(url, "_blank", options); }); event.preventDefault(); } else { // display only system image. The system is displayed // at the bottom of the screen, centered if the image does // not go all of the way across the screen. let heightprop = 4; // max 1/4 of window height for image let url = `${iiifbase}/${xywh}/full/0/default.jpg`; let matches = xywh.match(/(\d+),(\d+),(\d+),(\d+)/); let width = 0; let height = 0 if (matches) { width = matches[3]; height = matches[4]; } let aspect = width / height; let maxheight = parseInt(scheight / heightprop); let maxwidth = scwidth; width = width > maxwidth ? maxwidth : width; height = height > maxheight ? maxheight : height; let newaspect = width / height; if (newaspect > aspect) { width = parseInt(height * aspect); } else if (newaspect < aspect) { height = parseInt(width / aspect); } let sctop = scheight - height; let scleft = parseInt((scwidth - width)/2); options += `,width=${width}`; options += `,height=${height}`; options += `,top=${sctop}`; options += `,left=${scleft}`; window.open(url, "_blank", options); } } function processClickForIiif(event) { let path = buildPath(event.target); if (!path) { return; } let boxinfo = getIiifBoundingBoxInfo(path); if (!boxinfo) { return; } if (!boxinfo.xywh) { return; } if (!boxinfo.label) { return; } getIiifBase(boxinfo, event, iiifCallback); } // Functions related to loading files: ////////////////////////////// // // applyUrlAliases -- // // function applyUrlAliases(file) { if (!file) { return file; } var matches; // Github web interface URL: // https://github.com/josquin-research-project/Ock/blob/master/Ock2002-Ave_Maria.krn // Maps to the raw data associated with that page: // https://raw.githubusercontent.com/josquin-research-project/Ock/master/Ock2002-Ave_Maria.krn matches = file.match(/https:\/\/github.com\/([^\/]+)\/([^\/]+)\/blob\/([^\/]+)\/(.*)/); if (matches) { var user = matches[1]; var repertory = matches[2]; var commit = matches[3]; var path = matches[4]; file = "https://raw.githubusercontent.com/" + user + "/" + repertory + "/"; file += commit + "/" + path; } return file; } ////////////////////////////// // // cleanRepertoryEntryText -- // function cleanRepertoryEntryText(text) { text = text.replace(/-sharp/g, "♯").replace(/-flat/g, "♭"); text = text.replace(/.*?<\/not>/g, ""); let matches = text.match(/@\{link:([^}]+)\}/); if (matches) { let link = matches[1]; let replacement = ""; if (link.match(/https?:\/\/.*wikipedia/)) { replacement += ''; replacement += '\n'; replacement += '\n'; replacement += '\n'; replacement += '\n'; replacement += '\n'; text = text.replace(/@\{link:[^}]+\}/, replacement); } } return text; } ////////////////////////////// // // commaDuplicate -- // function commaDuplicate(value) { var pieces = value.split(/\s*,\s*/); var first = pieces[0]; var matches = first.match(/^(.*\/)([^\/]+)/); if (!matches) { return value; } var base = matches[1]; pieces[0] = matches[2]; var output = []; for (var i=0; i= 3) { if (matches = data[1].match(/(.*)HIDE$/)) { // data[1] = matches[1]; data[1] = data[1].replace(/\/.ref/, ""); data[2] = data[2].replace(//g, ""); data[2] = data[2].replace(//g, ""); } newline = data[1] + "\t" + data[0] + "\t" + data[2]; newlines.push(newline); } } newlines.sort(); var items = []; for (i=0; i]*wikipedia[^<]*.*?<\/a>\]?/gi, ""); final += ""; if (items[i].filename.match(/^@/)) { final += "" } else { final += "" } if (indents[items[i].sorter]) { final += ""; } else if (indents[items[i].sorter.replace(/HIDE$/, "")]) { final += ""; } if (items[i].filename.match(/^@/)) { items[i].text.replace(/.*?<\/not>/g, ""); final += items[i].text; var xtext = items[i].filename; xtext = xtext.replace(/^@/, ""); var tindent = xtext.split(/:/); indents = {}; for (var j=0; j"; items[i].text = items[i].text.replace(//, spantext); final += items[i].text; } else if (!items[i].text.match(/hlstart/)) { final += ""; final += items[i].text; final += ""; } else { var spantext = ""; spantext += ""; items[i].text = items[i].text.replace(//, spantext); if (items[i].text.match(//)) { items[i].text = items[i].text.replace(//, ""); } else { items[i].text += ""; } final += items[i].text; } final += "" } final += ""; let cssTop = 30; let buttonCount = 0; // close button (always) let button = ``; buttonCount++; // random button (always) button += ``; buttonCount++; if (options && options.event) { let target = options.event.target; if (target && target.dataset.website) { let website = target.dataset.website; if (!(website && website.match(/^\s*$/))) { button += ``; buttonCount++; } } if (target && target.dataset.github) { let github = target.dataset.github; if (!(github && github.match(/^\s*$/))) { button += ``; buttonCount++; } } } else { if (WEBSITE_LINKS[file]) { button += ``; buttonCount++; } if (GITHUB_LINKS[file]) { button += ``; buttonCount++; } } final = `${button}
${final}
`; var indexelem = document.querySelector("#index"); indexelem.innerHTML = final; indexelem.style.visibility = "visible"; indexelem.style.display = "block"; } ////////////////////////////// // // chooseRandomEntry -- // function chooseRandomEntry() { let table = document.querySelector("table.index-list"); if (!table) { return; } let list = table.querySelectorAll(".ilink"); if (list.length == 0) { return; } let randomNumber = Math.floor(Math.random() * list.length); let text = list[randomNumber].outerHTML; let matches = text.match(/displayWork.['"](.*?)['"]/); if (matches) { let entry = matches[1]; displayWork(entry); } } ////////////////////////////// // // downloadKernScoresFile -- // function downloadKernScoresFile(file, measures, page) { var location; var filename; var matches; var jrp = false; var bitbucket = false; var github = false; var nifc = false; matches = file.match(/^jrp:(.*)/i); if (matches) { jrp = true; file = matches[1]; } else { matches = file.match(/^(?:bitbucket|bb):(.*)/i); if (matches) { bitbucket = true; file = matches[1]; } else { matches = file.match(/^(?:github|gh):(.*)/i); if (matches) { bitbucket = true; file = matches[1]; } else { matches = file.match(/^nifc:(.*)/i); if (matches) { nifc = true; file = matches[1]; } } } } var url; if (jrp) { if (matches = file.match(/(.*)\/([^\/]+)/)) { location = matches[1]; filename = matches[2]; } url = "https://josquin.stanford.edu/data?id=" + location; url += "&a=humdrum"; } else if (nifc) { file = file.replace(/^\/+/, ""); url = "https://humdrum.nifc.pl/krn/" + file; } else { if (matches = file.match(/(.*)\/([^\/]+)/)) { location = matches[1]; filename = matches[2]; } url = "https://kern.humdrum.org/data?l=" + location + "&file=" + filename; if (measures) { url += "&mm=" + measures; } } if (filename) { SAVEFILENAME = filename; console.log("SAVEFILENAME - ", SAVEFILENAME); } if (bitbucket && url.match(/,/)) { downloadMultipleFiles(url); return; } console.log("DATA URL", url); var request = new XMLHttpRequest(); request.open("GET", url); request.addEventListener("load", function() { if (request.status == 200) { // console.log("DATA", request.responseText); //var inputarea = document.querySelector("#input"); //console.log("Current file:", file); //inputarea.value = request.response; // https://ace.c9.io/#nav=api&api=editor replaceEditorContentWithHumdrumFile(request.response, page); if (CGI.k.match(/c/)) { CGI.k = CGI.k.replace(/c/, ""); compileFilters(); } } }); request.send(); } ///////////////////////////// // // downloadMultipleFiles -- Currently assumes to be MuseData. // function downloadMultipleFiles(url) { console.log("DOWNLOADING MULTIPLE FILES", url); } ////////////////////////////// // // getBitbucketUrl -- // // http://verovio.humdrum.org/?file=bitbucket:musedata/beethoven/bhl/qrtet/op18no5/stage2/01/03 // https://bitbucket.org/musedata/beethoven/raw/master/bhl/qrtet/op18no5/stage2/01/03 // function getBitbucketUrl(file, measures) { file = file.replace(/^(bb|bitbucket):/, ""); var username = ""; var repository = ""; var pathandfile = ""; var url = ""; url = "https://bitbucket.org/"; matches = file.match("^\/?([^\/]+)\/([^\/]+)\/(.*)"); if (matches) { username = matches[1]; repository = matches[2]; pathandfile = matches[3]; } url += username; url += "/"; url += repository; url += "/raw/master/"; url += pathandfile; var key = pathandfile; return {url: url, key: key}; } ////////////////////////////// // // getGithubUrl -- // // http://verovio.humdrum.org/?file=github:polyrhythm-project/rds-scores // https://bitbucket.org/musedata/beethoven/raw/master/bhl/qrtet/op18no5/stage2/01/03 // function getGithubUrl(file, measures) { file = file.replace(/^github:\/*/, ""); var username = ""; var repository = ""; var pathandfile = ""; var url = ""; url = "https://raw.githubusercontent.com/"; matches = file.match("^\/*([^\/]+)\/([^\/]+)\/?(.*)"); if (matches) { username = matches[1]; repository = matches[2]; pathandfile = matches[3]; } url += username; url += "/"; url += repository; url += "/master/"; if (!pathandfile) { url += ".ref"; loadIndexFile(url); return; } else { url += pathandfile; } var key = pathandfile; var obj = {url: url, key: key}; return obj; } ////////////////////////////// // // getRequires -- Convert a comma-construct for URL into a list of files to download. // function getRequires(url, key) { var expire = 172; var listing; if (!key.match(/,/)) { listing = [{ url: url, key: key, expire: expire, execute: false }]; return listing; } // Input represents multiple files, such as // https://verovio.humdrum.org?bb=musedata/beethoven/bhl/qrtet/op18no5/stage2/01/03,04 // should expand to two files: // https://verovio.humdrum.org?bb=musedata/beethoven/bhl/qrtet/op18no5/stage2/01/03 // https://verovio.humdrum.org?bb=musedata/beethoven/bhl/qrtet/op18no5/stage2/01/04 var urls = commaDuplicate(url); var keys = commaDuplicate(key); listing = []; for (var i=0; i 10000) { console.log("RECURSION TOO LARGE", file); return; } let url = ""; let key = ""; let ret; if (file.match(/^https?:/)) { url = file; key = file; } else if (file.match(/^bb:/)) { ret = getBitbucketUrl(file, measures); if (ret) { url = ret.url; key = ret.key; } } else if (file.match(/^bitbucket:/)) { ret = getBitbucketUrl(file, measures); if (ret) { url = ret.url; key = ret.key; } } else if (file.match(/^github:/)) { ret = getGithubUrl(file, measures); if (ret) { url = ret.url; key = ret.key; } } else if (file.match(/^gh:/)) { ret = getGithubUrl(file, measures); if (ret) { url = ret.url; key = ret.key; } } else { ret = kernScoresUrl(file, measures, options); if (ret) { url = ret.url; key = ret.url; } } if (!key) { key = "DATA"; // return; } let requires = getRequires(url, key); let keys = commaDuplicate(key); if (force) { for (let i=0; i 1) { for (j=0; j 1) { // console.log("GOING TO ADD MULTIPLE FILES TO EDITOR", infos); } else if (infos.length == 1) { /* info = basketSession.get(key); console.log("INFO = ", info); if (info) { try { jinfo = JSON.parse(info.data); if (force) { try { let textdata = atob(jinfo.content); } catch (err) { // text is not MIME encoding. } if (textdata.match(/^\s*$/)) { textdata = "!!!ONB: No data content\n"; } try { displayScoreTextInEditor(atob(jinfo.content), vrvWorker.page); } catch (err) { displayScoreTextInEditor(jinfo.content, vrvWorker.page); } } if (getnext) { processInfo(jinfo, options, false, false); } } catch(err) { console.log("Error downloading", key, "Error:", err); displayScoreTextInEditor(info.data, vrvWorker.page); if (CGI.k.match(/c/)) { CGI.k = CGI.k.replace(/c/, ""); compileFilters(); } } } else { console.log("Error retrieving", key); } redrawInputArea(); */ } }, function() { console.log("Error retrieving", key); }); } else if (!info) { console.log("Going to download2 KEY=", key, "URL=", url); basketSession.require( { url: url, key: key, expire: expire, execute: false } ).then(function() { info = basketSession.get(key); if (info) { if (info.url.match(/\/index.hmd$/)) { HMDINDEX = new HMDIndex(info.data); HMDINDEX.parameters.githubbase = file; displayHmdIndexFinally(HMDINDEX, url, options); } else { try { jinfo = JSON.parse(info.data); if (force) { // let textdata = atob(jinfo.content); let textdata = Base64.decode(jinfo.content); if (textdata.match(/^\s*$/)) { textdata = "!!!ONB: No data content\n"; } // displayScoreTextInEditor(atob(jinfo.content), vrvWorker.page); displayScoreTextInEditor(Base64.decode(jinfo.content), vrvWorker.page); } if (getnext) { processInfo(jinfo, options, false, false); } } catch(err) { console.log("Error downloading", key, "Error:", err); displayScoreTextInEditor(info.data, vrvWorker.page); if (CGI.k.match(/c/)) { CGI.k = CGI.k.replace(/c/, ""); compileFilters(); } } } } else { console.log("Error1 retrieving", key); } redrawInputArea(); }, function() { console.log("Error2 retrieving", key); }); } else { try { jinfo = JSON.parse(info.data); if (getnext) { processInfo(jinfo, options, false, false); } } catch(err) { displayScoreTextInEditor(info.data, vrvWorker.page); if (CGI.k && CGI.k.match(/c/)) { CGI.k = CGI.k.replace(/c/, ""); compileFilters(); } redrawInputArea(); } } } ////////////////////////////// // // getPolyFile -- return RDS polyrhythm project file based on example number // function getPolyFile(polyid) { let polymap = {}; polymap["R129"] = "R129_Jan-w30p11m124-127.krn"; polymap["R130"] = "R130_Jan-w33p13m63-71.krn"; polymap["R131"] = "R131_Jan-w43p6m1-4.krn"; polymap["R144"] = "R144_Jan-w47p5h4m1-4.krn"; polymap["R161"] = "R161_Deb-w13p34m25-26.krn"; polymap["R180"] = "R180_Deb-w40p21h15m5-7.krn"; polymap["R183"] = "R183_Deb-w16p69h21m7-9.krn"; polymap["R187"] = "R187_Deb-w42p9s3-4.krn"; polymap["R187x"] = "R187x_Deb-w42p9s3-4.krn"; polymap["R198"] = "R198_Sch-w9p42m4-1h40m1-2.krn"; polymap["R215"] = "R215_Sch-w33p85m523-528.krn"; polymap["R218"] = "R218_Sch-w33p200m252-256.krn"; polymap["R222"] = "R222_Sch-w35p20m73-75.krn"; polymap["R237B"] = "R237B_Ive-w31p9hEm2-3.krn"; polymap["R255"] = "R255_Ive-w35p12m19-24.krn"; polymap["R258"] = "R258_Ive-w30p9m55-57.krn"; polymap["R262"] = "R262_Ive-w33b4p26.krn"; polymap["R262x"] = "R262x_Ive-w33b4p26.krn"; polymap["R279"] = "R279_Rav-w15p1m4-5.krn"; polymap["R281"] = "R281_Rav-w21p2m8-9.krn"; polymap["R295"] = "R295_Rav-w23p20h22m1-4.krn"; polymap["R299"] = "R299_Rav-w32p1-2m1-12.krn"; polymap["R308B"] = "R308B_Fal-w6p111h10m1-7.krn"; polymap["R310"] = "R310_Fal-w3p15m1-8.krn"; polymap["R315"] = "R315_Fal-w8p62h67m1-5.krn"; polymap["R319"] = "R319_Fal-w6p178-179h44m1-5.krn"; polymap["R322A"] = "R322A_Bar-w3p70m1-4.krn"; polymap["R324"] = "R324_Bar-w14p6m3-10.krn"; polymap["R322"] = "R332_Bar-w24p53m5-3h21.krn"; polymap["R350"] = "R350_Bar-w30p4m22-30.krn"; polymap["R371"] = "R371_Str-w15p19m2-1h1m1-5.krn"; polymap["R389"] = "R389_Str-w32p8s1-2.krn"; polymap["R392"] = "R392_Str-w33p52-54h74m1-h80m1.krn"; polymap["R396"] = "R396_Str-w47p8m1h8-h10m1.krn"; polymap["R408"] = "R408_Web-w13p1-2m1-12.krn"; polymap["R409"] = "R409_Web-w3p7m46-49.krn"; polymap["R411"] = "R411_Web-w28p4m33-35.krn"; polymap["R415"] = "R415_Web-w28p2-3m11-19.krn"; polymap["R420"] = "R420_Var-w8p23h7m10-14.krn"; polymap["R426"] = "R426_Var-w4p17h1m5-10.krn"; polymap["R428"] = "R428_Var-w1p12-13h5m9-12.krn"; polymap["R432"] = "R432_Var-w4p18-19h2m1-9.krn"; polymap["R441"] = "R441_Ber-w10p81m376-377.krn"; polymap["R443"] = "R443_Ber-w10p321m593-595.krn"; polymap["R453"] = "R453_Ber-w15p362-363m118-121.krn"; polymap["R456B"] = "R456B_Ber-w15p474-475m553-557.krn"; polymap["R485"] = "R485_Mau-w85p12m57-60.krn"; polymap["R488"] = "R488_Mau-w56p9m35-37.krn"; polymap["R492"] = "R492_Mau-w24p19m99-104.krn"; polymap["R525"] = "R525_Mau-w94p35h19m5-8.krn"; polymap["R1534"] = "R534_Mai-w6p2m1-5.krn"; polymap["R534x"] = "R534x_Mai-w6p1-2m1-12.krn"; polymap["R536"] = "R536_Mai-w8p11m32-41.krn"; polymap["R537"] = "R537_Mai-w9p50m1-6.krn"; polymap["R560"] = "R560_Mai-w29p25m10-14.krn"; polymap["R572"] = "R572_Pro-w32p63h48m7.krn"; polymap["R573"] = "R573_Pro-w36p38m293-295.krn"; polymap["R574"] = "R574_Pro-w41p21m74-77.krn"; polymap["R582"] = "R582_Pro-w35p25s1-3.krn"; polymap["R584"] = "R584_Hon-w4p5h6m1-3.krn"; polymap["R588"] = "R588_Hon-w18p7-8m51-66.krn"; polymap["R599"] = "R599_Hon-w38p60h5m8-20.krn"; polymap["R602"] = "R602_Hon-w20p7h3m1-5.krn"; polymap["R616"] = "R616_Hin-w6p9m114-117.krn"; polymap["R630"] = "R630_Hin-w22p74-75hDm4-9.krn"; polymap["R655"] = "R655_Hin-w77p19m154-160.krn"; polymap["R678"] = "R678_Hin-w90p19m143-147.krn"; polymap["R686"] = "R686_Ger-w3p12h9m1-5.krn"; polymap["R686x"] = "R686x_Ger-w3v2p12h9m1-5.krn"; polymap["R687"] = "R687_Ger-w6p24h19m1-3.krn"; polymap["R688"] = "R688_Ger-w3p19h14m1-3.krn"; polymap["R689"] = "R689_Ger-w12p59m29-34.krn"; polymap["R700"] = "R700_Cop-w2p64h38m3-10.krn"; polymap["R701"] = "R701_Cop-w1v2p8m1-h2m2.krn"; polymap["R714"] = "R714_Cop-w32p117-118m110-112.krn"; polymap["R724"] = "R724_Cop-w42p64h66m1-7.krn"; polymap["R730"] = "R730_Mes-w16b1p8m26-27.krn"; polymap["R731"] = "R731_Mes-w16b3p9m24-28.krn"; polymap["R744"] = "R744_Mes-w19p135h2m13-14.krn"; polymap["R770"] = "R770_Mes-w22p273h7m3-6.krn"; polymap["R798"] = "R798_Bri-w42p12m41.krn"; polymap["R799"] = "R799_Bri-w22p62m286-289.krn"; polymap["R809"] = "R809_Bri-w28p5m22-30.krn"; polymap["R812"] = "R812_Bri-w33p39h19m2-13.krn"; polyid += ""; if (!polyid.match(/^R/)) { polyid = "R" + polyid; polyid = polyid.replace(/_.*/, ""); } let file = polymap[polyid]; if (file) { return `poly/${file}`; } else { return `poly`; } } ////////////////////////////// // // processInfo -- // function processInfo(info, obj, nextwork, prevwork) { var score; if (info) { FILEINFO = info; // score = atob(info.content); score = Base64.decode(info.content); // console.log("Score unpacked"); } else { console.log("Impossible error for", infojson); return; } var matches; if (obj && obj.file && (matches = obj.file.match(/([^\/]+)$/))) { SAVEFILENAME = matches[1]; } // var inputarea = document.querySelector("#input"); // inputarea.value = score; displayScoreTextInEditor(score, vrvWorker.page); obj.next = false; obj.previous = false; if (!obj) { return; } if (info["next-work"]) { obj.file = info["next-work"]; loadKernScoresFile(obj) } if (info["previous-work"]) { obj.file = info["previous-work"]; loadKernScoresFile(obj) } } // Functions related to the menu (see also _includes/menu): ////////////////////////////// // // buildScanIconListInMenu -- Read !!!URL-scan: reference records and // create icons for each one at the top right of the VHV window. // function buildScanIconListInMenu() { var container = document.querySelector("#scan-urls"); if (!container) { return; } var urllist = getScanUrlList(); var output = ""; if (urllist.length > 0) { for (var i=0; i 0) { string += " | "; } string += filterList[i]; } string = encodeURIComponent(string); let letter = title.charAt(0).toUpperCase(); title = title.replace(/"/g, "'"); let output = ""; // Highlight any .filter-button that matches the contents // of #filter. let filterElement = document.querySelector("#filter"); let filterText = filterElement.value || ""; if (!filterText) { filterText = ""; } else { filterText = encodeURIComponent(filterText); } let highlight = ""; if ((filterText !== "") && (filterText === string)) { highlight = "highlight-filter-button"; } output += ``; output += ``; output += `${letter}`; output += ``; return output; } ////////////////////////////// // // makeScanIcon -- // function makeScanIcon(url, title) { title = title.replace(/"/g, "'"); var output = `"; return output; } ////////////////////////////// // // makeYoutubeIcon -- // output += "class='nav-icon fas fa-file-video-o'>"; // function makeYoutubeIcon(url, title) { title = title.replace(/"/g, "'"); var output = "
// // // //Verovio text font not needed anymore (loaded as a base-64 string): // // // // The saving process also needs FileSaver.js: // https://github.com/eligrey/FileSaver.js // but this is already included for saving editor contents. // ////////////////////////////// // // cleanOptions2 -- Remove options that will be processed interally from the data. // function cleanOptions2(content, options) { var lines = content.match(/[^\r\n]+/g); var output = options; var setlist = [""]; var optionsets = {}; optionsets[""] = {}; var i; for (i=0; i svgheight) { orientation = "landscape"; } } var orientation = orientation ? orientation : "portrait"; if (orientation === "landscape") { pagewidth = [pageheight, pageheight = pagewidth][0]; } var pageaspect = pageheight / pagewidth; var scaling = 0.99; var mmwidth; var mmheight; if (aspect < pageaspect) { mmwidth = (pagewidth / 10) * scaling; mmheight = (pagewidth / 10) * aspect * scaling; } else { mmheight = (pageheight / 10) * scaling; mmwidth = (pageheight / 10) / aspect * scaling; } var pagewidthmm = pagewidth / 10.0; var pageheightmm = pageheight / 10.0; // pdf page offset (units are in mm?) var x = 0; var y = 0; if (mmwidth < pagewidthmm) { x = (pagewidthmm - mmwidth); } x += 1; var newspan = document.createElement("span"); newspan.innerHTML = svg.outerHTML; var newsvg = newspan.querySelector("svg"); newsvg.setAttribute("width", mmwidth + "mm"); newsvg.setAttribute("height", mmheight + "mm"); var pdfOptions = {}; pdfOptions.fontCallback = svgFontCallback; var pdf = new PDFDocument({ useCSS: true, compress: true, autoFirstPage: false, layout: orientation }); var stream = pdf.pipe(blobStream()); stream.on('finish', function() { var blob = stream.toBlob('application/pdf'); var pdfFilebase = getFilenameBase(); var pdfFilename = pdfFilebase; //if (SAVEFILENAME) { // pdfFilename = SAVEFILENAME.replace(/\.[^.]*$/, "") + "-snapshot.pdf"; //} else { // pdfFilename = "snapshot.pdf"; //} if (pdfFilename) { pdfFilename += "-snapshot.pdf"; } else { pdfFilename = "snapshot.pdf"; } saveAs(blob, pdfFilename); $('html').css('cursor', 'auto'); }); loadPdfFonts(pdf) .then(function() { pdf.addPage({size: format, layout: orientation}); SVGtoPDF(pdf, newsvg, x, y, pdfOptions); pdf.end(); }); } ////////////////////////////// // // loadFontResource -- use font from file in pdf, returns promise // function loadFontResource(pdf, name, path) { var promise = new RSVP.Promise(function(resolve, reject) { var client = new XMLHttpRequest(); client.open("GET", path); client.responseType = "arraybuffer"; client.onreadystatechange = function() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(this); }; } }; client.send(null); }); return promise.then(function(data) { pdf.registerFont(name, data); return true; }); } ////////////////////////////// // // loadPdfFonts -- load all default fonts used by Verovio // function loadPdfFonts(pdf) { return RSVP.all([ // Text font used on VHV: loadFontResource(pdf, 'Times', '/scripts/pdfkit/EBGaramond-Regular.ttf'), loadFontResource(pdf, 'TimesItalic', '/scripts/pdfkit/EBGaramond-Italic.ttf'), loadFontResource(pdf, 'TimesBold', '/scripts/pdfkit/EBGaramond-Bold.ttf'), loadFontResource(pdf, 'TimesBoldItalic', '/scripts/pdfkit/EBGaramond-BoldItalic.ttf'), // no longer used: loadFontResource(pdf, 'VerovioText', '/scripts/pdfkit/VerovioText-1.0.ttf'), // SMuFL fonts that are available in VHV: loadFontResource(pdf, 'Leipzig', '/scripts/pdfkit/Leipzig.ttf'), loadFontResource(pdf, 'Leland', '/scripts/pdfkit/Leland.ttf'), loadFontResource(pdf, 'Bravura', '/scripts/pdfkit/Bravura.ttf'), loadFontResource(pdf, 'Gootville', '/scripts/pdfkit/Gootville.ttf'), loadFontResource(pdf, 'Petaluma', '/scripts/pdfkit/Petaluma.ttf'), ]); } ////////////////////////////// // // svgFontCallback -- substitute svg fonts with pdf fonts // function svgFontCallback(family, bold, italic, options) { if (family == "Leipzig") { return family; } if (family == "Leland") { return family; } if (family == "Bravura") { return family; } if (family == "Gootville") { return family; } if (family == "Petaluma") { return family; } if (family == "VerovioText") { // not used any more, probably remove return family; } if (family.match(/(?:^|,)\s*sans-serif\s*$/) || true) { if (bold) { return (italic) ? "TimesBoldItalic" : "TimesBold"; } else { return (italic) ? "TimesItalic" : "Times"; }; } return family; } // Functions related to saving files: ////////////////////////////// // // saveEditorContents -- Save the editor contents to a file on the local disk. // Saves in UTF-8 format. // function saveEditorContents() { var filebase = getFilenameBase(); if (!filebase) { filebase = "data"; } var filename = filebase; var extension = getFilenameExtension(); if (extension) { filename += "." + extension; } var size = EDITOR.session.getLength(); var matches; var line; var text = getTextFromEditor(); // var blob = new Blob([text], {type: 'text/plain;charset=utf-8'}); var blob = new Blob([text], {type: 'text/plain'}); saveAs(blob, filename); } // Functions for musical searching, and also // related to search toolbar: function buildSearchQueryFilter(parameters) { var output = ""; var pitch = parameters.pitch || ""; var interval = parameters.interval || ""; var rhythm = parameters.rhythm || ""; if (pitch.match(/^\s*bach\s*$/i)) { // Special search for the pitch sequence BACH. // H means B-natural in German, B means B-flat // The pitch search normally searches diatonically, // so also give the natural qualifications for // A and C (An and Cn for A-natural and C-natural). pitch = "b-ancnbn"; } // var output = "!!!filter: msearch"; var output = "msearch"; if (!pitch.match(/^\s*$/)) { output += " -p '" + pitch + "'"; } if (!interval.match(/^\s*$/)) { output += " -i '" + interval + "'"; } if (!rhythm.match(/^\s*$/)) { output += " -r '" + rhythm + "'"; } return output; } ////////////////////////////// // // clearMatchInfo -- if there is no queries in the search toolbar, // then clear any old search results. // function clearMatchInfo() { var esearch = document.querySelector("#search-results"); if (!esearch) { return; } esearch.innerHTML = "Search"; hideSearchLinkIcon(); } ////////////////////////////// // // copySearchUrl -- Copy URL with search if there is a repertory work // present in the text editor (although it will not be checked for any // possible modifications). This function gets the SEARCHFILTEROBJ parameter // and adds it to URL parameters. A repertory work is // identify if the FILEINFO object is defined and not empty, and // FILEINFO.location and FILEINFO.file are present and non-empty. // // SEARCHFILTEROBJ.pitch = p parameter // SEARCHFILTEROBJ.interval = i parameter // SEARCHFILTEROBJ.rhythm = r parameter // function copySearchUrl() { if (!SEARCHFILTEROBJ) { console.log("SEARCHFILTEROBJ IS EMPTY:", SEARCHFILTEROBJ); copyToClipboard(""); return; } if (!FILEINFO) { console.log("NO REPERTORY FILE TO WORK WITH"); copyToClipboard(""); return; } if (!FILEINFO.location) { console.log("NO LOCATION FOR REPERTORY FILE"); copyToClipboard(""); return; } if (!FILEINFO.file) { console.log("NO FILENAME FOR REPERTORY FILE"); copyToClipboard(""); return; } var pitch = SEARCHFILTEROBJ.pitch || ""; var interval = SEARCHFILTEROBJ.interval || ""; var rhythm = SEARCHFILTEROBJ.rhythm || ""; if (!pitch && !interval && !rhythm) { console.log("NO SEARCH PRESENT pitch:", pitch, "rhythm:", rhythm, "interval:", interval); copyToClipboard(""); return; } // Assuming data is accessed through https://, may // need to be adjusted if through http:// var link = "https://verovio.humdrum.org/?file="; var file = FILEINFO.location file += "/"; file += FILEINFO.file; link += encodeURIComponent(file); if (pitch) { link += "&p=" + encodeURIComponent(pitch); } if (interval) { link += "&i=" + encodeURIComponent(interval); } if (rhythm) { link += "&r=" + encodeURIComponent(rhythm); } link = link.replace(/%2f/gi, "/"); console.log("COPYING SEARCH URL", link, "TO CLIPBOARD"); copyToClipboard(link); } ////////////////////////////// // // doMusicSearch -- // function doMusicSearch() { var esearch = document.querySelector("#search-group"); if (!esearch) { return; } var epitch = esearch.querySelector("#search-pitch"); var einterval = esearch.querySelector("#search-interval"); var erhythm = esearch.querySelector("#search-rhythm"); var pitch = epitch.value.replace(/["']/g, "");; var interval = einterval.value.replace(/["']/g, "");; var rhythm = erhythm.value.replace(/["']/g, "");; PQUERY = pitch; RQUERY = rhythm; IQUERY = interval; if (pitch.match(/^\s*$/) && interval.match(/^\s*$/) && rhythm.match(/^\s*$/)) { if (SEARCHFILTER) { clearMatchInfo(); SEARCHFILTER = ""; SEARCHFILTEROBJ = {}; displayNotation(); hideSearchLinkIcon(); } else { // no previous search filter, so do not do anything } return; } SEARCHFILTEROBJ = { pitch: pitch, interval: interval, rhythm: rhythm }; SEARCHFILTER = buildSearchQueryFilter(SEARCHFILTEROBJ); showSearchLinkIcon(); displayNotation(); } ////////////////////////////// // // hideSearchLinkIcon -- Make sure that the search link icon is hidden. // function hideSearchLinkIcon() { var element = document.querySelector("#search-link"); if (element) { element.style.display = "none"; } } ////////////////////////////// // // showSearchHelp -- // function showSearchHelp() { var help = window.open("https://doc.verovio.humdrum.org/interface/search", "documentation"); help.focus(); } ////////////////////////////// // // showSearchLinkIcon -- Show the search link icon. // function showSearchLinkIcon() { if (!FILEINFO) { // console.log("NO REPERTORY FILE TO WORK WITH"); return; } if (!FILEINFO.location) { // console.log("NO LOCATION FOR REPERTORY FILE"); return; } if (!FILEINFO.file) { // console.log("NO FILENAME FOR REPERTORY FILE"); return; } var element = document.querySelector("#search-link"); if (element) { element.style.display = "inline-block"; } } ////////////////////////////// // // toggleChordSearchDirection -- // function toggleChordSearchDirection() { var helement = document.querySelector("#search-chord"); if (!helement) { console.log("CANNOT FIND HAND ICONS"); return; } var output = ""; if (SEARCHCHORDDIRECTION === "chord -d") { SEARCHCHORDDIRECTION = "chord -u"; output = ''; } else{ SEARCHCHORDDIRECTION = "chord -d"; output = ''; } helement.innerHTML = output; displayNotation(); } ////////////////////////////// // // toggleSearchView -- // function toggleSearchView() { var selement = document.querySelector("#search-zoom"); if (!selement) { console.log("CANNOT FIND SEARCH VIEW ICON"); return; } var output = ""; if (BRIEFSEARCHVIEW) { BRIEFSEARCHVIEW = ""; output = ''; } else { BRIEFSEARCHVIEW = "myank -d --marks"; output = ''; } selement.innerHTML = output; displayNotation(); } // Functions for to Google spreadsheet interaction // and also related to spreadsheet toolbar: ////////////////////////////// // // downloadDataFromSpreadsheet -- // function downloadDataFromSpreadsheet(event) { var selement = document.querySelector("#scriptid"); if (!selement) { return; } var id = getSpreadsheetScriptId(selement.value); if (!id) { return; } showSpreadsheetIconState(); setTimeout(function () { document.body.classList.add("waiting"); }, 0); var url = "https://script.google.com/macros/s/" + id + "/exec"; var request = new XMLHttpRequest; request.open("GET", url); var shiftkey = event.shiftKey; request.addEventListener("load", function (event) { storeSpreadsheetDataInEditor(request.responseText, shiftkey); setTimeout(function () { document.body.classList.remove("waiting"); }, 10); }); request.send(); } ////////////////////////////// // // fillSpreadsheetId -- This is run after creating the toolbar. // The spreasdsheet information from localStorage is inserted // into the Spreadsheet script ID box. // function fillSpreadsheetId() { var value = ""; if (SPREADSHEETSCRIPTID) { value = SPREADSHEETSCRIPTID; } if (SPREADSHEETID) { value += "|" + SPREADSHEETID; } var selement = document.querySelector("#scriptid"); if (!selement) { return; } selement.value = value; showSpreadsheetIconState(); } ////////////////////////////// // // getSpreadsheetId -- A spreadsheed ID may be added // after a | character in the spreadsheet script ID box. // function getSpreadsheetId(value) { var matches = value.match(/([^\/]+)\/exec/); if (matches) { value = matches[1]; } if (value.match(/^\s*$/)) { value = ""; } matches = value.match(/^\s*(.*)[|\s]+(.*)\s*$/); if (matches) { value = matches[2]; } SPREADSHEETID = value; localStorage.SPREADSHEETID = SPREADSHEETID; return value; } ////////////////////////////// // // getSpreadsheetScriptId -- Extract ID from URL if present and also // store ID in localStorage for use in a later session. // function getSpreadsheetScriptId(value) { var matches = value.match(/([^\/]+)\/exec/); if (matches) { value = matches[1]; } if (value.match(/^\s*$/)) { value = ""; } matches = value.match(/^\s*([^|\s]*)/); if (matches) { value = matches[1]; } SPREADSHEETSCRIPTID = value; localStorage.SPREADSHEETSCRIPTID = SPREADSHEETSCRIPTID; return value; } ////////////////////////////// // // openSpreadsheet -- // function openSpreadsheet() { var selement = document.querySelector("#scriptid"); if (!selement) { return; } var id = getSpreadsheetId(selement.value); if (!id) { if (SPREADSHEETID) { id = SPREADSHEETID; } } if (!id) { return; } var url = "https://docs.google.com/spreadsheets/d/"; url += id; window.open(url, "spreasheet"); } ////////////////////////////// // // showSpreadsheetIconState -- // function showSpreadsheetIconState() { var selement = document.querySelector("#scriptid"); if (!selement) { return; } var scriptid = getSpreadsheetScriptId(selement.value); var sheetid = getSpreadsheetId(selement.value); SPREADSHEETSCRIPTID = scriptid; SPREADSHEETID = sheetid; localStorage.SPREADSHEETSCRIPTID = scriptid; localStorage.SPREADSHEETID = sheetid; var sheetelement = document.querySelector("#sheetid"); if (!sheetelement) { return; } if (!sheetid) { sheetelement.style.display = "none"; } else { sheetelement.style.display = "inline-block"; } } function storeSpreadsheetDataInEditor(data, shiftkey) { // first check to see if the current contents has any double tabs, // and if not, collapse tabs in data. var contents = getTextFromEditor(); if (!contents.match(/\t\t/)) { // collapse tabs if (shiftkey) { storeSpreadsheetDataInEditor2(data); } else { MENU.applyFilter("tabber -r", data, storeSpreadsheetDataInEditor2); } } else { // preserve presumed expanded tab data. setTextInEditor(data); } } function storeSpreadsheetDataInEditor2(data) { setTextInEditor(data); } ////////////////////////////// // // uploadDataToSpreadsheet -- // function uploadDataToSpreadsheet(event) { setTimeout(function () { document.body.classList.add("waiting"); }, 0); if (event.shiftKey) { // upload without passing through tabber filter. uploadDataToSpreadsheet2(getTextFromEditor()); } else { MENU.applyFilter("tabber", getTextFromEditor(), uploadDataToSpreadsheet2); } } function uploadDataToSpreadsheet2(data) { var selement = document.querySelector("#scriptid"); if (!selement) { return; } var id = getSpreadsheetScriptId(selement.value); if (!id) { return; } showSpreadsheetIconState(); var url = "https://script.google.com/macros/s/" + id + "/exec"; var request = new XMLHttpRequest; var formdata = new FormData(); formdata.append("humdrum", data); request.open("POST", url); request.send(formdata); request.addEventListener("load", function (event) { setTimeout(function () { document.body.classList.remove("waiting"); }, 10); }); } // Functions related to sound playback: // // Programmer: Craig Stuart Sapp // Creation Date: Fri Jun 23 08:11:13 CEST 2017 // Last Modified: Fri Jun 23 08:11:16 CEST 2017 // Filename: _includes/scripts/timemap.js // Syntax: JavaScript 1.8/ECMAScript 5 // vim: ts=3: ft=javascript // // Description: Timemap processing code for VHV. // var TIMEMAP = []; var LAST_TIMEMAP_INDEX = -1; var LAST_TIME = -1; var LOOKAHEAD = 20; // 20 milliseconds var INCREMENT = 20; // 20 milliseconds var REFRESH; ////////////////////////////// // // CheckEventMap -- // function CheckEventMap(etime, events) { for (var i=0; i 0) { // a specific toolbar menu is desired nextindex = menunum - 1; if (nextindex >= elements.length) { nextindex = elements.length - 1; } } else { nextindex = activeindex + 1; if (nextindex >= elements.length) { nextindex = 0; } } elements[activeindex].style.display = "none"; elements[nextindex].style.display = "block"; LASTTOOLBAR = nextindex + 1; localStorage.LASTTOOLBAR = LASTTOOLBAR; } function gotoNextToolbar(number, event) { var elements = document.querySelectorAll("[id^=toolbar-]"); var newnum; if (event) { if (event.shiftKey) { if (event.altKey) { newnum = 1; } else { newnum = number - 1; } } else if (event.altKey) { newnum = 1; } else { newnum = number + 1; } } else { newnum = number + 1; } if (newnum < 1) { newnum = elements.length; } else if (newnum > elements.length) { newnum = 1; } var id = "toolbar-" + newnum; for (var i=0; i elements.length) { nextNumber = 1; } var id = "toolbar-" + nextNumber; for (var i=0; i" KEYS.EnterKey = "Enter"; // 13 "Enter" KEYS.EscKey = "Escape"; // 27 "Escape" KEYS.MinusKey = "Minus"; // 189 "-", "_" KEYS.SemiColonKey = "Semicolon"; // 186 ";", ":" KEYS.SingleQuoteKey = "Quote"; // 222 "'", "\"" KEYS.SlashKey = "Slash"; // 191 "/" KEYS.SpaceKey = "Space" // 32 " " KEYS.TabKey = "Tab"; // 9 "Tab" KEYS.BracketLeftKey = "BracketLeft"; // 219 "[", "{" KEYS.BracketRightKey = "BracketRight"; // 221 "]", "}" KEYS.EqualKey = "Equal"; // 187 "=", "+" KEYS.ControlLeftKey = "ControlLeft"; // 17 "Control" event.ctrl KEYS.ControlRightKey = "ControlRight"; // 17 "Control" event.ctrl KEYS.ShiftLeftKey = "ShiftLeft"; // 16 "Shift" event.shift KEYS.ShiftRightKey = "ShiftRight"; // 16 "Shift" event.shift KEYS.LeftKey = "ArrowLeft"; // 37 "ArrowLeft" KEYS.UpKey = "ArrowUp"; // 38 "ArrowUp" KEYS.RightKey = "ArrowRight"; // 39 "ArrowRight" KEYS.DownKey = "ArrowDown"; // 40 "ArrowDown" KEYS.PgUpKey = "PageUp"; // 33 "PageUp" KEYS.PgDnKey = "PageDown"; // 34 "PageDown" KEYS.EndKey = "End"; // 35 "End" KEYS.HomeKey = "Home"; // 36 "Home" KEYS.F1Key = "F1"; // 112 "F1" KEYS.F2Key = "F2"; // 113 "F2" KEYS.F3Key = "F3"; // 114 "F3" KEYS.F4Key = "F4"; // 115 "F4" KEYS.F5Key = "F5"; // 116 "F5" KEYS.F6Key = "F6"; // 117 "F6" KEYS.F7Key = "F7"; // 118 "F7" KEYS.F8Key = "F8"; // 119 "F8" KEYS.F9Key = "F9"; // 120 "F9" KEYS.F10Key = "F10"; // 121 "F10" KEYS.F11Key = "F11"; // 122 "F11" KEYS.F12Key = "F12"; // 123 "F12" // etc. to F32Key ////////////////////////////// // // GetKey -- // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState // https://hacks.mozilla.org/2017/03/internationalize-your-keyboard-controls // function GetKey(event) { console.log("EVENT", event); let code = event.code; let key = event.key; if (key && key === "Dead") { return code; } if (key && key.match(/^[A-Za-z]$/)) { return KEYS[`${key.toUpperCase()}Key`]; } // Alt-key hassles which will cause problems entering // text that uses the alt key to create characters... if (event.altKey) { if ((key == "›") && (code == "KeyZ")) { return KEYS.YKey; } if ((key == "Dead") && (code == "KeyY")) { return KEYS.ZKey; } if ((key == "∫") && (code == "KeyB")) { return KEYS.BKey; } } return event.code; } // Initialization functions: ////////////////////////////// // // downloadVerovioToolkit -- // function downloadVerovioToolkit(use_worker) { vrvWorker = new vrvInterface(use_worker, initializeVerovioToolkit); }; ////////////////////////////// // // setupAceEditor -- // https://en.wikipedia.org/wiki/Ace_(editor) // // see: https://github.com/ajaxorg/ace/wiki/Embedding-API // // Folding: // https://cloud9-sdk.readme.io/docs/code-folding // // console.log("NUMBER OF LINES IN FILE", EDITOR.session.getLength()); // // Keyboard Shortcuts: // https://github.com/ajaxorg/ace/wiki/Default-Keyboard-Shortcuts // // ACE Grammar editor: // https://foo123.github.io/examples/ace-grammar // function setupAceEditor(idtag) { EDITOR = ace.edit(idtag); ace.config.set('modePath', "/scripts/ace"); ace.config.set('workerPath', "/scripts/ace"); ace.config.set('themePath', "/scripts/ace"); EDITOR.getSession().setUseWorker(true); EDITOR.$blockScrolling = Infinity; EDITOR.setAutoScrollEditorIntoView(true); EDITOR.setBehavioursEnabled(false); // no auto-close of parentheses, quotes, etc. // EDITOR.cursorStyle: 'ace', // "ace"|"slim"|"smooth"|"wide" // See this webpage to turn of certain ace editor shortcuts: // https:github.com//ajaxorg/ace/blob/master/lib/ace/commands/default_commands.js // These eat alt-l and alt-shift-l keyboard shortcuts on linux: EDITOR.commands.removeCommand("fold", true); EDITOR.commands.removeCommand("unfold", true); // best themes: // kr_theme == black background, gray highlight, muted colorizing // solarized_dark == blue background, light blue hilight, relaxing colorizing // vibrant_ink == black background, gray highlight, nice colorizing // solarized_light == yellowish background, gray highlight, nice colorizing // EDITOR.setKeyboardHandler("ace/keyboard/vim"); // keybinding = ace | vim | emacs | custom // fontsize = 10px, etc // theme = "ace/theme/solarize_light" // EDITOR.getSession().setMode("ace/mode/javascript"); setEditorModeAndKeyboard(); EDITOR.getSession().setTabSize(TABSIZE); EDITOR.getSession().setUseSoftTabs(false); // Don't show line at 80 columns: EDITOR.setShowPrintMargin(false); Range = require("ace/range").Range; EDITOR.getSession().selection.on("changeCursor", function(event) { if (EditorMode == "esac") { var cursorPosition = EDITOR.getCursorPosition(); if (cursorPosition.row != EditorCursorLine) { EditorCursorLine = cursorPosition.row; if (!FreezeRendering) { displayNotation(); } updateMelodyStartLineForEsac(); } } else { highlightNoteInScore(event) } }); // Force the cursor to blink when blurred (unfocused): // EDITOR.renderer.$cursorLayer.showCursor(); EDITOR.renderer.$cursorLayer.smoothBlinking = true; EDITOR.renderer.$cursorLayer.setBlinking(true); //EDITOR.commands.addCommand({ // name: 'saveFile', // bindKey: { // win: 'Alt-G', // mac: 'Alt-G', // sender: 'editor|cli' // }, // exec: function(env, argc, request) { // alert("HI!", env, argc, request); // } //}); var cursor = document.querySelector(".ace_content .ace_cursor-layer"); if (cursor) { CURSOR_OBSERVER = new MutationObserver(customCursor); CURSOR_OBSERVER.observe(cursor, {attributes: true}); } insertSplashMusic(); } ////////////////////////////// // // updateMelodyStartLineForEsac // function updateMelodyStartLineForEsac() { if (EditorMode !== "esac") { clearAllAceMarkers(); } let cursorPosition = EDITOR.getCursorPosition(); let currentLine = cursorPosition.row; let startLine = Math.max(0, currentLine - 50); let endLine = Math.min(EDITOR.session.getLength() - 1, currentLine + 50); let lines = EDITOR.session.getLines(startLine, endLine + 1); let regex = /^[A-Z0-9_-]+\s*$/; function findRange(lines, startLine, currentLine, regex) { let start = -1; let end = -1; // Check if the current line matches the regex if (regex.test(lines[currentLine - startLine])) { start = currentLine; // Set the start line to the current line } else { // Search backward from current line to find first line matching regex for (let i = currentLine - startLine; i >= 0; i--) { if (regex.test(lines[i])) { start = i + startLine; // Set start to first matching line above cursor break; } } } // If no start line is found, return early //if (start === -1) { // return { start: start, end: end }; //} // Search forward from the line after the start line to find the next line matching the regex let startj = 0; if (start < 0) { for (let j = 0; j < lines.length; j++) { if (regex.test(lines[j])) { startj = j + 1; start = j; // Set to the next break; } } } for (let j = startj; j < lines.length; j++) { if (regex.test(lines[j])) { end = (j + startLine) - 1; // Set end to the line before the next matching line break; } } // If no next matching line is found, set the end to the last line in the window if (end < 0) { end = endLine; // Set end to the last line in the window (inclusive) } if (start < 0) { start = 0; } return { start: start, end: end }; } clearAllAceMarkers(); // Find the range of lines to extract within the 50-line window let range = findRange(lines, startLine, currentLine, regex); // console.log("RANGE START = ", range.start, "RANGE END = ", range.end); if (range.start !== -1) { addAceEditorMarker(range.start); } else { console.warn("Cannot find starting line of EsAC data."); } } ////////////////////////////// // // addAceEditorMarker -- // function addAceEditorMarker(line) { console.warn("ADDING MARKER TO LINE", line); let range = ace.require('ace/range').Range; let value = EDITOR.session.addMarker(new range(line, 0, line, 1), "esac-highlight", "fullLine", true); EDITOR.renderer.updateFull(); // Forces the editor to refresh/render console.error("MARKER RETURN", value); } ////////////////////////////// // // clearAllAceMarks -- // function clearAllAceMarkers() { let markers = EDITOR.session.getMarkers(true); for (let markerId in markers) { if (markers.hasOwnProperty(markerId)) { if (markers[markerId].type === "fullLine") { EDITOR.session.removeMarker(markerId); } } } } ////////////////////////////// // // insertSplashMusic -- // function insertSplashMusic() { var splashElement = document.querySelector("#input-splash"); if (!splashElement) { return; } text = EDITOR.getValue(); if (!text.match(/^\s*$/)) { return; } var splash = splashElement.textContent; setTextInEditor(splash); } ////////////////////////////// // // Setup styling of blurred ace-editor cursor: // var CURSOR_OBSERVER; var CURSOR_DISPLAY; function customCursor() { activeElement = document.activeElement.nodeName; let cursor = EDITOR.renderer.$cursorLayer.cursor; let cursorstate = null; for (let i=0; i= parseInt(line2)) { return; } var i = line - 2; // -1 for 0-index and -1 for line after var counter = 0; var target = InterfaceSingleNumber; if (!target) { target = 1; } while (i > 0) { var text = EDITOR.session.getLine(i); if (text.match(/^\*/) || text.match(/^=/) || text.match(/^!/) || (text === "")) { i--; continue; } var token2 = getEditorContents(i+1, field); if (token2.match(/[A-G]/i)) { counter++; } if (counter != target) { i--; continue; } break; } console.log("LEFTENDMOVEBACK NEW", token1, line, field, number, token2, i+1, id); if (i <= 0) { // no note to attach to return; } if ((text[0] == '*') || (text[0] == '!') || (text === "")) { // no note to attach to return; } var freezeBackup = FreezeRendering; FreezeRendering = true; var slurstart = deleteSlurStart(id, line, field, number); if (slurstart !== "") { addSlurStart(id, i+1, field, slurstart); } FreezeRendering = freezeBackup; displayNotation(); InterfaceSingleNumber = 0; } function addSlur(id, line, field) { var token = getEditorContents(line, field); var freezeBackup = FreezeRendering; FreezeRendering = true; addSlurStart(id, line, field, '('); var i = parseInt(line); // -1 for 0-index and +1 for line after var counter = 0; var size = EDITOR.session.getLength(); var target = InterfaceSingleNumber; if (!target) { target = 1; } while (i < size) { var text = EDITOR.session.getLine(i); if (text.match(/^\*/) || text.match(/^=/) || text.match(/^!/) || (text === "")) { i++; continue; } var token2 = getEditorContents(i+1, field); if (token2.match(/[A-G]/i)) { counter++; } if (counter != target) { i++; continue; } break; } if (i >= size) { // no note to attach to return; } if ((text[0] == '*') || (text[0] == '!') || (text === "")) { // no note to attach to return; } if (i+1 <= line) { // do not pass slur begin return; } addSlurEnd(id, i+1, field, ')'); var newid = id.replace(/^note-/, "slur-"); // FIX N number here later: var ending = "-L" + (i+1) + "F" + field + "N" + 1; newid += ending; FreezeRendering = freezeBackup; if (!FreezeRendering) { displayNotation(null, null, newid); } InterfaceSingleNumber = 0; // for some reason the highlighting is lost on the note, // so add it back: // wait for worker to finish redrawing? setTimeout(function() { var element = document.querySelector("svg g#" + id); if (element) { var classname = element.getAttribute("class"); if (!classname.match(/\bhighlight\b/)) { classname += " highlight"; element.setAttribute("class", classname); } CursorNote = element; } }, 300); } function addSlurStart(id, line, field, slurstart) { var token = getEditorContents(line, field); var newtoken = ""; for (var i=token.length-1; i>=0; i--) { if (token[i] == '(') { // need to insert new slur after last one newtoken = token.substring(0, i+1); newtoken += slurstart; newtoken += token.substring(i+1); break; } } if (newtoken === "") { newtoken = slurstart + token; } var pcount = 0; for (i=0; i') { output += '>'; i++; } else if (token[i+1] == '<') { output += '<'; i++; } counter++; } // console.log("OLDTOKEN1", token, "NEWTOKEN1", newtoken); if (newtoken !== token) { RestoreCursorNote = id; HIGHLIGHTQUERY = id; setEditorContents(line, field, newtoken, id); } return output; } function deleteSlurEnd(id, line, field, number) { var token = getEditorContents(line, field); var newtoken = ""; var counter = 0; var output = ""; for (var i=0; i= parseInt(line2)) { return; } var i = parseInt(line); // -1 for 0-index and +1 for line after var counter = 0; var size = EDITOR.session.getLength(); var target = InterfaceSingleNumber; if (!target) { target = 1; } while (i < size) { var text = EDITOR.session.getLine(i); if (text.match(/^\*/) || text.match(/^=/) || text.match(/^!/) || (text === "")) { i++; continue; } var token2 = getEditorContents(i+1, field); if (token2.match(/[A-G]/i)) { counter++; } if (counter != target) { i++; continue; } break; } if (i >= size) { // no note to attach to return; } if ((text[0] == '*') || (text[0] == '!') || (text === "")) { // no note to attach to return; } if (i+1 >= line2) { // do not pass slur end return; } var freezeBackup = FreezeRendering; FreezeRendering = true; var slurstart = deleteSlurStart(id, line, field, number); if (slurstart !== "") { addSlurStart(id, i+1, field, slurstart); } FreezeRendering = freezeBackup; displayNotation(); InterfaceSingleNumber = 0; } function rightEndMoveForward(id, line, field, number, line2, field2, number2) { // console.log("RIGHT END MOVE FORWARD"); var token1 = getEditorContents(line2, field); if (parseInt(line) >= parseInt(line2)) { return; } var i = parseInt(line2); // -1 for 0-index and +1 for line after var counter = 0; var size = EDITOR.session.getLength(); var target = InterfaceSingleNumber; if (!target) { target = 1; } while (i < size) { var text = EDITOR.session.getLine(i); if (text.match(/^\*/) || text.match(/^=/) || text.match(/^!/) || (text === "")) { i++; continue; } var token2 = getEditorContents(i+1, field); if (token2.match(/[A-G]/i)) { counter++; } if (counter != target) { i++; continue; } break; } if (i >= size) { // no note to attach to return; } if ((text[0] == '*') || (text[0] == '!') || (text === "")) { // no note to attach to return; } if (i+1 <= line) { // do not pass slur start return; } var freezeBackup = FreezeRendering; FreezeRendering = true; var slurend = deleteSlurEnd(id, line2, field2, number2); if (slurend !== "") { addSlurEnd(id, i+1, field, slurend); } // need to remove "N" if "N1" (in verovio) var newend = "L" + (i+1) + "F" + field2 + "N" + number2; var newid = id.replace(/-[^-]+$/, "-" + newend); RestoreCursorNote = newid; HIGHLIGHTQUERY = newid; FreezeRendering = freezeBackup; displayNotation(); InterfaceSingleNumber = 0; } function rightEndMoveBack(id, line, field, number, line2, field2, number2) { // console.log("RIGHT END MOVE BACKWARD"); var token1 = getEditorContents(line2, field); if (parseInt(line) >= parseInt(line2)) { return; } var i = parseInt(line2) - 2; // -1 for 0-index and -1 for line after var counter = 0; var target = InterfaceSingleNumber; if (!target) { target = 1; } while (i >= 0) { var text = EDITOR.session.getLine(i); if (text.match(/^\*/) || text.match(/^=/) || text.match(/^!/) || (text === "")) { i--; continue; } var token2 = getEditorContents(i+1, field); if (token2.match(/[A-G]/i)) { counter++; } if (counter != target) { i--; continue; } break; } if (i <= 0) { // no note to attach to return; } if ((text[0] == '*') || (text[0] == '!') || (text === "")) { // no note to attach to return; } if (i+1 <= line) { // do not pass slur start return; } var freezeBackup = FreezeRendering; FreezeRendering = true; var slurend = deleteSlurEnd(id, line2, field2, number2); if (slurend !== "") { addSlurEnd(id, i+1, field, slurend); } // need to remove "N" if "N1" (in verovio) var newend = "L" + (i+1) + "F" + field2 + "N" + number2; var newid = id.replace(/-[^-]+$/, "-" + newend); RestoreCursorNote = newid; HIGHLIGHTQUERY = newid; FreezeRendering = freezeBackup; displayNotation(); InterfaceSingleNumber = 0; } function setTieAboveMarker(id, line, field, subfield) { console.log("TIE ABOVE", token, line, field, subfield, id); var token = getEditorContents(line, field); if ((token === ".") || (token[0] == "!") || (token[0] == "*")) { return; } if (subfield) { var subtokens = token.split(" "); token = subtokens[subfield-1]; } if (token.match("r")) { // reset, so no tie allowed return; } var newtoken = ""; var matches; if (!(token.match(/[[]/) || token.match("_"))) { // no tie start return; } var directions = insertDirectionRdfs(); var above = directions[0]; var below = directions[1]; var re = new RegExp("([^_[]*)([_[]+)([" + above + below + "]*)([^_[]*)"); if (matches = re.exec(token)) { newtoken = matches[1] + matches[2] + above + matches[4]; } else { newtoken = token; } if (subfield) { subtokens[subfield-1] = newtoken; newtoken = subtokens.join(" "); } // console.log("OLDTOKEN", token, "NEWTOKEN", newtoken); if (newtoken !== token) { RestoreCursorNote = id; HIGHLIGHTQUERY = id; setEditorContents(line, field, newtoken, id); } } function setTieBelowMarker(id, line, field, subfield) { console.log("TIE BELOW", token, line, field, subfield, id); var token = getEditorContents(line, field); if ((token === ".") || (token[0] == "!") || (token[0] == "*")) { return; } if (subfield) { var subtokens = token.split(" "); token = subtokens[subfield-1]; } if (token.match("r")) { // reset, so no tie allowed return; } var newtoken = ""; var matches; if (!(token.match(/[[]/) || token.match("_"))) { // no tie start return; } var directions = insertDirectionRdfs(); var above = directions[0]; var below = directions[1]; var re = new RegExp("([^_[]*)([_[]+)([" + above + below + "]*)([^_[]*)"); if (matches = re.exec(token)) { newtoken = matches[1] + matches[2] + below + matches[4]; } else { newtoken = token; } if (subfield) { subtokens[subfield-1] = newtoken; newtoken = subtokens.join(" "); } // console.log("OLDTOKEN", token, "NEWTOKEN", newtoken); if (newtoken !== token) { RestoreCursorNote = id; HIGHLIGHTQUERY = id; setEditorContents(line, field, newtoken, id); } } function deleteTieDirectionMarker(id, line, field, subfield) { console.log("TIE DIRECTION REMOVE", token, line, field, subfield, id); var token = getEditorContents(line, field); if ((token === ".") || (token[0] == "!") || (token[0] == "*")) { return; } if (subfield) { var subtokens = token.split(" "); token = subtokens[subfield-1]; } if (token.match("r")) { // reset, so no tie allowed return; } var newtoken = ""; var matches; if (!(token.match(/[[]/) || token.match("_"))) { // no tie start return; } var directions = insertDirectionRdfs(); var above = directions[0]; var below = directions[1]; var re = new RegExp("([^_[]*)([_[]+)([" + above + below + "]*)([^_[]*)"); if (matches = re.exec(token)) { newtoken = matches[1] + matches[2] + matches[4]; } else { newtoken = token; } if (subfield) { subtokens[subfield-1] = newtoken; newtoken = subtokens.join(" "); } // console.log("OLDTOKEN", token, "NEWTOKEN", newtoken); if (newtoken !== token) { RestoreCursorNote = id; HIGHLIGHTQUERY = id; setEditorContents(line, field, newtoken, id); } } function setStemAboveMarker(id, line, field) { console.log("STEM ABOVE", line, field, id); var token = getEditorContents(line, field); if ((token === ".") || (token[0] == "!") || (token[0] == "*")) { return; } if (token.match("r")) { // rest, which does not need/have a natural return; } var matches; var subtokens = token.split(" "); for (var i=0; in-]*)([A-Ga-g#Xx<>yYnTt:'~oOS$MmWw\^-]+)(.*)/)) { subtokens[i] = matches[1] + matches[2] + "/" + matches[3]; } } var newtoken = subtokens.join(" "); // console.log("OLDTOKEN", token, "NEWTOKEN", newtoken); if (newtoken !== token) { RestoreCursorNote = id; HIGHLIGHTQUERY = id; setEditorContents(line, field, newtoken, id); } } function setStemBelowMarker(id, line, field) { console.log("STEM BELOW", line, field, id); var token = getEditorContents(line, field); console.log("TOKEN EXTRACTED IS", token); if ((token === ".") || (token[0] == "!") || (token[0] == "*")) { return; } if (token.match("r")) { // rest, which does not need/have a natural return; } var matches; var subtokens = token.split(" "); for (var i=0; in-]*)([A-Ga-g#Xx<>yYnTt:'~oOS$MmWw\^-]+)(.*)/)) { subtokens[i] = matches[1] + matches[2] + "\\" + matches[3]; } } var newtoken = subtokens.join(" "); // console.log("OLDTOKEN", token, "NEWTOKEN", newtoken); if (newtoken !== token) { RestoreCursorNote = id; HIGHLIGHTQUERY = id; setEditorContents(line, field, newtoken, id); } } function deleteStemMarker(id, line, field) { console.log("REMOVE STEMS", line, field, id); var token = getEditorContents(line, field); if ((token === ".") || (token[0] == "!") || (token[0] == "*")) { return; } if (token.match("r")) { // rest, which does not need/have a natural return; } var newtoken = token.replace(/[\\\/]/g, ""); // console.log("OLDTOKEN", token, "NEWTOKEN", newtoken); if (newtoken !== token) { RestoreCursorNote = id; HIGHLIGHTQUERY = id; setEditorContents(line, field, newtoken, id); } } function transposeNote(id, line, field, subfield, amount) { // console.log("TRANSPOSE Note", line, field, subfield, id); var token = getEditorContents(line, field); amount = parseInt(amount); var target = InterfaceSingleNumber; if (!target) { target = 1; } if (target > 1) { if (amount > 0) { amount = target - 1; } else { amount = -target + 1; } InterfaceSingleNumber = 0; } if (subfield) { var subtokens = token.split(" "); token = subtokens[subfield-1]; } if ((token === ".") || (token[0] == "!") || (token[0] == "*")) { return; } if (token.match("r")) { // rest, which does not need/have a natural return; } var newtoken; var matches; if (matches = token.match(/([^a-gA-G]*)([a-gA-G]+)([^a-gA-G]*)/)) { newtoken = matches[1]; newtoken += transposeDiatonic(matches[2], amount); newtoken += matches[3]; } if (subfield) { subtokens[subfield-1] = newtoken; newtoken = subtokens.join(" "); } // console.log("OLDTOKEN", token, "NEWTOKEN", newtoken); if (newtoken !== token) { RestoreCursorNote = id; HIGHLIGHTQUERY = id; setEditorContents(line, field, newtoken, id); } } function toggleEditorialAccidental(id, line, field, subfield) { console.log("TOGGLE EDITORIAL ACCIDENTAL", line, field, subfield, id); var token = getEditorContents(line, field); if (subfield) { var subtokens = token.split(" "); token = subtokens[subfield-1]; } if ((token === ".") || (token[0] == "!") || (token[0] == "*")) { return; } if (token.match("r")) { // rest, which does not need/have an accidental return; } var editchar = insertEditorialAccidentalRdf(); var newtoken; var matches; var re = new RegExp(editchar); if (re.exec(token)) { newtoken = token.replace(new RegExp(editchar, "g"), ""); } else if (token.match(/[-#n]/)) { // add editorial accidental matches = token.match(/(.*[a-gA-Gn#xXyY-]+)(.*)/); newtoken = matches[1] + editchar + matches[2]; } else { // add a natural and an editorial accidental matches = token.match(/(.*[a-gA-GxXyY]+)(.*)/); newtoken = matches[1] + "n" + editchar + matches[2]; } if (subfield) { subtokens[subfield-1] = newtoken; newtoken = subtokens.join(" "); } // console.log("OLDTOKEN", token, "NEWTOKEN", newtoken); if (newtoken !== token) { RestoreCursorNote = id; HIGHLIGHTQUERY = id; setEditorContents(line, field, newtoken, id); } } function toggleSharp(id, line, field, subfield) { // console.log("TOGGLE NATURAL ACCIDENTAL", line, field, subfield, id); var token = getEditorContents(line, field); if (subfield) { var subtokens = token.split(" "); token = subtokens[subfield-1]; } if ((token === ".") || (token[0] == "!") || (token[0] == "*")) { return; } if (token.match("r")) { // rest, which does not need/have a natural return; } var newtoken; if (InterfaceSingleNumber == 2) { if (!token.match("##")) { // add double sharp newtoken = token.replace(/[#n-]+/, ""); newtoken = newtoken.replace(/([a-gA-G]+)/, function(str,p1) { return p1 ? p1 + "##" : str}); } else { // remove double-sharp newtoken = token.replace(/#+i?/, ""); } InterfaceSingleNumber = 0; } else { if (token.match("##") || !token.match("#")) { // add sharp newtoken = token.replace(/[#n-]+/, ""); newtoken = newtoken.replace(/([a-gA-G]+)/, function(str,p1) { return p1 ? p1 + "#" : str}); } else { // remove sharp newtoken = token.replace(/#+i?/, ""); } } if (subfield) { subtokens[subfield-1] = newtoken; newtoken = subtokens.join(" "); } // console.log("OLDTOKEN", token, "NEWTOKEN", newtoken); if (newtoken !== token) { RestoreCursorNote = id; HIGHLIGHTQUERY = id; setEditorContents(line, field, newtoken, id); } } function toggleFlat(id, line, field, subfield) { // console.log("TOGGLE FLAT ACCIDENTAL", line, field, subfield, id); var token = getEditorContents(line, field); if (subfield) { var subtokens = token.split(" "); token = subtokens[subfield-1]; } if ((token === ".") || (token[0] == "!") || (token[0] == "*")) { return; } if (token.match("r")) { // rest, which does not need/have a natural return; } var newtoken; if (InterfaceSingleNumber == 2) { if (!token.match("--")) { // add flat newtoken = token.replace(/[#n-]+/, ""); newtoken = newtoken.replace(/([a-gA-G]+)/, function(str,p1) { return p1 ? p1 + "--" : str}); } else { // remove flat newtoken = token.replace(/-+i?/, ""); } InterfaceSingleNumber = 0; } else { if (token.match("--") || !token.match("-")) { // add flat newtoken = token.replace(/[#n-]+/, ""); newtoken = newtoken.replace(/([a-gA-G]+)/, function(str,p1) { return p1 ? p1 + "-" : str}); } else { // remove flat newtoken = token.replace(/-+i?/, ""); } } if (subfield) { subtokens[subfield-1] = newtoken; newtoken = subtokens.join(" "); } // console.log("OLDTOKEN", token, "NEWTOKEN", newtoken); if (newtoken !== token) { RestoreCursorNote = id; HIGHLIGHTQUERY = id; setEditorContents(line, field, newtoken, id); } } function toggleNatural(id, line, field, subfield) { console.log("TOGGLE NATURAL ACCIDENTAL", line, field, subfield, id); var token = getEditorContents(line, field); if (subfield) { var subtokens = token.split(" "); token = subtokens[subfield-1]; } if ((token === ".") || (token[0] == "!") || (token[0] == "*")) { return; } if (token.match("r")) { // rest, which does not need/have a natural return; } var newtoken; if (!token.match("n")) { // add natural newtoken = token.replace(/[#n-]+/, ""); newtoken = newtoken.replace(/([a-gA-G]+)/, function(str,p1) { return p1 ? p1 + "n" : str}); } else { // remove natural newtoken = token.replace(/n+i?/, ""); } if (subfield) { subtokens[subfield-1] = newtoken; newtoken = subtokens.join(" "); } // console.log("OLDTOKEN", token, "NEWTOKEN", newtoken); if (newtoken !== token) { RestoreCursorNote = id; HIGHLIGHTQUERY = id; setEditorContents(line, field, newtoken, id); } } function toggleExplicitAccidental(id, line, field, subfield) { console.log("TOGGLE EXPLICIT ACCIDENTAL", line, field, subfield, id); var token = getEditorContents(line, field); if (subfield) { var subtokens = token.split(" "); token = subtokens[subfield-1]; } if ((token === ".") || (token[0] == "!") || (token[0] == "*")) { return; } if (token.match("r")) { // rest, so no accidental return; } var newtoken; var matches; if (token.match(/n/)) { // remove cautionary natural newtoken = token.replace(/n/g, ""); } else if (matches = token.match(/([^#-]*)([#-]+)(X?)([^#-]*)/)) { // add or remove "X" from sharp/flats if (matches[3] === "X") { // remove cautionary accidental newtoken = matches[1] + matches[2] + matches[4]; } else { // add cautionary accidental newtoken = matches[1] + matches[2] + "X" + matches[4]; } } else { // add a natural sign if (matches = token.match(/([^A-G]*)([A-G]+)([^A-G]*)/i)) { newtoken = matches[1] + matches[2] + "n" + matches[3]; } } if (subfield) { subtokens[subfield-1] = newtoken; newtoken = subtokens.join(" "); } // console.log("OLDTOKEN", token, "NEWTOKEN", newtoken); if (newtoken !== token) { RestoreCursorNote = id; HIGHLIGHTQUERY = id; setEditorContents(line, field, newtoken, id); } } function toggleStaccato(id, line, field) { console.warn("TOGGLING STACCATO AT ID", id); var counter = 0; var maxline = EDITOR.session.getLength(); var i = line; var freezeBackup = FreezeRendering; FreezeRendering = true; var target = InterfaceSingleNumber; if (!target) { target = 1; } while ((line < maxline) && (counter < target)) { var token = getEditorContents(line, field); if (token.match(/^\*/) || token.match(/^=/) || token.match(/^!/) || (token === "")) { line++; continue; } if (token === ".") { // nothing to do, just a null data token line++; continue; } if (token.match("r")) { // not a note line++; continue; } if (!token.match("'")) { // add staccato token = token.replace(/'+/, ""); token = token.replace(/([a-gA-G]+[-#nXxYy<>]*)/g, function(str,p1) { return p1 ? p1 + "'" : str}); RestoreCursorNote = id; setEditorContents(line, field, token, id); counter++; line++; } else { // remove staccato token = token.replace(/'[<>]*/g, ""); RestoreCursorNote = id; setEditorContents(line, field, token, id); counter++; line++; } } InterfaceSingleNumber = 0; FreezeRendering = freezeBackup; displayNotation(); } function toggleAccent(id, line, field) { var counter = 0; var maxline = EDITOR.session.getLength(); var i = line; var freezeBackup = FreezeRendering; FreezeRendering = true; var target = InterfaceSingleNumber; if (!target) { target = 1; } while ((line < maxline) && (counter < target)) { var token = getEditorContents(line, field); if (token.match(/^\*/) || token.match(/^=/) || token.match(/^!/) || (token === "")) { line++; continue; } if (token === ".") { // nothing to do, just a null data token line++; continue; } if (token.match("r")) { // not a note line++; continue; } if (!token.match(/\^+/)) { // add accent token = token.replace(/\^+/, ""); token = token.replace(/([a-gA-G]+[-#nXxYy<>]*)/, function(str,p1) { return p1 ? p1 + "^" : str}); RestoreCursorNote = id; setEditorContents(line, field, token, id); counter++; line++; } else { // remove accent token = token.replace(/\^+[<>]*/g, ""); RestoreCursorNote = id; setEditorContents(line, field, token, id); counter++; line++; } } InterfaceSingleNumber = 0; FreezeRendering = freezeBackup; displayNotation(); } function toggleMarcato(id, line, field) { var counter = 0; var maxline = EDITOR.session.getLength(); var i = line; var freezeBackup = FreezeRendering; FreezeRendering = true; var target = InterfaceSingleNumber; if (!target) { target = 1; } while ((line < maxline) && (counter < target)) { var token = getEditorContents(line, field); if (token.match(/^\*/) || token.match(/^=/) || token.match(/^!/) || (token === "")) { line++; continue; } if (token === ".") { // nothing to do, just a null data token line++; continue; } if (token.match("r")) { // not a note line++; continue; } if (!token.match(/\^+/)) { // add marcato token = token.replace(/\^+/, ""); token = token.replace(/([a-gA-G]+[-#nXxYy<>]*)/, function(str,p1) { return p1 ? p1 + "^^" : str}); RestoreCursorNote = id; setEditorContents(line, field, token, id); counter++; line++; } else { // remove marcato token = token.replace(/\^+[<>]*/g, ""); RestoreCursorNote = id; setEditorContents(line, field, token, id); counter++; line++; } } InterfaceSingleNumber = 0; FreezeRendering = freezeBackup; displayNotation(); } function toggleTenuto(id, line, field) { var counter = 0; var maxline = EDITOR.session.getLength(); var i = line; var freezeBackup = FreezeRendering; FreezeRendering = true; var target = InterfaceSingleNumber; if (!target) { target = 1; } while ((line < maxline) && (counter < target)) { var token = getEditorContents(line, field); if (token.match(/^\*/) || token.match(/^=/) || token.match(/^!/) || (token === "")) { line++; continue; } if (token === ".") { // nothing to do, just a null data token line++; continue; } if (token.match("r")) { // not a note line++; continue; } if (!token.match(/~/)) { // add marcato token = token.replace(/~+/g, ""); token = token.replace(/([a-gA-G]+[-#nXxYy<>]*)/, function(str,p1) { return p1 ? p1 + "~" : str}); RestoreCursorNote = id; setEditorContents(line, field, token, id); counter++; line++; } else { // remove marcato token = token.replace(/~[<>]*/g, ""); RestoreCursorNote = id; setEditorContents(line, field, token, id); setEditorContents(line, field, token, id); counter++; } } InterfaceSingleNumber = 0; FreezeRendering = freezeBackup; displayNotation(); } function toggleStaccatissimo(id, line, field) { var counter = 0; var maxline = EDITOR.session.getLength(); var i = line; var freezeBackup = FreezeRendering; FreezeRendering = true; var target = InterfaceSingleNumber; if (!target) { target = 1; } while ((line < maxline) && (counter < target)) { var token = getEditorContents(line, field); if (token.match(/^\*/) || token.match(/^=/) || token.match(/^!/) || (token === "")) { line++; continue; } if (token === ".") { // nothing to do, just a null data token line++; continue; } if (token.match("r")) { // not a note line++; continue; } if (!token.match(/`/)) { // add marcato token = token.replace(/`/g, ""); token = token.replace(/([a-gA-G]+[-#nXxYy<>]*)/, function(str,p1) { return p1 ? p1 + "`" : str}); RestoreCursorNote = id; setEditorContents(line, field, token, id); counter++; line++; } else { // remove marcato token = token.replace(/`[<>]*/g, ""); RestoreCursorNote = id; setEditorContents(line, field, token, id); counter++; line++; } } InterfaceSingleNumber = 0; FreezeRendering = freezeBackup; displayNotation(); } function toggleGraceNoteType(id, line, field) { var token = getEditorContents(line, field); var subtokens = token.split(" "); for (var i=0; i]*)/, function(str,p1) { return p1 ? p1 + "t" : str}); RestoreCursorNote = id; setEditorContents(line, field, token, id); } else if (token.match(/T/)) { // change to major-second trill token = token.replace(/T/g, "t"); RestoreCursorNote = id; setEditorContents(line, field, token, id); } else { // remove trill token = token.replace(/T[<>]*/gi, ""); RestoreCursorNote = id; setEditorContents(line, field, token, id); } } function toggleMordent(mtype, id, line, field, subfield) { console.log("TOGGLE MORDENT", token, line, field, subfield, id); var token = getEditorContents(line, field); if ((token === ".") || (token[0] == "!") || (token[0] == "*")) { return; } if (subfield) { var subtokens = token.split(" "); token = subtokens[subfield-1]; } if (token.match("r")) { // reset, so no mordent allowed return; } var newtoken = ""; var matches; var matches = token.match(/[MmWw]/); var hasmordent = false; if (matches) { hasmordent = true; } var hascurrentmordent = false; if (hasmordent) { var re2 = new RegExp(mtype); if (re2.exec(token)) { hascurrentmordent = true; } } if (hascurrentmordent) { // remove existing mordent newtoken = token.replace(/[MmWw][<>]*/g, ""); } else if (hasmordent) { // change the current mordent to the new one newtoken = token.replace(/[MmWw]/g, mtype); } else { // add the given mordent newtoken = token + mtype; } if (subfield) { subtokens[subfield-1] = newtoken; newtoken = subtokens.join(" "); } // console.log("OLDTOKEN", token, "NEWTOKEN", newtoken); if (newtoken !== token) { RestoreCursorNote = id; HIGHLIGHTQUERY = id; setEditorContents(line, field, newtoken, id); } } function toggleLigatureStart(id, line, field) { var addline = true; var ptext = EDITOR.session.getLine(line); if (ptext.match(/^\*/) && ptext.match(/\*lig/)) { // if there is an lig line don't add one addline = false; } if (!addline) { // Already a line with one or more *lig exists. Toggle *lig on/off // for given field and delete line if only contains * tokens. let oldline = EDITOR.session.getLine(line); oldline = oldline.replace(/\t+$/, "").replace(/^\t+/, ""); let fields = oldline.split(/\t+/) if (fields[field-1] === "*") { fields[field-1] = "*lig"; } else { fields[field-1] = "*"; } let newline = fields.join("\t"); if (newline.match(/^[*\t]+$/)) { // blank line so delete it console.log("DELETING BLANK LINE"); EDITOR.session.replace(new Range(line-2, 0, line-1, 0), ""); newid = id.replace(/L\d+/, "L" + (line-1)); RestoreCursorNote = newid; HIGHLIGHTQUERY = newid; } else { // update line console.log("UPDATING LINE:", newline); newline += "\n"; EDITOR.session.replace(new Range(line, 0, line+1, 0), newline); var newid = id; RestoreCursorNote = newid; HIGHLIGHTQUERY = newid; } } else { // Add an *lig on a line after the selected line at the given field. let oldline = EDITOR.session.getLine(line-1); oldline = oldline.replace(/\t+$/, "").replace(/^\t+/, ""); let fields = oldline.split(/\t+/) let fieldcount = fields.length; let newline = ""; for (let i=0; i]*)/, function(str,p1) { return p1 ? p1 + "T" : str}); RestoreCursorNote = id; setEditorContents(line, field, token, id); } else if (token.match(/t/)) { // switch to major second trill token = token.replace(/t/g, "T"); RestoreCursorNote = id; setEditorContents(line, field, token, id); } else { // remove trill token = token.replace(/T[<>]*/gi, ""); RestoreCursorNote = id; setEditorContents(line, field, token, id); } } function toggleArpeggio(id, line, field) { var token = getEditorContents(line, field); if (token === ".") { // nothing to do, just a null data token return; } if (token.match("r")) { // not a note return; } if (!token.match(/:/i)) { // add arpeggio token = token.replace(/:/gi, ""); token = token.replace(/([a-gA-G]+[-#nXxYy<>]*)/g, function(str,p1) { return p1 ? p1 + ":" : str}); RestoreCursorNote = id; setEditorContents(line, field, token, id); } else { // remove arpeggio token = token.replace(/:/gi, ""); RestoreCursorNote = id; setEditorContents(line, field, token, id); } } function toggleFermata(id, line, field) { console.log("TOGGLING FERMATA"); var token = getEditorContents(line, field); if (token === ".") { // nothing to do, just a null data token return; } if (!token.match(/;/i)) { // add marcato token = token.replace(/;/gi, ""); token = token.replace(/([ra-gA-G]+[-#nXxYy<>]*)/, function(str,p1) { return p1 ? p1 + ";" : str}); RestoreCursorNote = id; setEditorContents(line, field, token, id); } else { // remove marcato token = token.replace(/;[<>]*/gi, ""); RestoreCursorNote = id; setEditorContents(line, field, token, id); } } function toggleVisibility(id, line, field) { var token = getEditorContents(line, field); if (token === ".") { // nothing to do, just a null data token return; } if (token.match(/yy/)) { // token is invisible, so make it visible again. token = token.replace(/yy/, ""); RestoreCursorNote = id; setEditorContents(line, field, token, id); } else { // make token invisible (deal with chords later) token = token + "yy"; RestoreCursorNote = id; setEditorContents(line, field, token, id); } } function setEditorContents(line, field, token, id, dontredraw) { var freezeBackup = FreezeRendering; if (FreezeRendering == false) { FreezeRendering = true; } var i; var linecontent = EDITOR.session.getLine(line-1); var range = new Range(line-1, 0, line-1, linecontent.length); var components = linecontent.split(/\t+/); components[field-1] = token; // count tabs between fields var tabs = []; for (i=0; i 1) { var tabcount = 0; for (i=0; i 0) && (linecontent[i-1] != '\t')) { tabcount++; } } if (tabcount == field - 1) { break; } } } for (var c=col; c= lineNumber) { // cursorPosition.row += 1; // } EDITOR.moveCursorToPosition(location); } function addSystemBreakToPreviousBarline() { let location = EDITOR.getCursorPosition(); let index = location.row; var contents = getTextFromEditor().split(/\r?\n/); let barIndex = -1; for (let i=index; i>=1; i--) { if (contents[i].match(/^=/)) { barIndex = i; break; } } if (barIndex < 1) { return; } console.warn("LO", contents[barIndex - 1]); if (contents[barIndex-1].match(/^!!LO:[LP]B:/)) { // Remove system break line var Range = ace.require("ace/range").Range; var range = new Range(barIndex-1, 0, barIndex, 0); EDITOR.session.remove(range); location.row--; EDITOR.moveCursorToPosition(location); return; } let text = "!!LO:LB:g=original"; let textIndex = barIndex - 1; EDITOR.session.insert({ row: textIndex + 1, column: 0 }, text + '\n'); location.row++; EDITOR.moveCursorToPosition(location); } function createNullLine(token, textline) { var newline = ""; if (textline[0] == '\t') { newline += '\t'; } else { newline += token; } var i; for (i=1; i g[id^='note']"; selector += ", #" + pid + " > g[id^='rest']"; selector += ", #" + pid + " > g[id^='chord']"; var children = parent.querySelectorAll(selector); var targeti = -1; for (var i=0; i g[id^='note']"; selector += ", #" + pid + " > g[id^='rest']"; selector += ", #" + pid + " > g[id^='chord']"; var children = parent.querySelectorAll(selector); var targeti = -1; for (var i=0; i]?/g, ""); setEditorContents(line, field, token, id, true); } function addBeamStart(element) { if (!element) { return; } var id = element.id; var matches = id.match(/[^-]+-.*L(\d+).*F(\d+)/); if (!matches) { return; } var line = parseInt(matches[1]); var field = parseInt(matches[2]); var token = getEditorContents(line, field).replace(/[LJKk]+[<>]?/g, ""); token += 'L'; setEditorContents(line, field, token, id, true); } function addBeamEnd(element) { if (!element) { return; } var id = element.id; var matches = id.match(/[^-]+-.*L(\d+).*F(\d+)/); if (!matches) { return; } var line = parseInt(matches[1]); var field = parseInt(matches[2]); var token = getEditorContents(line, field).replace(/[LJKk]+[<>]?/g, ""); token += 'J'; setEditorContents(line, field, token, id, true); } // Functions related to repertory indexes: // // Programmer: Craig Stuart Sapp // Creation Date: Thu Jun 21 16:07:56 PDT 2018 // Last Modified: Thu Jun 21 16:08:01 PDT 2018 // Filename: hmdindex.js // Web Address: https://verovio.humdrum.org/scripts/hmdindex.js // Syntax: JavaScript 1.8/ECMAScript 5 // vim: ts=3: ft=javascript // // Description: Parse an index.hmd file giving the contents of a repertory. // ////////////////////////////// // // HMDIndex constructor -- Creat an HMDIndex object. // function HMDIndex(contents) { this.clear(); this.parse(contents); return this; } ////////////////////////////// // // HMDIndex.prototype.clear -- Clear the old contents of the index // HMDIndex.prototype.clear = function() { // parameters == list of key/value pairs extracted from // Humdrum reference records in the input Humdurm data. this.parameters = {}; // items == list of files, groups, or dummy/dummy-vhv lines stored // on data lines in the input Humdrum data. These are // sorted by the sortkey field after loading the data. this.items = []; // groupedItems == database of sortkey values for entries // that are in groups (movements of a larger work). this.groupedItems = {}; // sortIndex == database of entries indexed by sortkey value. this.sortIndex = {}; }; ////////////////////////////// // // HMDIndex.prototype.setParameter -- Set a parameter. // HMDIndex.prototype.setParameter = function(key, value) { this.parameters[key] = value; }; ////////////////////////////// // // HMDIndex.prototype.getParameter -- Get a parameter. // HMDIndex.prototype.getParameter = function(key) { return this.parameters[key]; }; ////////////////////////////// // // HMDIndex.prototype.parse -- Parse the contents of a Humdrum // file containing and index of works and store them in the // object. // HMDIndex.prototype.parse = function(contents) { this.clear(); var exfound = 0; var index = {}; var lines = contents.match(/[^\r\n]+/g); if (lines.length == 1) { if (lines[0].match(/^https?:\/\//)) { return this.parseURL(lines[0]); } } var entry; for (var i = 0; i b.sortkey) { return 1; } else { return 0; } }); }; ////////////////////////////// // // HMDIndex.prototype.parseURL -- // HMDIndex.prototype.parseURL = function(url) { var that = this; var request = new XMLHttpRequest(); request.open("GET", url); request.onload = function() { if (request.status == 200) { that.parse(request.responseText); } else { reject("ERROR:", request.status); } } request.send(); }; ////////////////////////////// // // HMDIndex.prototpye.addEntry -- // HMDIndex.prototype.addEntry = function(object) { var filename = object.filename; var sortkey = object.sortkey; var available = object.available; var pdfname = object.pdfname; var description = cleanTitle(object.description); var matches; if ((!filename) || filename === ".") { // require filename at a minimum return; } if ((!available) || available === ".") { available = "Y"; } if ((available !== "Y") && (available !== "N")) { if (available.match(/y/i)) { available = "Y"; } else { available = "N"; } } if (!available) { available = "Y"; } if ((!sortkey) || (sortkey === ".")) { sortkey = filename; } if ((!pdfname) || (pdfname === ".")) { pdfname = ""; } if ((!description) || (description === ".")) { description = filename; } // split the filename into directory, basename, and extension: var directory = ""; var basename = ""; var extension = ""; var obj = { sortkey: sortkey, description: description, pdfname: pdfname }; // THERE IS ALSO filename === "DUMMY" to implement. if (filename.match(/^@/)) { // this is a group, not a filename. The group is a list // of sortkeys of the items that form the group. obj.group = filename.replace(/^@/, "").split(":"); for (var i=0; i(.*?)<\/link>(.*)/); var prefix = ""; var postfix = ""; if (matches) { prefix = matches[1]; postfix = matches[3]; description = matches[2]; } if (description.match(/^\s*$/)) { description = entry.file.basename; } if (indent) { output += ""; } output += prefix; output += " 0) { return output; } } // In the data was loaded from a repertory file, then use that // file as the filename base. if (FILEINFO) { if (FILEINFO.file) { output = FILEINFO.file; output = output.replace(/.*\//, "").replace(/\..*?$/, ""); if (output.length > 0) { return output; } } } return "data"; } ////////////////////////////// // // getFilenameExtension -- // function getFilenameExtension(text) { if (!text) { text = getTextFromEditorRaw(); } if (!text) { return "txt"; } var beginning = text.substring(0, 1000).replace(/^\s+/, ""); if (beginning.match(/ 0)) { return ext; } } } if (FILEINFO) { if (FILEINFO.file) { fullname = FILEINFO.file.replace(/.*\//, ""); ext = fullname.replace(/.*\./, ""); if (ext && (ext.length > 0)) { return ext; } } } return "krn"; } if (beginning.match(/group memberships:/i)) { // MuseData return ".msd"; } return "txt"; } ////////////////////////////// // // dataIsHumdrum -- Returns true if the input text (or text from // the editor if no text given as input) is Humdrum data or not. // function dataIsHumdrum(data) { if (!data) { data = getTextFromEditor(); } if (data.match(/^\s*[!*]/)) { return true; } else { return false; } } ////////////////////////////// // // dataIsXml -- Returns true if the input text (or text from // the editor if no text given as input) is XML data or not. // function dataIsXml(data) { if (!data) { data = getTextFromEditor(); } if (data.match(/^\s*<\?xml\b/)) { return true; } else { return false; } } ////////////////////////////// // // trimTabs -- also removes blank lines and tabs from inside of reference records. // function trimTabs(data) { var lines = data.split(/\r?\n/); var output = ""; for (var i=0; i> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); } return output; }, // public method for decoding decode : function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = this._keyStr.indexOf(input.charAt(i++)); if (i < input.length) { enc2 = this._keyStr.indexOf(input.charAt(i++)); } else { enc2 = 64; } if (i < input.length) { enc3 = this._keyStr.indexOf(input.charAt(i++)); } else { enc3 = 64; } if (i < input.length) { enc4 = this._keyStr.indexOf(input.charAt(i++)); } else { enc4 = 64; } chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } output = Base64._utf8_decode(output); return output; }, // private method for UTF-8 encoding _utf8_encode : function (string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }, // private method for UTF-8 decoding _utf8_decode : function (utftext) { var string = ""; var i = 0; var c = c1 = c2 = 0; while ( i < utftext.length ) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } } ////////////////////////////// // // convertDataToTsv -- // function convertDataToTsv(lines) { var output = ""; for (var i=0; i= 2) && (chars[0] == '!') && (chars[1] == '!')) { // Global commands and reference records which do not start with a // quote are considered to be literal. return line; } var separator = ","; for (var i=0; i=0; i--) { if (!lines[i].match(/!|@/)) { continue; } if (matches = lines[i].match(regex1)) { let key = matches[1]; let value = matches[2]; output[key] = value; if (matches = key.match(/(.*)@@(.*)/)) { output[matches[1]] = value; } if (matches = key.match(/(.*)@(.*)/)) { output[matches[1]] = value; } } if (matches = lines[i].match(query2)) { output["title"] = matches[1]; } } if ((!output["title"]) || output["title"].match(/^\s*$/)) { output["title"] = FILEINFO["title-expansion"]; } let counter = 0; let prefix = ""; let postfix = ""; let substitute; if (output["title"] && !output["title"].match(/^\s*$/)) { let pattern = output["title"]; while (matches = pattern.match(/@\{([^\}]*)\}/)) { prefix = ""; postfix = ""; key = ""; if (matches = pattern.match(/@\{([^\}]*)\}\{([^\}]*)\}\{([^\}]*)\}/)) { prefix = matches[1]; key = matches[2]; postfix = matches[3]; pattern = pattern.replace(/@\{([^\}]*)\}\{([^\}]*)\}\{([^\}]*)\}/, "ZZZZZ"); } else if (matches = pattern.match(/@\{([^\}]*)\}\{([^\}]*)\}/)) { prefix = matches[1]; key = matches[2]; postfix = ""; pattern = pattern.replace(/@\{([^\}]*)\}\{([^\}]*)\}/, "ZZZZZ"); } else if (matches = pattern.match(/@\{([^\}]*)\}/)) { prefix = ""; key = matches[1]; postfix = ""; pattern = pattern.replace(/@\{([^\}]*)\}/, "ZZZZZ"); } if (!key) { break; } if (key.match(/^\s*$/)) { break; } if (output[key]) { substitute = prefix + output[key] + postfix; } else { substitute = ""; } pattern = pattern.replace(/ZZZZZ/, substitute); counter++; if (counter > 20) { // avoid infinite loop in case something goes wrong break; } } output["title"] = pattern; } return output; } ////////////////////////////// // // getStaffCount -- Return the number of **kern or **mens spines in the data. // function getStaffCount(data) { let output = 0; let lines = data.split(/\r?\n/); for (let i=0; i 0) { kcount = 0; } output = mcount + kcount; break; } return output; } ////////////////////////////// // // diatonicToHumdrum -- // function diatonicToHumdrum(pitch) { pitch = parseInt(pitch); let octave = parseInt(pitch / 7); let pc = pitch % 7; let pchar = "x"; if (pc == 0) { pchar = "c"; } else if (pc == 1) { pchar = "d"; } else if (pc == 2) { pchar = "e"; } else if (pc == 3) { pchar = "f"; } else if (pc == 4) { pchar = "g"; } else if (pc == 5) { pchar = "a"; } else if (pc == 6) { pchar = "b"; } let i; let count; let output = ""; if (octave < 4) { pchar = pchar.toUpperCase(); count = 4 - octave; for (i=0; i= 70) { // to high to process or mean anything return pitch; } return diatonicToHumdrum(pitchnum); } ////////////////////////////// // // getFieldAndSubtoken -- Return the data token and subtoken position // of the item at the given column on the line (column is index from 0), // but token and subtoken are indexed from 1. // function getFieldAndSubtoken(text, column) { // column++; // needed for some reason? let output = {field: -1, subspine: -1}; if (text.match(/^[*!=]/)) { return output; } if (text == "") { return output; } let field = 0; let subspine = 0; let i; for (i=0; i 0) && (text[i] == '\t') && (text[i-1] != '\t')) { field++; subspine = 0; } else if (text[i] == ' ') { subspine++; } } let subtok = false; // check if the field contains subtokens. If so, set the if (subspine > 0) { subtok = true; } else { for (i=column; i=0; i--) { if (size - i > limit) { break; } let line = EDITOR.session.getLine(i); if (matches = line.match(/^!!!RDF\*\*kern:\s+([^\s])\s*=.*mark.*\s+note/)) { editchar = matches[1]; } if (editchar !== "") { break; } } if (editchar === "") { for (i=0; i limit) { break; } let line = EDITOR.session.getLine(i); if (matches = line.match(/^\!\!\!RDF\*\*kern:\s+([^\s])\s*=.*mark.*\s+note/)) { editchar = matches[1]; } if (editchar !== "") { break; } } } if (editchar !== "") { return editchar; } let text = ""; if (editchar === "") { text += "!!!RDF**kern: @ = marked note"; editchar = "@"; } else { text += "!!!RDF**kern: " + editchar + " = marked note"; } // append markers to end of file. let freezeBackup = FreezeRendering; if (FreezeRendering == false) { FreezeRendering = true; } EDITOR.session.insert({ row: EDITOR.session.getLength(), column: 0 }, "\n" + text); FreezeRendering = freezeBackup; return editchar; } ////////////////////////////// // // insertDirectionRdfs -- If not present, insert above/below RDF markers // in data; otherwise returns what chatacters should represent "above" // and "below". Typically ">" means "above" and "<" means "below". // also can be used to check if "<" or ">" are already used for // something else. // function insertDirectionRdfs() { let limit = 20; // search only first and last 20 lines of data for RDF entries. let abovechar = ""; let belowchar = ""; let matches; let i; let size = EDITOR.session.getLength(); for (i=size-1; i>=0; i--) { if (size - i > limit) { break; } let line = EDITOR.session.getLine(i); if (matches = line.match(/^!!!RDF\*\*kern:\s+([^\s])\s*=.*above/)) { abovechar = matches[1]; } else if (matches = line.match(/^!!!RDF\*\*kern:\s+([^\s])\s*=.*below/)) { belowchar = matches[1]; } if ((abovechar !== "") && (belowchar !== "")) { break; } } if ((abovechar === "") || (belowchar === "")) { for (i=0; i limit) { break; } let line = EDITOR.session.getLine(i); if (matches = line.match(/^\!\!\!RDF\*\*kern:\s+([^\s])\s*=.*above/)) { abovechar = matches[1]; } else if (matches = line.match(/^\!\!\!RDF\*\*kern:\s+([^\s])\s*=.*below/)) { belowchar = matches[1]; } if ((abovechar !== "") && (belowchar !== "")) { break; } } } if ((abovechar !== "") && (belowchar !== "")) { return [abovechar, belowchar]; } let text = ""; if (abovechar === "") { text += "!!!RDF**kern: > = above\n"; abovechar = ">"; } else { text += "!!!RDF**kern: " + abovechar + " = above\n"; } if (belowchar === "") { text += "!!!RDF**kern: < = below"; belowchar = "<"; } else { text += "!!!RDF**kern: " + belowchar + " = below"; } // append markers to end of file. let freezeBackup = FreezeRendering; if (FreezeRendering == false) { FreezeRendering = true; } EDITOR.session.insert({ row: EDITOR.session.getLength(), column: 0 }, "\n" + text); FreezeRendering = freezeBackup; return [abovechar, belowchar]; } ////////////////////////////// // // insertEditorialAccidentalRdf -- If not present, insert editorial accidental // RDF marker in data; otherwise returns what chatacters should represent // an editorial accidental. // function insertEditorialAccidentalRdf() { let limit = 20; // search only first and last 20 lines of data for RDF entries. let editchar = ""; let matches; let i; let size = EDITOR.session.getLength(); for (i=size-1; i>=0; i--) { if (size - i > limit) { break; } let line = EDITOR.session.getLine(i); if (matches = line.match(/^!!!RDF\*\*kern:\s+([^\s])\s*=.*edit.*\s+acc/)) { editchar = matches[1]; } if (editchar !== "") { break; } } if (editchar === "") { for (i=0; i limit) { break; } let line = EDITOR.session.getLine(i); if (matches = line.match(/^\!\!\!RDF\*\*kern:\s+([^\s])\s*=.*edit.*\s+acc/)) { editchar = matches[1]; } if (editchar !== "") { break; } } } if (editchar !== "") { return editchar; } let text = ""; if (editchar === "") { text += "!!!RDF**kern: i = editorial accidental\n"; editchar = "i"; } else { text += "!!!RDF**kern: " + editchar + " = editorial accidental\n"; } // append markers to end of file. let freezeBackup = FreezeRendering; if (FreezeRendering == false) { FreezeRendering = true; } EDITOR.session.insert({ row: EDITOR.session.getLength(), column: 0 }, "\n" + text); FreezeRendering = freezeBackup; return editchar; } // Functions related to svg manipulation: ////////////////////////////// // // goDownHarmonically -- // function goDownHarmonically(current) { moveHarmonically(current, -1); } ////////////////////////////// // // goUpHarmonically -- Move up harmonically in the SVG score. // function goUpHarmonically(current) { moveHarmonically(current, +1); } ////////////////////////////// // // moveHarmonically -- Move up (+1) or down (-1) harmonically in the SVG score. // Go to the next chord note or voice on the same staff, or go to the next // higher staff. If at the top of the top staff, then wrap around to the bottom // chord of the bottom voice of the bottom staff in the system. // function moveHarmonically(current, direction) { if (!current) { return; } var startid = current.id; var nextid = getNextHarmonicNote(startid, direction) if (!nextid) { return; } unhighlightCurrentNote(current); highlightIdInEditor(nextid, "moveHarmonically"); } ////////////////////////////// // // inSvgImage -- Used to prevent processing clicks in the text // editor for the click event listener used in the SVG image. // Returns true if the node is inside of an SVG image, or // false otherwise. // function inSvgImage(node) { var current = node; while (current) { if (current.nodeName === "svg") { return true; } current = current.parentNode; } return false; } ////////////////////////////// // // observeSVGContent -- // function observeSvgContent() { var content = document.querySelector("#output"); var i; var s; var callback = function(mList, observer) { var svg = content.querySelector("svg"); if (svg) { // Mark encoding problem messages with red caution symbol. spans = svg.querySelectorAll("g.dir.problem tspan.rend tspan.text tspan.text"); for (i=0; i bstaff) { return -1; } if (astaff < bstaff) { return +1; } if (alayer > blayer) { return -1; } if (alayer < blayer) { return +1; } // notes are in a chord so sort by pitch from low to high var match; var aoct = 0; var boct = 0; var ab40 = 0; var bb40 = 0; if (match = a.className.baseVal.match(/oct-(-?\d+)/)) { aoct = parseInt(match[1]); } if (match = b.className.baseVal.match(/oct-(-?\d+)/)) { boct = parseInt(match[1]); } if (match = a.className.baseVal.match(/b40c-(\d+)/)) { ab40 = aoct * 40 + parseInt(match[1]); } if (match = b.className.baseVal.match(/b40c-(\d+)/)) { bb40 = boct * 40 + parseInt(match[1]); } if (ab40 < bb40) { return -1; } if (ab40 > bb40) { return +1; } return 0; }); if (harmonic.length == 1) { // nothing to do return undefined; } for (var j=0; j= harmonic.length) { index = 0; } return harmonic[index].id; } ////////////////////////////// // // unhighlightCurrentNote -- // function unhighlightCurrentNote(element) { if (element) { var classes = element.getAttribute("class"); var classlist = classes.split(" "); var outclass = ""; for (var i=0; i0; i--) { if (!staffelements[i]) { continue; } if (staffelements[i].id) { if (staffelements[i].id.match(/space/)) { continue; } } return staffelements[i].id; } // find a note/rest in a higher layer for (i=targetlayer; i0; i--) { if (!staffelements[i]) { continue; } return staffelements[i].id; } // find a note/rest in a higher layer for (i=targetlayer; i elemnet within a // measure. // function getStaffPosition(element) { var count = 0; var current = element; while (current) { if (current.className.baseVal.match(/staff/)) { count++; } current = current.previousElementSibling; } return count; } ////////////////////////////// // // getLayerPosition -- Return the nth position of a elemnet within a // staff. // function getLayerPosition(element) { var count = 0; var current = element; while (current) { if (current.className.baseVal.match(/layer/)) { count++; } current = current.previousElementSibling; } return count; } ////////////////////////////// // // getStaffAndLayerNumbers -- Return the staff and layer number of the // location of the given id's element. The layer and staff numbers // are zero indexed to match MEI's enumeration (but this is not // necessary). // function getStaffAndLayerNumbers(id) { var element = document.querySelector("#" + id); return getStaffAndLayerNumbersByElement(element); } function getStaffAndLayerNumbersByElement(element) { if (!element) { return {}; } var id = element.id; var staff = 0; var layer = 0; var current = element; current = current.parentNode; while (current && current.className.baseVal) { // console.log("CURRENT", current.className.baseVal); if (current.className.baseVal.match(/layer/)) { layer = getLayerPosition(current); } else if (current.className.baseVal.match(/staff/)) { staff = getStaffPosition(current); } current = current.parentNode; } return { layer: layer, staff: staff } } ////////////////////////////// // // getOffClassElements -- // function getOffClassElements(offclass) { var nlist = document.querySelectorAll("." + offclass); var rlist = document.querySelectorAll(".r" + offclass); var alist = []; for (var i=0; i 0) && (vrvWorker.pageCount == vrvWorker.page)) { // at last page, so don't do anything. // console.log("AT LAST PAGE, so not continuing further"); return; } vrvWorker.gotoPage(vrvWorker.page + 1) .then(function(obj) { // loadPage(vrvWorker.page); var page = obj.page || vrvWorker.page; $("#overlay").hide().css("cursor", "auto"); $("#jump_text").val(page); vrvWorker.renderPage(page) .then(function(svg) { $("#output").html(svg); // adjustPageHeight(); // resizeImage(); }) .then(function() { alist = getOnClassElements(onclass); if (alist.length == 1) { highlightIdInEditor(alist[0].id, "goToNextNoteOrRest2"); } else { nextid = chooseBestId(alist, location.staff, location.layer); if (nextid) { EDITINGID = nextid; highlightIdInEditor(nextid, "goToNextNoteOrRest3"); } } }); }); } else { nextid = chooseBestId(alist, location.staff, location.layer); if (nextid) { EDITINGID = nextid; highlightIdInEditor(nextid, "goToNextNoteOrRest4"); } } } ////////////////////////////// // // toggleAppoggiaturaColoring -- turn appoggiatura color highlighting on/off. // function toggleAppoggiaturaColoring() { var sylesheet; stylesheet = document.querySelector("#appoggiatura-color-stylesheet"); if (stylesheet) { var parentElement = stylesheet.parentNode; parentElement.removeChild(stylesheet); return; } stylesheet = document.createElement('style'); var text = ""; text += "g.appoggiatura-start { fill: limegreen; }"; text += "g.appoggiatura-stop { fill: forestgreen; }"; stylesheet.innerHTML = text; stylesheet.id = "appoggiatura-color-stylesheet"; document.body.appendChild(stylesheet); } ////////////////////////////// // // toggleCautionaryAccidentalColoring -- // function toggleCautionaryAccidentalColoring() { var sylesheet; stylesheet = document.querySelector("#cautionary-accidental-color-stylesheet"); if (stylesheet) { var parentElement = stylesheet.parentNode; parentElement.removeChild(stylesheet); return; } stylesheet = document.createElement('style'); var text = ""; text += "g.accid.caution[id^='accid-'] { fill: hotpink; }\n"; stylesheet.innerHTML = text; stylesheet.id = "cautionary-accidental-color-stylesheet"; document.body.appendChild(stylesheet); } ////////////////////////////// // // toggleLayerColoring -- turn layer color highlighting on/off. // function toggleLayerColoring() { var sylesheet; stylesheet = document.querySelector("#layer-color-stylesheet"); if (stylesheet) { var parentElement = stylesheet.parentNode; parentElement.removeChild(stylesheet); return; } stylesheet = document.createElement('style'); var text = ""; text += "g[id^='layer-'][id*='N2'] { fill: #00cc00; }\n"; text += "g[id^='layer-'][id*='N3'] { fill: #cc00aa; }\n"; text += "g[id^='layer-'][id*='N4'] { fill: #0088cc; }\n"; text += "g[id^='layer-'][id*='N5'] { fill: #0000cc; }\n"; text += "g[id^='layer-'][id*='N6'] { fill: #cc0000; }\n"; text += "g[id^='layer-'][id*='N7'] { fill: #00cc00; }\n"; // Disable highlighting of clefs in layers: text += "g.clef { fill: black !important; }"; stylesheet.innerHTML = text; stylesheet.id = "layer-color-stylesheet"; document.body.appendChild(stylesheet); } ////////////////////////////// // // togglePlaceColoring -- turn explicitly placed item highlighting on/off. // function togglePlaceColoring() { var sylesheet; stylesheet = document.querySelector("#placed-color-stylesheet"); if (stylesheet) { var parentElement = stylesheet.parentNode; parentElement.removeChild(stylesheet); return; } stylesheet = document.createElement('style'); var text = "g.placed { fill: orange; } "; text += "g.placed path { stroke: orange; } "; stylesheet.innerHTML = text; stylesheet.id = "placed-color-stylesheet"; document.body.appendChild(stylesheet); } /////////////////////////////////// // // restoreSelectedSvgElement -- Need to generalize to multiple pages. // function restoreSelectedSvgElement(id) { if (!id) { return; } var item = document.querySelector("#" + id); if (!item) { return; } var line; var matches = id.match(/L(\d+)/); if (matches) { line = parseInt(line); } else { return; } markItem(item, line); } ////////////////////////////// // // markItem -- Used by highlightNoteInScore. // function markItem(item, line) { if (!item) { item = CursorNote; } if (!item) { return; } EditorLine = line; // This case is not good for editing a note: //if (CursorNote && item && (CursorNote.id == item.id)) { // console.log("THE SAME NOTE"); // return; //} if (CursorNote) { // console.log("TURNING OFF OLD NOTE", CursorNote); /// CursorNote.setAttribute("fill", "#000"); // CursorNote.removeAttribute("fill"); var classes = CursorNote.getAttribute("class"); var classlist = classes.split(" "); var outclass = ""; for (var i=0; i 1) { var tabcount = 0; for (i=0; i 0) && (linecontent[i-1] != '\t')) { tabcount++; } } if (tabcount == field - 1) { break; } } } if (subtoken >= 1) { var scount = 1; while ((col < linecontent.length) && (scount < subtoken)) { col++; if (linecontent[col] == " ") { scount++; if (scount == subtoken) { col++; break; } } } } col2 = col; var searchstring = linecontent[col2]; while (col2 < linecontent.length) { col2++; if (linecontent[col2] == " ") { break; } else if (linecontent[col2] == "\t") { break; } else { searchstring += linecontent[col2]; } } CursorNote = document.querySelector("#" + id); MENU.showCursorNoteMenu(CursorNote); EDITOR.gotoLine(row, col); // 0.5 = center the cursor vertically: EDITOR.renderer.scrollCursorIntoView({row: row-1, column: col}, 0.5); centerCursorHorizontallyInEditor(); } // Functions related to svg manipulation: ////////////////////////////// // // centerCursorHorizontallyInEditor -- // function centerCursorHorizontallyInEditor() { // Center the cursort horizontally: // Get distance between cursor and left side of textarea in pixels: let cursorLeft = EDITOR.renderer.$cursorLayer.getPixelPosition(0).left; // Get width of visible text area let scrollerWidth = EDITOR.renderer.$size.scrollerWidth; // Move scroller so that left side at same point as cursor minus half width of visible area: if (cursorLeft > scrollerWidth / 2) { EDITOR.renderer.scrollToX(cursorLeft - scrollerWidth/2); } } ////////////////////////////// // // setEditorModeAndKeyboard -- // function setEditorModeAndKeyboard() { if (EDITOR) { EDITOR.setTheme(EditorModes[EditorMode][KeyboardMode].theme); EDITOR.getSession().setMode("ace/mode/" + EditorMode); // null to reset to default (ace) mode EDITOR.setKeyboardHandler(KeyboardMode === "ace" ? null : "ace/keyboard/" + KeyboardMode); } }; ////////////////////////////// // // toggleEditorMode -- Switch between plain text editing and vim editing. // This is used by the alt-v keyboard shortcut. // function toggleEditorMode() { if (KeyboardMode == "ace") { KeyboardMode = "vim"; } else { KeyboardMode = "ace"; }; setEditorModeAndKeyboard(); }; ////////////////////////////// // // showIdInEditor -- Highlight the current line of data being played, // and center it. But only do this if Humdrum data is being shown // in the editor (MEI data is not time-ordered by notes, only by // measure). // function showIdInEditor(id) { if (EditorMode == "xml") { // MusicXML data has no IDs so cannot use this function return; } if (EditorMode == "esac") { // EsAC data has no IDs so cannot use this function return; } var matches = id.match(/-[^-]*L(\d+)/); if (!matches) { return; } var row = parseInt(matches[1]); EDITOR.gotoLine(row, 0); EDITOR.centerSelection(); // console.log("PLAYING ROW", row); } ////////////////////////////// // // getMode -- return the Ace editor mode to display the data in: // ace/mode/humdrum == for Humdrum // ace/mode/esac == for Humdrum // ace/mode/xml == for XML data (i.e., MEI, or SVG) // function getMode(text) { if (!text) { return "humdrum"; } if (text.match(/^\s* 0) { query += "S" + subspine; } } var item = 0; if (Splitter.rightContent) { // see: https://www.w3.org/TR/selectors var items = Splitter.rightContent.querySelectorAll("g[id$='" + query + "']"); if (items.length == 0) { // cannot find (hidden rest for example) return; } // give priority to items that possess qon/qoff classes. for (var i=0; i 1) { let tabcount = 0; for (let i=0; i 0) && (linecontent[i-1] != '\t')) { tabcount++; } } if (tabcount == field - 1) { break; } } } EDITOR.gotoLine(row, col); // 0.5 = center the cursor vertically: EDITOR.renderer.scrollCursorIntoView({row: row-1, column: col}, 0.5); centerCursorHorizontallyInEditor(); } // Splitter prototypes for dealing with split // windowing system for text and notation: /////////////////////////////////////////////////////////////////////////// // // Split window interface: // function SPLITTER() { this.mouseState = 0; this.positionX = null; this.leftContent = null; this.splitContent = null; this.splitWidth = 5; this.minXPos = 100; this.maxXPos = 2000; this.rightPadding = 10; this.defaultPos = 400; this.snapTolerance = 30; return this; } SPLITTER.prototype.setPositionX = function(xPosition) { if ((xPosition < this.defaultPos + this.snapTolerance) && (xPosition > this.defaultPos - this.snapTolerance)){ xPosition = this.defaultPos; } if (xPosition < 0) { xPosition = 0; } if (xPosition > this.maxXPos) { xPosition = this.maxXPos; } this.positionX = xPosition; if (!this.leftContent) { this.leftContent = document.querySelector('#input'); } if (!this.splitContent) { this.splitContent = document.querySelector('#splitter'); } if (!this.rightContent) { this.rightContent = document.querySelector('#output-container'); } if (this.leftContent) { this.leftContent.style.left = 0; this.leftContent.style.width = xPosition + 'px'; } if (this.splitContent) { this.splitContent.style.left = xPosition + 'px'; } if (this.rightContent) { this.rightContent.style.left = (xPosition + this.splitWidth + this.rightPadding) + 'px'; } }; var Splitter = new SPLITTER(); // Functions related to verovio options: let VEROVIOOPTIONS = { "OPTION": [ { "NAME": "stdin", "ABBR": "-", "INFO": "Read input data from standard input.", "CAT": "Base options", "ARG": "string", "CLI_ONLY": "true" }, { "NAME": "help", "ABBR": "h", "INFO": "Display help message or list of options by category.", "CAT": "Base options", "ARG": "string", "DEF": "\"\"", "ALT": [ "base", "general", "layout", "selectors", "margins", "midi", "mensural", "json", "full" ], "CLI_ONLY": "true" }, { "NAME": "allPages", "ABBR": "a", "INFO": "Output all pages.", "CAT": "Base options", "ARG": "boolean", "CLI_ONLY": "true?" }, { "NAME": "inputFrom", "ABBR": "f", "INFO": "Specify input data type (otherwise automatically detected from content).", "CAT": "Base options", "ARG": "string", "DEF": "auto", "ALT": [ "abc", "cmme.xml", "darms", "esac", "humdrum", "mei", "musicxml-hum", "pae", "volpiano", "xml" ] }, { "NAME": "logLevel", "ABBR": "l", "INFO": "Set log level.", "CAT": "Base options", "ARG": "string", "DEF": "warning", "ALT": [ "debug", "error", "info", "off" ] }, { "NAME": "outfile", "ABBR": "o", "INFO": "Output file name (use \"-\" for standard output).", "CAT": "Base options", "ARG": "string" }, { "NAME": "page", "ABBR": "p", "INFO": "Select the page to engrave.", "CAT": "Base options", "ARG": "integer", "DEF": "1", "MIN": "1", "CLI_ONLY": "true" }, { "NAME": "resourcePath", "ABBR": "r", "INFO": "Path to the directory with Verovio resources.", "CAT": "Base options", "ARG": "string", "DEF": "/usr/local/share/verovio", "CLI_ONLY": "true" }, { "NAME": "scale", "ABBR": "s", "INFO": "Size of the output SVG notation.", "CAT": "Base options", "ARG": "integer", "DEF": "100", "MIN": "1", "MAX": "1000" }, { "NAME": "outputTo", "ABBR": "t", "INFO": "Select output data format", "CAT": "Base options", "ARG": "string", "DEF": "svg", "ALT": [ "mei", "mei-pb", "mei-facs", "mei-basic", "midi", "timemap", "expansionmap", "humdrum", "pae" ] }, { "NAME": "version", "ABBR": "v", "INFO": "Display verovio version number.", "CAT": "Base options", "ARG": "boolean", "CLI_ONLY": "true" }, { "NAME": "xmlIdSeed", "ABBR": "x", "INFO": "Seed the random number generator for XML IDs (default is random).", "CAT": "Base options", "ARG": "integer", "MIN": "1", "MAX": "2147483647" }, { "NAME": "adjustPageHeight", "CAT": "Input and page configuration options", "INFO": "Crop page height to visible height of the SVG.", "ARG": "boolean" }, { "NAME": "adjustPageWidth", "CAT": "Input and page configuration options.", "INFO": "Crop page width to visible width of the SVG.", "ARG": "boolean" }, { "NAME": "breaks", "CAT": "Input and page configuration options", "INFO": "Page and system breaks layout for rendered notation.", "ARG": "string", "DEF": "auto", "ALT": [ "encoded", "line", "none", "smart" ] }, { "NAME": "breaksSmartSb", "CAT": "Input and page configuration options", "INFO": "In smart breaks mode, portion of system width usage at which an encoded system break will be used.", "ARG": "float", "DEF": "0.66", "MIN": "0.00", "MAX": "1.00" }, { "NAME": "condense", "INFO": "Control condensed score layout (rules for removing staves on a system that has only rests).", "CAT": "Input and page configuration options", "ARG": "string", "DEF": "auto", "ALT": [ "encoded", "none" ] }, { "NAME": "condenseFirstPage", "CAT": "Input and page configuration options", "INFO": "When condensing a score, also condense the first page.", "ARG": "boolean" }, { "NAME": "condenseNotLastSystem", "CAT": "Input and page configuration options", "INFO": "Do not condense last system.", "ARG": "boolean" }, { "NAME": "condenseTempoPages", "CAT": "Input and page configuration options", "INFO": "When condensing, also condense pages with a tempo change.", "ARG": "boolean" }, { "NAME": "evenNoteSpacing", "CAT": "Input and page configuration options", "INFO": "Align notes and rests without adding duration based space.", "ARG": "boolean" }, { "NAME": "expand", "CAT": "Input and page configuration options", "INFO": "Expand all referenced elements in expanion. Input is an xml:id of the expansion list.", "ARG": "string" }, { "NAME": "footer", "CAT": "Input and page configuration options", "INFO": "Control footer layout", "ARG": "string", "DEF": "auto", "ALT": [ "none", "encoded", "always" ] }, { "NAME": "header", "CAT": "Input and page configuration options.", "INFO": "Control header layout", "ARG": "string", "DEF": "auto", "ALT": [ "none", "encoded" ] }, { "NAME": "humType", "CAT": "Input and page configuration options", "INFO": "Include type attributes when importing rom Humdrum", "ARG": "boolean" }, { "NAME": "incip", "CAT": "Input and page configuration options", "INFO": "Read incip elements as data input", "ARG": "boolean" }, { "NAME": "justifyVertically", "CAT": "Input and page configuration options", "INFO": "Justify spacing vertically to fill a page.", "ARG": "boolean" }, { "NAME": "landscape", "CAT": "Input and page configuration options", "INFO": "Swap values for page height and width.", "ARG": "boolean" }, { "NAME": "minLastJustification", "CAT": "Input and page configuration options", "INFO": "Minimum length of last system which can be stretched to 100% width of page.", "ARG": "float", "DEF": "0.80", "MIN": "0.00", "MAX": "1.00" }, { "NAME": "mmOutput", "CAT": "Input and page configuration options", "INFO": "Use millimeter units in SVG output (default is px).", "ARG": "boolean" }, { "NAME": "moveScoreDefinitionToStaff", "CAT": "Input and page configuration options", "INFO": "Move score definition (clef, keySig, meterSig, etc.) from scoreDef to staffDef.", "ARG": "boolean" }, { "NAME": "neumeAsNote", "CAT": "Input and page configuration options", "INFO": "Render neumes as noteheads instead of original notation.", "ARG": "boolean" }, { "NAME": "noJustification", "CAT": "Input and page configuration options", "INFO": "Do not justify the system (ragged right).", "ARG": "boolean" }, { "NAME": "openControlEvents", "CAT": "Input and page configuration options", "INFO": "Render open control events.", "ARG": "boolean" }, { "NAME": "outputIndent", "CAT": "Input and page configuration options", "INFO": "Output indent value for MEI and SVG.", "ARG": "integer", "DEF": "3", "MIN": "1", "MAX": "10" }, { "NAME": "outputFormatRaw", "CAT": "Input and page configuration options", "INFO": "Output MEI with no line indents or non-content newlines. See svgFormatRaw.", "ARG": "boolean" }, { "NAME": "outputIndentTab", "CAT": "Input and page configuration options", "INFO": "Use tabs rather than spaces for indenting XML output.", "ARG": "boolean" }, { "NAME": "outputSmuflXmlEntities", "CAT": "Input and page configuration options", "INFO": "Output SMuFL characters as XML entities instead of hex byte codes.", "ARG": "boolean" }, { "NAME": "pageHeight", "CAT": "Input and page configuration options", "INFO": "The page height.", "ARG": "integer", "DEF": "2970", "MIN": "100", "MAX": "60000" }, { "NAME": "pageMarginBottom", "CAT": "Input and page configuration options", "INFO": "Page bottom margin", "ARG": "integer", "DEF": "50", "MIN": "0", "MAX": "500" }, { "NAME": "pageMarginLeft", "CAT": "Input and page configuration options", "INFO": "Page left margin.", "ARG": "integer", "DEF": "50", "MIN": "0", "MAX": "500" }, { "NAME": "pageMarginRight", "CAT": "Input and page configuration options", "INFO": "Page right margin.", "ARG": "integer", "DEF": "50", "MIN": "0", "MAX": "500" }, { "NAME": "pageMarginTop", "CAT": "Input and page configuration options", "INFO": "Page top margin.", "ARG": "integer", "DEF": "50", "MIN": "0", "MAX": "500" }, { "NAME": "pageWidth", "CAT": "Input and page configuration options", "INFO": "Page width", "ARG": "float", "DEF": "2100", "MIN": "100", "MAX": "100000" }, { "NAME": "pedalStyle", "CAT": "Input and page configuration options", "INFO": "Global pedal style", "ARG": "string", "DEF": "auto", "ALT": [ "line", "pedstar", "altpedstar" ] }, { "NAME": "preserveAnalyticalMarkup", "CAT": "Input and page configuration options", "INFO": "Preserves analytical markup in MEI.", "ARG": "boolean" }, { "NAME": "removeIds", "CAT": "Input and page configuration options", "INFO": "Remove XML IDs in the MEI output when not referenced.", "ARG": "boolean" }, { "NAME": "scaleToPageSize", "CAT": "Input and page configuration options", "INFO": "Scale content with page instead of scaling page itself.", "ARG": "boolean" }, { "NAME": "setLocale", "CAT": "Input and page configuration options", "INFO": "Changes the global locale to C (this is not thread-safe).", "ARG": "boolean" }, { "NAME": "showRuntime", "CAT": "Input and page configuration options", "INFO": "Display processing time.", "ARG": "boolean", "CLI-ONLY": "true" }, { "NAME": "shrinkToFit", "CAT": "Input and page configuration options", "INFO": "Scale down page content to fit page height, if needed.", "ARG": "boolean" }, { "NAME": "smuflTextFont", "CAT": "Input and page configuration options", "INFO": "Specify if the SMuFL text font access.", "ARG": "string", "DEF": "embedded", "ALT": [ "linked", "none" ] }, { "NAME": "staccato-center", "CAT": "Input and page configuration options", "INFO": "Align staccato and staccatissimo articulations with center of note.", "ARG": "boolean" }, { "NAME": "svgBoundingBoxes", "CAT": "Input and page configuration options", "INFO": "Include bounding boxes in SVG output.", "ARG": "boolean" }, { "NAME": "svgCss", "CAT": "Input and page configuration options", "INFO": "CSS to embed in SVG output.", "ARG": "string" }, { "NAME": "svgViewBox", "CAT": "Input and page configuration options", "INFO": "Use viewbox on SVG root element for easy scaling of document.", "ARG": "boolean" }, { "NAME": "svgHtml5", "CAT": "Input and page configuration options", "INFO": "Write data-id and data-class attributes for JS usage and ID clash avoidance.", "ARG": "boolean" }, { "NAME": "svgFormatRaw", "CAT": "Input and page configuration options", "INFO": "Write SVG with no line indenting or non-content newlines. See outputFormatRaw.", "ARG": "boolean" }, { "NAME": "svgRemoveXlink", "CAT": "Input and page configuration options", "INFO": "Removes the \"xlink:\" prefix from href attributes for compatibility with some newer browsers.", "ARG": "boolean" }, { "NAME": "svgAdditionalAttribute", "CAT": "Input and page configuration options", "INFO": "Add additional attributes for graphical elements in SVG as \"data-*\". For example: \"note@pname\" adds \"data-pname to all note elements.", "ARG": "string", "REPEAT": "true" }, { "NAME": "unit", "CAT": "Input and page configuration options", "INFO": "The MEI unit (1/2 of the distance between the staff lines).", "ARG": "float", "DEF": "9.00", "MIN": "4.50", "MAX": "12.00" }, { "NAME": "useBraceGlyph", "CAT": "Input and page configuration options", "INFO": "Use brace glyph from current font.", "ARG": "boolean" }, { "NAME": "useFacsimile", "CAT": "Input and page configuration options", "INFO": "Use information in the facsimile element to control the layout.", "ARG": "boolean" }, { "NAME": "usePgFooterForAll", "CAT": "Input and page configuration options", "INFO": "Use the pgFooter element for all pages.", "ARG": "boolean" }, { "NAME": "usePgHeaderForAll", "CAT": "Input and page configuration options", "INFO": "Use the pgHeader element for all pages.", "ARG": "boolean" }, { "NAME": "xmlIdChecksum", "CAT": "Input and page configuration options", "INFO": "Seed XML ID generator using checkoug of input data", "ARG": "boolean" }, { "NAME": "barLineSeparation", "CAT": "General layout", "INFO": "Default distance between multiple barlines when locked together.", "ARG": "float", "DEF": "0.80", "MIN": "0.50", "MAX": "2.00" }, { "NAME": "barLineWidth", "CAT": "General layout", "INFO": "Width of barlines.", "ARG": "float", "DEF": "0.30", "MIN": "0.10", "MAX": "0.80" }, { "NAME": "beamFrenchStyle", "CAT": "General layout", "INFO": "Note stems stop at first beam rather than last.", "ARG": "boolean" }, { "NAME": "beamMaxSlope", "CAT": "General layout", "INFO": "Maximum beam slope.", "ARG": "integer", "DEF": "10", "MIN": "0", "MAX": "20" }, { "NAME": "beamMixedPreserve", "INFO": "Mixed beams will be drawn even if there is not enough space.", "CAT": "General layout", "ARG": "boolean" }, { "NAME": "beamMixedStemMin", "INFO": "Minimal stem length in diatonic steps for mixed beams.", "CAT": "General layout", "ARG": "float", "DEF": "3.5", "MIN": "1.00", "MAX": "8.00" }, { "NAME": "bracketThickness", "CAT": "General layout", "INFO": "Thickness of system brackets.", "ARG": "float", "DEF": "1.00", "MIN": "0.50", "MAX": "2.00" }, { "NAME": "breaksNoWidow", "INFO": "Prevent single measures on last page by fitting on previous page.", "CAT": "General layout", "ARG": "boolean" }, { "NAME": "dashedBarLineDashLength", "INFO": "Dashed barline dash length.", "CAT": "General layout", "ARG": "float", "DEF": "1.14", "MIN": "0.10", "MAX": "5.00" }, { "NAME": "dashedBarLineGapLength", "INFO": "Dashed barline gap length.", "CAT": "General layout", "ARG": "float", "DEF": "1.14", "MIN": "0.10", "MAX": "5.00" }, { "NAME": "dynamDist", "INFO": "Distance from staff for dynamic marks", "CAT": "General layout", "ARG": "float", "DEF": "1.00", "MIN": "0.50", "MAX": "16.00" }, { "NAME": "dynamSingleGlyphs", "INFO": "Do not use SMuFL dynamics glyph combinations.", "CAT": "General layout", "ARG": "boolean" }, { "NAME": "engravingDefaults", "INFO": "Default options for engraving SMuFL font as JSON string.", "CAT": "General layout", "ARG": "string" }, { "NAME": "engravingDefaultsFile", "INFO": "Path to JSON file for engraving SMuFL font as JSON string.", "CAT": "General layout", "ARG": "string" }, { "NAME": "extenderLineMinSpace", "CAT": "General layout", "INFO": "Minimum space required for extender line to be drawn.", "ARG": "float", "DEF": "1.5", "MIN": "1.5", "MAX": "10.0" }, { "NAME": "fingeringScale", "CAT": "General layout", "INFO": "Scale of fingering numbers compared to default font size.", "ARG": "float", "DEF": "0.75", "MIN": "0.25", "MAX": "1.00" }, { "NAME": "font", "CAT": "General layout", "INFO": "Set the music font.", "ARG": "string", "DEF": "Leipzig", "ALT": [ "Bravura", "Gootville", "Leland", "Petaluma" ] }, { "NAME": "fontAddCustom", "INFO": "Add a custom music font as zip file.", "CAT": "General layout", "ARG": "string" }, { "NAME": "fontFallback", "INFO": "Fallback music font for missing glyphs", "CAT": "General layout", "ARG": "string", "DEF": "Leipzig", "ALT": "Bravura" }, { "NAME": "fontLoadAll", "INFO": "Load all music fonts.", "CAT": "General layout", "ARG": "boolean" }, { "NAME": "graceFactor", "CAT": "General layout", "INFO": "Size of grace notes relative to regular notes.", "ARG": "float", "DEF": "0.75", "MIN": "0.50", "MAX": "1.00" }, { "NAME": "graceRhythmAlign", "CAT": "General layout", "INFO": "Align grace notes rhythmically with all staves.", "ARG": "boolean" }, { "NAME": "graceRightAlign", "CAT": "General layout", "INFO": "Align the right position of a grace group with all staves.", "ARG": "boolean" }, { "NAME": "hairpinSize", "CAT": "General layout", "INFO": "Size of hairpins (crescendo lines) in diatonic steps.", "ARG": "float", "DEF": "3.00", "MIN": "1.00", "MAX": "8.00" }, { "NAME": "hairpinThickness", "CAT": "General layout", "INFO": "Hairpin thickness (crescendo lines) in diatonic-step units.", "ARG": "float", "DEF": "0.20", "MIN": "0.10", "MAX": "0.80" }, { "NAME": "handwrittenFont", "CAT": "General layout", "INFO": "Handwriting fonts that require special handling.", "ARG": "string", "REPEAT": "true" }, { "NAME": "harmDist", "CAT": "General layout", "INFO": "Default distance from harmonic labels to the staff.", "ARG": "float", "DEF": "1.00", "MIN": "0.50", "MAX": "16.00" }, { "NAME": "justificationStaff", "CAT": "General layout", "INFO": "Vertical staff justification.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "10.00" }, { "NAME": "justificationSystem", "CAT": "General layout", "INFO": "System spacing justification.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "10.00" }, { "NAME": "justificationBracketGroup", "CAT": "General layout", "INFO": "Space between staves inside a bracket group justification.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "10.00" }, { "NAME": "justificationBraceGroup", "CAT": "General layout", "INFO": "Space between staves inside a brace group justification.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "10.00" }, { "NAME": "justificationMaxVertical", "CAT": "General layout", "INFO": "Maximum ratio of justifiable height to page height that can be used for the vertical justification.", "ARG": "float", "DEF": "0.30", "MIN": "0.00", "MAX": "1.00" }, { "NAME": "ledgerLineThickness", "CAT": "General layout", "INFO": "Thickness of ledger lines (diatonic steps).", "ARG": "float", "DEF": "0.25", "MIN": "0.10", "MAX": "0.50" }, { "NAME": "ledgerLineExtension", "CAT": "General layout", "INFO": "Amount by which ledger lines should extend on either side of a notehead (diatonic steps).", "ARG": "float", "DEF": "0.54", "MIN": "0.20", "MAX": "1.00" }, { "NAME": "lyricElision", "CAT": "General layout", "INFO": "Lyric elision width.", "ARG": "string", "DEF": "regular", "ALT": [ "unicode", "narrow", "wide" ] }, { "NAME": "lyricHeightFactor", "CAT": "General layout", "INFO": "Lyric verse line height factor.", "ARG": "float", "DEF": "1.00", "ALT": [ "1.00", "20.00" ] }, { "NAME": "lyricLineThickness", "CAT": "General layout", "INFO": "Lyric verse line height factor.", "ARG": "float", "DEF": "0.25", "ALT": [ "0.10", "0.50" ] }, { "NAME": "lyricNoStartHyphen", "CAT": "General layout", "INFO": "Do not show hyphens at beginning of system", "ARG": "boolean" }, { "NAME": "lyricSize", "CAT": "General layout", "INFO": "Size of lyric text in diatonic-step units.", "ARG": "float", "DEF": "4.50", "MIN": "2.00", "MAX": "8.00" }, { "NAME": "lyricTopMinMargin", "CAT": "General layout", "INFO": "Minmal margin above lyrics (in diatonic steps)." }, { "NAME": "lyricWordSpace", "CAT": "General layout", "INFO": "Minimum width of spaces separating lyrics syllables.", "ARG": "float", "DEF": "1.20", "MIN": "0.00", "MAX": "10.00" }, { "NAME": "lyricVerseCollapse", "CAT": "General layout", "INFO": "Remove unused verse numbers from score.", "ARG": "boolean" }, { "NAME": "measureMinWidth", "CAT": "General layout", "INFO": "Minimal measure width in diatonic-step units.", "ARG": "integer", "DEF": "15", "MIN": "1", "MAX": "30" }, { "NAME": "mnumInterval", "INFO": [ "Repeat measure numbers at the given frequency.", "Repeat measure numbers at the given cycle size." ], "CAT": "General layout", "ARG": "integer", "DEF": "0", "MIN": [ "0", "64" ] }, { "NAME": "multiRestStyle", "CAT": "General layout", "INFO": "Rendering style of multiple measure rests.", "ARG": "string", "DEF": "auto", "ALT": [ "default", "block", "symbols" ] }, { "NAME": "multiRestThickness", "CAT": "General layout", "INFO": "Thickness of multi rest in diatonic steps.", "ARG": "float", "DEF": "2.00", "MIN": "0.50", "MAX": "6.00" }, { "NAME": "octaveAlternativeSymbols", "INFO": "Use alternative symbols for displaying octaves.", "CAT": "General layout", "ARG": "boolean" }, { "NAME": "octaveLineThickness", "INFO": "Octave line thickness.", "CAT": "General layout", "ARG": "float", "DEF": "0.20", "MIN": "0.10", "MAX": "1.00" }, { "NAME": "octaveNoSpanningParentheses", "INFO": "Do not add parentheses around octaves after system breaks.", "CAT": "General layout", "ARG": "boolean" }, { "NAME": "pedalLineThickness", "INFO": "Line thickness for piano pedalling in diatonci steps.", "CAT": "General layout", "ARG": "float", "DEF": "0.20", "MIN": "0.10", "MAX": "1.00" }, { "NAME": "repeatBarLineDotSeparation", "INFO": "Default horizontal distance between dots and inner repeat barline.", "CAT": "General layout", "ARG": "float", "DEF": "0.36", "MIN": "0.10", "MAX": "1.00" }, { "NAME": "repeatEndingLineThickness", "INFO": "Repeat and endling line thickness in diatonic steps.", "CAT": "General layout", "ARG": "float", "DEF": "0.15", "MIN": "0.10", "MAX": "2.00" }, { "NAME": "slurCurveFactor", "INFO": "Higher values mean rounder slurs.", "CAT": "General layout", "ARG": "float", "DEF": "1.00", "MIN": "0.20", "MAX": "5.00" }, { "NAME": "slurEndpointFlexibility", "INFO": "Allow more endpoint movement during adjustment.", "CAT": "General layout", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "1.00" }, { "NAME": "slurEndpointThickness", "INFO": "Slur endpoint thickness in diatonic steps.", "CAT": "General layout", "ARG": "float", "DEF": "0.10", "MIN": "0.05", "MAX": "0.25" }, { "NAME": "slurMargin", "INFO": "Slur padding in diatonic steps to avoid obstacles.", "CAT": "General layout", "ARG": "float", "DEF": "1.00", "MIN": "0.10", "MAX": "4.00" }, { "NAME": "slurMaxSlope", "INFO": "Maximum slur slope in degrees.", "CAT": "General layout", "ARG": "float", "DEF": "60", "MIN": "30", "MAX": "85" }, { "NAME": "slurMidpointThickness", "INFO": "Slur midpoint thickness in diatonic steps.", "CAT": "General layout", "ARG": "float", "DEF": "0.60", "MIN": "0.20", "MAX": "1.20" }, { "NAME": "slurSymmetry", "INFO": "High value means more symmetric slurs.", "CAT": "General layout", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "1.00" }, { "NAME": "spacingBraceGroup", "INFO": "Minimum space between staves inside of a braced group in diatonic steps.", "CAT": "General layout", "ARG": "integer", "DEF": "12", "MIN": "0", "MAX": "48" }, { "NAME": "spacingBracketGroup", "INFO": "Minimum space between staves inside a bracketed group in diatonic steps.", "CAT": "General layout", "ARG": "integer", "DEF": "12", "MIN": "0", "MAX": "48" }, { "NAME": "spacingDurDetection", "INFO": "Detect long duration for adjusting spacing.", "CAT": "General layout", "ARG": "boolean" }, { "NAME": "spacingLinear", "CAT": "General layout", "INFO": [ "Specify the linear spacing factor.", "Linear spacing factor between notes/rests." ], "ARG": "float", "DEF": "0.25", "MIN": "0.00", "MAX": "1.00" }, { "NAME": "spacingNonLinear", "CAT": "General layout", "ARG": "float", "INFO": "Ratio of spacing between rhythmic levels (such as width of quarter note compared to eighth note).", "DEF": "0.60", "MIN": "0.00", "MAX": "1.00" }, { "NAME": "spacingStaff", "INFO": "The staff minimal spacing", "CAT": "General layout", "ARG": "integer", "DEF": "12", "MIN": "0", "MAX": "48" }, { "NAME": "spacingSystem", "INFO": "Minimum spacing between systems in diatonic steps.", "CAT": "General layout", "ARG": "integer", "DEF": "4", "MIN": "0", "MAX": "48" }, { "NAME": "staffLineWidth", "INFO": [ "The staff line width in unit", "Staff line width in diatonic-step units." ], "CAT": "General layout", "ARG": "float", "DEF": "0.15", "MIN": "0.10", "MAX": "0.30" }, { "NAME": "stemWidth", "CAT": "General layout", "INFO": "The stem width of notes in diaontic steps.", "ARG": "float", "DEF": "0.20", "MIN": "0.10", "MAX": "0.50" }, { "NAME": "subBracketThickness", "CAT": "General layout", "ARG": "float", "INFO": "Thickness of system sub-brackets in diatonic steps.", "DEF": "0.20", "MIN": "0.10", "MAX": "2.00" }, { "NAME": "systemDivider", "CAT": "General layout", "INFO": "Display style of system dividers.", "ARG": "string", "DEF": "auto", "ALT": [ "none", "left", "left-right" ] }, { "NAME": "systemMaxPerPage", "CAT": "General layout", "INFO": "Maximum number of systems per page.", "ARG": "integer", "DEF": "0", "MIN": "0", "MAX": "24" }, { "NAME": "textEnclosureThickness", "CAT": "General layout", "INFO": "Thickness of text-enclosing boxes in diatonic-step units.", "ARG": "float", "DEF": "0.20", "MIN": "0.10", "MAX": "0.80" }, { "NAME": "thickBarlineThickness", "CAT": "General layout", "INFO": "Thickness of thick barlines in diatonic steps.", "ARG": "float", "DEF": "1.00", "MIN": "0.50", "MAX": "2.00" }, { "NAME": "tieEndpointThickness", "CAT": "General layout", "INFO": "Endpoint tie thickeness (diatonic steps).", "ARG": "float", "DEF": "0.10", "MIN": "0.05", "MAX": "0.25" }, { "NAME": "tieMidpointThickness", "CAT": "General layout", "INFO": "Tie midpoint thickeness (in diatonic steps).", "ARG": "float", "DEF": "0.50", "MIN": "0.20", "MAX": "1.00" }, { "NAME": "tieMinLength", "CAT": "General layout", "INFO": "Midpoint tie thickness (in diatonic steps).", "ARG": "float", "DEF": "2.00", "MIN": "0.00", "MAX": "10.00" }, { "NAME": "tupletAngledOnBeams", "CAT": "General layout", "INFO": "Tuplet brackets angled on beams only.", "ARG": "boolearn" }, { "NAME": "tupletBracketThickness", "CAT": "General layout", "INFO": "Tuplet bracket thickness in diatonic-step units.", "ARG": "float", "DEF": "0.20", "MIN": "0.10", "MAX": "0.80" }, { "NAME": "tupletNumHead", "CAT": "General layout", "INFO": "Place tuplet number on notehead-side.", "ARG": "boolean" }, { "NAME": "appXPathQuery", "CAT": "Selectors", "INFO": "Set xPath query for selecting app child elements. By default first lem or rdg is selected.", "ARG": "string", "REPEAT": "true", "EXAM": "\"./rdg[contains(@source, 'source-id')]\"" }, { "NAME": "choiceXPathQuery", "CAT": "Selectors", "INFO": "Set xPath query for selecting choice child elements. By default first child is selected.", "ARG": "string", "REPEAT": "true", "EXAM": "\"./orig\"" }, { "NAME": "loadSelectedMdivOnly", "CAT": "Selectors", "INFO": "Load only the selected mdif; the content of other mdivs are skipped.", "ARG": "boolean" }, { "NAME": "mdivAll", "CAT": "Selectors", "INFO": "Load and render all mdiv elements (movements/works).", "ARG": "boolean" }, { "NAME": "mdivXPathQuery", "CAT": "Selectors", "INFO": "Set xPath query for selecting mdiv to be rendered, only one mdiv can be rendered.", "ARG": "string", "DEF": "\"\"" }, { "NAME": "substXPAthQuery", "CAT": "Selectors", "INFO": "Set xPath query for selecting subst child elements. By default first child is selected", "ARG": "string", "EXAM": "\"./del\"", "REPEAT": "true" }, { "NAME": "transpose", "CAT": "Selectors", "INFO": "Transpose the entire content", "ARG": "string", "DEF": "\"\"", "REPEAT": "true" }, { "NAME": "transposeMdiv", "CAT": "Selectors", "INFO": "JSON mapping mdiv IDs to corresponding transposition", "ARG": "string" }, { "NAME": "transposeSelectedOnly", "CAT": "Selectors", "INFO": "Transpose only selected content and ignore unselected editorial content.", "ARG": "boolean" }, { "NAME": "transposeToSoundingPitch", "CAT": "Selectors", "INFO": "Transpose to sounding pitch by evaluating @trans.semi", "ARG": "boolean" }, { "NAME": "defaultBottomMargin", "CAT": "Element margins", "INFO": "Default bottom margin.", "ARG": "float", "DEF": "0.50", "MIN": "0.00", "MAX": "5.00" }, { "NAME": "defaultLeftMargin", "CAT": "Element margins", "INFO": "Default left margin.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "defaultRightMargin", "CAT": "Element margins", "INFO": "Default right margin.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "defaultTopMargin", "CAT": "Element margins", "INFO": "Default top margin.", "ARG": "float", "DEF": "0.50", "MIN": "0.00", "MAX": "6.00" }, { "NAME": "bottomMarginArtic", "CAT": "Element margins", "INFO": "Bottom margin for articulations in diatonic-step units.", "ARG": "float", "DEF": "0.75", "MIN": "0.00", "MAX": "10.00" }, { "NAME": "bottomMarginHarm", "CAT": "Element margins", "INFO": "Bottom margin for harmony labels in diatonic-step units.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "10.00" }, { "NAME": "bottomMarginOctave", "CAT": "element margins", "INFO": "Margin for octave (diatonic steps).", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "10.00" }, { "NAME": "bottomMarginHeader", "CAT": "Element margins", "INFO": "Bottom margin for page headers in diatonic-step units.", "ARG": "float", "DEF": "2.00", "MIN": "0.00", "MAX": "24.00" }, { "NAME": "leftMarginAccid", "CAT": "element margins", "INFO": "The margin for accid (diatonic steps).", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "leftMarginBarLine", "CAT": "Element margins", "INFO": "Left margin for barlines in diatonic-step units.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "leftMarginBeatRpt", "CAT": "Element margins", "INFO": "Left margin for beat repetition symbols in diatonic-step units.", "ARG": "float", "DEF": "2.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "leftMarginChord", "CAT": "Element margins", "INFO": "Left margin for chords in diatonic-step units.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "leftMarginClef", "CAT": "Element margins", "INFO": "Left margin for clefs in diatonic-step units.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "leftMarginKeySig", "CAT": "Element margins", "INFO": "Left margin for key signatures in diatonic-step units.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "leftMarginLeftBarLine", "CAT": "Element margins", "INFO": "Left margin for left barlines in diatonic-step units.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "leftMarginMensur", "CAT": "Element margins", "INFO": "Left margin for mensuration signs.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "leftMarginMeterSig", "CAT": "Element margins", "INFO": "Left margin for time signatures.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "leftMarginMRest", "CAT": "Element margins", "INFO": "Left margin for measure rests in diatonic-step units.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "leftMarginMRpt2", "CAT": "Element margins", "INFO": "Left margin for two-measure repeat signs in diatonic-step units.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "leftMarginMultiRest", "CAT": "Element margins", "INFO": "Left margin for multi-bar rests in diatonic-step units.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "leftMarginMultiRpt", "CAT": "Element margins", "INFO": "Left margin for multi-bar repeats in diatonic-step units.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "leftMarginNote", "CAT": "element margins", "INFO": "Left margin for note.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "leftMarginRest", "CAT": "Element margins", "INFO": "Left margin for rest in diatonic-step units.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "leftMarginRightBarLine", "CAT": "element margins", "INFO": "Left margin for right barLine.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "leftMarginTabDurSym", "CAT": "element margins", "INFO": "Left margin for tabDurSym.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "rightMarginAccid", "CAT": "Element margins", "INFO": "Right margin for accidentals.", "ARG": "float", "DEF": "0.50", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "rightMarginBarLine", "CAT": "Element margins", "INFO": "Right margin for barlines in diatonic-step units.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "rightMarginBeatRpt", "CAT": "Element margins", "INFO": "Right margin for beat repeat symbols in diatonic-step units.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "rightMarginChord", "CAT": "Element margins", "INFO": "Right margin for chords.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "rightMarginClef", "CAT": "Element margins", "INFO": "Right margin for clefs.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "rightMarginKeySig", "CAT": "Element margins", "INFO": "Right margin for key signatures.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "rightMarginLeftBarLine", "CAT": "Element margins", "INFO": "Right margin for left barlines in diatonic-step units.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "rightMarginMensur", "CAT": "Element margins", "INFO": "Right margin for mensuration signs.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "rightMarginMeterSig", "CAT": "Element margins", "INFO": "Right margin for time signatures.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "rightMarginMRest", "CAT": "Element margins", "INFO": "Right margin for full-measure rests in diatonic-step units.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "rightMarginMRpt2", "CAT": "Element margins", "INFO": "Right margin for two-measure repeat symbols in diatonic-step units.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "rightMarginMultiRest", "CAT": "Element margins", "INFO": "Right margin for multi-bar rests in diatonic-step units.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "rightMarginMultiRpt", "CAT": "Element margins", "INFO": "Right margin for multi-measure repeat signs in diatonic-step units.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "rightMarginNote", "CAT": "Element margins", "INFO": "Right margin for notes.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "rightMarginRest", "CAT": "Element margins", "INFO": "Right margin for rests.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "rightMarginRightBarLine", "CAT": "Element margins", "INFO": "Right margin for right barLine.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "rightMarginTabDurSym", "CAT": "Element margins", "INFO": "Right margin for tabDurSym in diatonic-step units.", "ARG": "float", "DEF": "0.00", "MIN": "0.00", "MAX": "2.00" }, { "NAME": "topMarginArtic", "CAT": "Element margins", "INFO": "Top margin for articulations in diatonic-step units.", "ARG": "float", "DEF": "0.75", "MIN": "0.00", "MAX": "10.00" }, { "NAME": "topMarginHarm", "CAT": "Element margins", "INFO": "Top margin for harmony labels in diatonic-step units.", "ARG": "float", "DEF": "1.00", "MIN": "0.00", "MAX": "10.00" }, { "NAME": "topMarginPgFooter", "CAT": "element margins", "INFO": "Top margin for page footer.", "ARG": "float", "DEF": "2.00", "MIN": "0.00", "MAX": "24.00" }, { "NAME": "midiNoCue", "CAT": "MIDI options", "INFO": "Skip cue notes in MIDI output.", "ARG": "boolean" }, { "NAME": "midiTempoAdjust", "CAT": "MIDI options", "INFO": "MIDI tempo adjustment factor.", "ARG": "float", "DEF": "1.00", "MIN": "0.20", "MAX": "4.00" }, { "NAME": "durationEquivalence", "CAT": "Mensural options", "INFO": "Mensural duration equivalence.", "ARG": "string", "DEF": "brevis", "ALT": [ "semibrevis", "minima" ] }, { "NAME": "ligatureAsBracket", "CAT": "Mensural options", "INFO": "Render ligatures as bracket instead of as ligature.", "ARG": "boolean" }, { "NAME": "mensuralResponsiveView", "CAT": "Mensural options", "INFO": "Convert mensural content to more responsive view reduced to the selected markup.", "ARG": "boolean" }, { "NAME": "mensuralToCmn", "CAT": "Mensural options", "INFO": "Convert mensural sections to CMN measure-based.", "ARG": "boolean" }, { "NAME": "mensuralScoreUp", "CAT": "Mensural options", "INFO": "Score up the mensural voices providing a dur.quality to the notes.", "ARG": "boolean" }, { "NAME": "timemapOptions", "CAT": "JSON options", "INFO": "JSON options for producing timemap.", "ARG": "string", "DEF": "{}" } ] } ; let opts = VEROVIOOPTIONS.OPTION; for (let i=0; i500), it will be limited // to those values. A size of 0 will set scale to 40. Currently // this function does not store the calculated SCALE value in // localStorage so that the music size can be returned to in a // later session. This seems best, since any custom SCALE should // not be overridden by a scale for a particular work included in // the URL. // function getScaleFromPercentSize(string, baseScale) { if (!baseScale) { baseScale = 40; } if (!string) { return baseScale; } var mysize; try { mysize = parseFloat(string); } catch(err) { mysize = 100.0; } var scale = parseInt(baseScale * mysize / 100.0 + 0.5); if (scale < 15) { scale = 15; } else if (scale > 500) { scale = 500; } return scale; } ////////////////////////////// // // getVerovioDefaultOptions -- // function getVerovioDefaultOptions() { let output = {}; if (!VEROVIOOPTIONS) { return output; } var options = VEROVIOOPTIONS.OPTION; for (let i=0; i 3.0) { value = 3.0; } INPUT_FONT_SIZE = value; var value2 = localStorage.SCALE; if (!value2) { value2 = 40; } else { value2 *= 1; } if (value2 < 1) { value2 = 40; } else if (value2 > 1000) { value2 = 40; } SCALE = value2; } function meiToHumdrumOptions() { return { inputFrom : "mei-hum", breaks : "auto" } } function meiToMeiOptions() { return { inputFrom : "mei", breaks : "encoded" } } function musedataToHumdrumOptions() { return { inputFrom : "musedata-hum" } } function musicxmlToHumdrumOptions() { return { inputFrom : "musicxml-hum" } } function musicxmlToMeiOptions() { return { inputFrom : "musicxml", breaks : "auto" } } ////////////////////////////// // // validateOptions -- Make sure verovio options are valid: numbers with a min // and max value will clip the option value to that range. Strings with // multiple ALT entries will only be passed if option value is in that // list or is in DEF (default). Unknown options will not be passed. // Warning messages will be sent to the console if invalid options // are detected. // function validateOptions(options) { // Function to check if an option value is a number: function isNumber(value) { return typeof value === 'number' ? isFinite(value) : (typeof value === 'string' && value !== '' && isFinite(Number(value))); } // Cleaned options to be returned: let output = {}; for (let key in options) { if (!options.hasOwnProperty(key)) { console.warn(`Warning: option ${key} is not local to option list.`); continue; } // First check if the option is known: let value = options[key]; let name = VEROVIOOPTIONS[key]; if (!name) { console.error(`Cannot find ${key} in verovio option list`); continue; } // Get the data type of the option: let arg = VEROVIOOPTIONS[key].ARG; // Process integer options, checking to see if number is in min/max range // if the option definition has a min/max value: if ((arg === "integer")) { // Interger options must have a number as its value: if (!isNumber(value)) { console.warn(`Expected a number for option ${key}, but got ${value}`); continue; } let min = VEROVIOOPTIONS[key].MIN; let max = VEROVIOOPTIONS[key].MAX; if (isNumber(min) && Number(value) < Number(min)) { // If number is less than MIN, the clip to MIN console.warn(`Value ${value} for option ${key} is too small.`); console.warn(`Setting to ${min}`); value = min; output[key] = value; continue; } else if (isNumber(max) && Number(value) > Number(max)) { // If number is greater than MIN, the clip to MAX console.warn(`Value ${value} for option ${key} is too large.`); console.warn(`Setting to ${max}`); value = max; output[key] = value; continue; } else { // number in range output[key] = value; continue; } } else if ((arg === "float")) { // Float options must have a number as its value: if (!isNumber(value)) { console.warn(`Expected a number for option ${key}, but got ${value}`); continue; } let min = VEROVIOOPTIONS[key].MIN; let max = VEROVIOOPTIONS[key].MAX; if (isNumber(min) && Number(value) < Number(min)) { // If number is less than MIN, the clip to MIN console.warn(`Value ${value} for option ${key} is too small.`); console.warn(`Setting to ${min}`); value = min; output[key] = value; continue; } else if (isNumber(max) && Number(value) > Number(max)) { // If number is greater than MIN, the clip to MAX console.warn(`Value ${value} for option ${key} is too large.`); console.warn(`Setting to ${max}`); value = max; output[key] = value; continue; } else { // number in range output[key] = value; continue; } } else if (arg === "boolean") { // Use only 1/0 for true/false: if (value) { output[key] = 1; } else { output[key] = 0; } continue; } else if (arg == "string") { let def = VEROVIOOPTIONS[key].DEF; let alt = VEROVIOOPTIONS[key].ALT; if (value === def) { // Default value is used (could suppress if default option): output[key] = value; continue; } else if (Array.isArray(alt)) { if (alt.includes(value)) { // Option value is in the alternate list: output[key] = value; continue; } else { console.warn(`Warning: option ${key}'s value ${value} is not in list: ${def}, ${alt.join(", ")}`); continue; } } else { // Open-ended string value for option: output[key] = value; continue; } } console.warn(`SKIPPING OPTION: ${key} VALUE: ${value} ARG: ${arg} `, VEROVIOOPTIONS[key]); } return output; } // Uncategorized files: ////////////////////////////// // // displayNotation -- Convert Humdrum data in textarea to notation. // This function seems to be called twice in certain cases (editing). // function displayNotation(page, force, restoreid) { if (!vrvWorker.initialized || (FreezeRendering && !force)) { // console.log("Ignoring displayNotation request: not initialized or frozen"); return; }; if (COMPILEFILTERAUTOMATIC) { COMPILEFILTERAUTOMATIC = false; compileFilters(); return; } if (FILEINFO && FILEINFO.location && FILEINFO.file) { let file = `${FILEINFO.location}/${FILEINFO.file}`; let url = getRepertoryUrlWithFilters(file); window.history.pushState(null, null, url); } // if input area is a "; let w = window.open("about:blank", "SVG transcoding", 'width=600,height=800,resizeable,scrollabars,location=false'); w.document.write(prefix + data + postfix); w.document.close(); // Set the title of the window. It cannot be set immediately and must wait // until the content has been loaded. function checkTitle() { if (w.document) { w.document.title = "SVG transcoding"; } else { setTimeout(checkTitle, 40); } } checkTitle(); verovioCallback(data); }); } ////////////////////////////// // // displayPdf -- // function displayPdf() { // If a humdrum file has a line starting with // !!!URL-pdf: (https?://[^\s]*) // then load that file. let loaded = false; if (EditorMode === "humdrum") { let loaded = displayHumdrumPdf("!!!"); } else if (EditorMode === "musedata") { let loaded = displayHumdrumPdf("@@@"); } if (loaded) { return; } if (!FILEINFO["has-pdf"]) { return; } if (FILEINFO["has-pdf"] != "true") { return; } let url = "https://kern.humdrum.org/data?l=" + FILEINFO["location"]; url += "&file=" + FILEINFO["file"]; url += "&format=pdf&#view=FitH"; openPdfAtBottomThirdOfScreen(url); } ////////////////////////////// // // displayKeyscape -- // function displayKeyscape(event) { let fileinfo = FILEINFO; if (!fileinfo) { console.log("Error: no fileinfo"); return; } if (typeof fileinfo.file === "undefined") { console.log("Error: filename not found"); return; } let file = fileinfo.file; if (!file) { console.log("Error: filename is empty"); return; } if (typeof fileinfo.location === "undefined") { console.log("Error: location not found"); return; } let location = fileinfo.location; if (!location) { console.log("Error: location is empty"); return; } let url = "https://kern.humdrum.org/data?file="; url += encodeURIComponent(file); url += "&l="; url += encodeURIComponent(location); if (event.shiftKey) { if (event.altKey) { url += "&format=keyscape-tonic-dirty-html"; } else { url += "&format=keyscape-tonic-html"; } } else { if (event.altKey) { url += "&format=keyscape-dirty-html"; } else { url += "&format=keyscape-html"; } } // console.log("Loading Keyscape", url); if (WKEY) { WKEY.close(); WKEY = null; } // https://developer.mozilla.org/en-US/docs/Web/API/Window/open#window____features let features = ""; // width and height are not the dimensions of the PNG image (600x461) // features += "width=950"; // features += ", height=775"; features += "width=664"; features += ", height=511"; features += ", left=10"; features += ", top=10"; features += ", resizeable"; features += ", scrollbars"; features += ", toolbar=no"; features += ", location=0"; console.log("FEATURES", features); WKEY = window.open(url, "", features); WKEY.focus(); } ////////////////////////////// // // displayHumdrumPdf -- Also does URL-youtube // // !!!URL-pdf: (https?://[^\s]*) // If there is a number in the keyboard buffer: // !!!URL-pdf[1-9]: (https?://[^\s]*) // Return value: false if not loaded from reference record // // function displayHumdrumPdf(prefix) { let list = getUrlAndFilterList(prefix); if (!list.url) { return 0; } if (!list.url.pdf) { return 0; } let pdflist = list.url.pdf; let url = ""; let i; if (InterfaceSingleNumber > 1) { for (i=0; i 1) { if (data[i].charAt(1) != firstchar) { continue; } } if (prefix.length > 2) { if (data[i].charAt(2) != firstchar) { continue; } } let line = data[i]; let matches; // Store named filters: matches = rex3.exec(line); if (matches) { let obj = {}; obj.type = matches[1]; if (!output.filter[obj.type]) { output.filter[obj.type] = []; } output.filter[obj.type].push(matches[2]); } // Store named urls matches = rex.exec(line); if (matches) { let obj = {}; if (!matches[1]) { obj.number = -1; } else { obj.number = parseInt(matches[1]); } obj.line = i; obj.text = data[i]; obj.type = matches[2]; obj.url = matches[3]; obj.title = matches[4]; if (typeof output.url[obj.type] === "undefined") { output.url[obj.type] = []; } output.url[obj.type].push(obj); } else { matches = rex2.exec(line); if (matches) { let obj = {}; if (!matches[1]) { obj.number = -1; } else { obj.number = parseInt(matches[1]); } obj.line = i; obj.text = data[i]; obj.type = matches[2] obj.title = ""; let matches2; if (matches2 = obj.type.match("pdf-(.*)")) { obj.type = "pdf"; obj.title = matches2[1]; } obj.url = matches[3]; if (matches[4] && !matches[4].match(/^\s*$/)) { obj.title = matches[4]; } if (typeof output.url[obj.type] === "undefined") { output.url[obj.type] = []; } output.url[obj.type].push(obj); } } // Extract reference records for title template: let regex = new RegExp(`^${prefix}([^:]+)\s*:\s*(.*)\s*$`); matches = line.match(regex); if (matches) { obj = {}; obj.line = i; obj.text = data[i]; obj.key = matches[1]; obj.value = matches[2]; if (!refrecords[obj.key]) { refrecords[obj.key] = []; } refrecords[obj.key].push(obj); } } // Go through extracted reference records and fill in any templating: for (let key in output.url) { for (let i=0; i 100) { TABSIZE = 100; } EDITOR.getSession().setTabSize(TABSIZE); } ////////////////////////////// // // clearContent -- Used by the alt-e option or the erase button // in the main toolbar. // function clearContent() { let data = getTextFromEditorNoCsvProcessing(); clearCgiHash(); moveToTopOfNotation(); if (data.match(/^\s*$/)) { // restore the text (which may have accidentally been erased) setTextInEditor(ERASED_DATA); displayFileTitle(ERASED_DATA); restoreWorkNavigator(); // The left/right arrows are still active for navigating to // other works in the repertory. } else { // Erase the text, but store it in a buffer in case // the user wants to recall it if the editor is still empty. ERASED_DATA = data; ERASED_URL = window.location.href; let element setTextInEditor(""); let output = document.querySelector("#output"); if (output) { output.innerHTML = ""; } displayFileTitle(""); removeWorkNavigator(); } EDITOR.focus(); } ////////////////////////////// // // playCurrentMidi -- If a note is selected start playing from that note; // otherwise, start from the start of the music. // function playCurrentMidi() { if (CursorNote && CursorNote.id) { let id = CursorNote.id; vrvWorker.getTimeForElement(id) .then(function(time) { play_midi(time); }); } else { play_midi(); } } ////////////////////////////// // // setCursorNote -- // function setCursorNote(item, location) { CursorNote = item; MENU.showCursorNoteMenu(CursorNote); } ////////////////////////////// // // hideRepertoryIndex -- // function hideRepertoryIndex() { let element = document.querySelector("#index"); if (element && (element.style.display != "none")) { element.style.display = "none"; // element.style.visibility = "hidden"; let output = document.querySelector("#output"); if (output) { console.log("FOCUSING ON OUTPUT"); output.focus(); } ShowingIndex = 0; } } ////////////////////////////// // // updateEditorMode -- Automatically detect the type of data and change edit mode: // function updateEditorMode() { if (!EDITOR) { return; } let text = getTextFromEditorRaw(); if (!text) { // This check is needed to prevent intermediate // states when the editor has been cleared in preparation // for new contents. // console.log("EDITOR IS EMPTY"); return; } let shorttext = text.substring(0, 2000); let xmod = getMode(shorttext); if (xmod !== EditorMode) { EditorMode = xmod; setEditorModeAndKeyboard(); console.log("Changing to", xmod, "mode."); } } ////////////////////////////// // // nextPageClick -- this is a click event for the next page. If the shift key is // pressed, go to the last page instead of the next page. // function nextPageClick(event) { if (!event) { MENU.goToNextPage(event) } if (event.shiftKey) { MENU.goToLastPage(event) } else { MENU.goToNextPage(event) } } ////////////////////////////// // // previousPageClick -- this is a click event for the previous page. // If the shift key is pressed, go to the last page instead of // the next page. // function previousPageClick(event) { if (!event) { MENU.goToPreviousPage(event) } if (event.shiftKey) { MENU.goToFirstPage(event) } else { MENU.goToPreviousPage(event) } } ////////////////////////////// // // copyToClipboard -- // function copyToClipboard(string) { // console.log("Copying", string, "to clipboard"); let element = document.createElement("textarea"); element.value = string; document.body.appendChild(element); element.select(); document.execCommand("copy"); document.body.removeChild(element); }; ////////////////////////////// // // dataHasLineBreaks -- // function dataHasLineBreaks(data) { if (!data) { data = getTextFromEditor(); } // do something here ggg } ////////////////////////////// // // removeLastLineInTextEditorIfMatches -- Remove the last non-empty line // in the text editor if it matches the given input string. This function // is used by compileFilters() to remove the used GLOBALFILTER. // function removeLastLineInTextEditorIfMatches(line) { if (!line) { return; } let text = getTextFromEditor(); if (!text) { return; } let lines = text.replace(/^\s+/, "").replace(/\s+$/, "").split(/\r?\n/); let deleteindex = -1; for (let i=lines.length-1; i>=0; i--) { if (lines[i].match(/^\s*$/)) { continue; } if (lines[i] === line) { deleteindex = i; // also delete #@%! empty lines before the delete line for (let j=deleteindex-1; j<=0; j--) { if (lines[j].match(/^\s*$/)) { deleteindex--; continue; } break; } break; } break; } if (deleteindex < 0) { retrun; } let newtext = ""; for (let i=0; i // Creation Date: Sat Jan 9 19:54:31 PST 2021 // Last Modified: Sun Jan 10 16:01:24 PST 2021 // Filename: highlight.js // Syntax: ECMAScript 6 // vim: ts=3:nowrap:ft=javascript // // Description: Interface to highlight SVG notation created from Humdrum // files. // /////////////////////////////////////////////////////////////////////////// // // HnpMarkup class -- Interface to highlight and markup regions of a // verovio-generated SVG image. // ////////////////////////////// // // HnpMarkup constructor -- Creat an HnpMarkup object. // to create an object: // let highligher = new HnpMarkup(); // to load an SVG image (an SVG element or a selector for an SVG element): // highlighter.loadSvg(svg) // functions starting with "m_" should be treated as private to the class. // function HnpMarkup() { this.clear(); return this; } ////////////////////////////// // // HnpMarkup.prototype.clear -- Clear the contents of the highlighter. // HnpMarkup.prototype.clear = function() { this.clearSvgInfo(); }; ////////////////////////////// // // HnpMarkup.prototype.clearSvgInfo -- Clear information about // the stored SVG image. Does not clear highlighting database. // HnpMarkup.prototype.clearSvgInfo = function() { this.m_svg = new HnpSvg(); }; ////////////////////////////// // // HnpMarkup.prototype.loadSvg -- // HnpMarkup.prototype.loadSvg = function (svg) { let status = this.m_svg.loadSvg(svg); if (!status) { console.warn("Warning: could not load SVG image"); } return status; } ////////////////////////////// // // HnpMarkup.prototype.getMeasure -- // HnpMarkup.prototype.getMeasure = function (barnum) { if (!this.m_svg) { return null; } return this.m_svg.getMeasure(barnum); }; ////////////////////////////// // // HnpMarkup.prototype.getMeasureElement -- // HnpMarkup.prototype.getMeasureElement = function (barnum) { if (!this.m_svg) { return null; } let measure = this.m_svg.getMeasure(barnum); if (!measure) { return null; } if (typeof measure.element === "undefined") { return null; } return measure.element; }; ////////////////////////////// // // HnpMarkup.prototype.getLowerSystemMarkupElement -- // HnpMarkup.prototype.getLowerSystemMarkupElement = function () { return this.m_svg.getLowerSystemMarkupElement(); }; ////////////////////////////// // // HnpMarkup.prototype.getLowerMeasureMarkupElement -- // HnpMarkup.prototype.getLowerMeasureMarkupElement = function () { return this.m_svg.getLowerMeasureMarkupElement(); }; ////////////////////////////// // // HnpMarkup.prototype.highlightMeasure -- // // Options: // measure : the measure # to highlight // opacity : 0.0 == transparent, 1.0 == opaque // padding : units of 1/2 space between stafflines HnpMarkup.prototype.highlightMeasure = function (options) { let measure; let color; let opacity; let padding; if (typeof options === "number") { measure = options; color = "goldenrod"; opacity = 0.25; padding = 1; } else if (typeof options === "string") { measure = parseInt(options); color = "goldenrod"; opacity = 0.25; padding = 1; } else { measure = options.measure || 1; color = options.color || "goldenrod"; opacity = options.opacity || 0.25; if (typeof options.padding !== "undefined") { padding = options.padding; } else { padding = 1; } } if (measure < 0) { return null; } let measureobj = this.getMeasure(measure); if (!measureobj) { return null; } let x = measureobj.getX(); let y = measureobj.getY(); let width = measureobj.getWidth(); let height = measureobj.getHeight(); let vu = measureobj.getVuScale(); if ((padding > 0.0) && (vu > 0.0)) { x = x - padding * vu; y = y - padding * vu; width = width + 2 * padding * vu; height = height + 2 * padding * vu; } let mbox = document.createElementNS("http://www.w3.org/2000/svg","rect"); mbox.setAttribute("x", x); mbox.setAttribute("y", y); mbox.setAttribute("width", width); mbox.setAttribute("height", height); mbox.setAttribute("fill", color); mbox.setAttribute("opacity", opacity); let markupLayer = this.getLowerMeasureMarkupElement(); if (!markupLayer) { return null; } markupLayer.appendChild(mbox); return mbox; } /////////////////////////////////////////////////////////////////////////// // // HnpSvg class -- Interface to verovio-generated SVG image of music notation. // ////////////////////////////// // // HnpSvg constructor -- Creat an HnpSvg object. This is used by the // HnpMarkup class to interact with verovio-generated SVG image. // function HnpSvg() { this.clear(); return this; } ////////////////////////////// // // HnpSvg.prototype.clear -- Remove link to SVG image. // HnpSvg.prototype.clear = function () { this.element = null; // List of SVG system elements in image: this.svgSystems = []; // List of list of measure elements in each system: this.svgSystemMeasures = []; // List of all measures on the page (with other information added // such as the measure number and bounding box of the measure). this.svgMeasures = []; /////////////////////////// // // Clear attributes relatd to the SVG image: // // pagemargin == element for the page region of the SVG image: this.pagemargin = null; // lowerMarkupLayer == element for storing highlights in SVG // (behind the notation): this.lowerMarkupElement = null; // lowerSystemMarkups == element containing system highlights: this.lowerSystemMarkupElement = null; // lowerMeasureMarkupElement == element containing measure highlights: this.lowerMeasureMarkupElement = null; }; ////////////////////////////// // // HnpSvg.prototype.loadSvg -- Load an svg image for later processing. // Returns false if cannot load SVG. // HnpSvg.prototype.loadSvg = function (svg) { this.clear(); // Verify the SVG image being loaded: if (typeof svg === "string") { // Assume selector to SVG object: let element = document.querySelector(svg); if (!element) { console.warn("Warning: Selector for SVG element is invalid", svg); return false; } svg = element; } if (!svg) { console.warn("Warning: SVG element not found"); return false; } let nodename = svg.nodeName; if (nodename !== "svg") { console.warn("Warning: SVG element is not an SVG element:", svg); return false; } this.element = svg; // Create a list of systems in the SVG image: let systems = svg.querySelectorAll('g.system'); if (!systems) { console.warn("Warning: no systems in SVG image"); return false; } this.svgSystems = []; for (let i=0; i { let checksum = getChecksum(humdrum); if (checksum === LAST_CHECKSUM) { return; } else { LAST_CHECKSUM = checksum; } let prehtmlElement = document.querySelector(".PREHTML"); let posthtmlElement = document.querySelector(".POSTHTML"); // let humdrum = getTextFromEditor(); let parameters = getHumdrumParameters(humdrum); let language = LANGUAGE; // parameters.PREHTML contains content of HTML code to display above score. let PREHTML = parameters.PREHTML; // parameters.POSTHTML contains content of HTML code to display below score. let POSTHTML = parameters.POSTHTML; // parameters._REFS contains the Humdrum reference records in the file. let REFS = parameters._REFS; if (PREHTML && !Array.isArray(PREHTML)) { PREHTML = [ PREHTML ]; } if (POSTHTML && !Array.isArray(POSTHTML)) { POSTHTML = [ POSTHTML ]; } if (PREHTML && Array.isArray(PREHTML)) { let pretext = ""; for (let i=0; i response.text()); }) .then(function (svg) { // console.warn(">>>>>>>>>>>> SVG", svg); target.innerHTML = svg; }) .catch(function (error) { console.error("Error submitting SCORE data:", error); }); } ////////////////////////////// // // getScoreData -- // function getScoreData(scoreinfo, id) { if (!scoreinfo) { return null; } if (!Array.isArray(scoreinfo)) { scoreinfo = [ scoreinfo ]; } if (!Array.isArray(scoreinfo)) { console.warn("WARNING: Score info is not an array:", scoreinfo); return; } for (let i=0; i { var signature = new Uint8Array(buffer); var isZip = signature[0] === 0x50 && signature[1] === 0x4B && signature[2] === 0x03 && signature[3] === 0x04; if (isZip) { // Process ZIP file processZipFile(file, myevent); } else { // Process as a regular text file reader.readAsText(file, 'UTF-8'); reader.onload = function () { var contents = reader.result; if (myevent.shiftKey) { replaceEditorContentWithHumdrumFile(contents); } else { EDITOR.setValue(contents, -1); } $('html').css('cursor', 'auto'); }; } }); break; // Only processing the first file } } function hideDropArea(droparea) { if (!droparea) { droparea = DROPAREA; } droparea.style.visibility = "hidden"; } function processZipFile(file, event) { var reader = new FileReader(); reader.readAsArrayBuffer(file); reader.onload = async function () { var zip = new JSZip(); var zipData = await zip.loadAsync(reader.result); const containerPath = "META-INF/container.xml"; if (!zipData.files[containerPath]) { $('html').css('cursor', 'auto'); alert("META-INF/container.xml not found in ZIP"); return; } var containerXmlText = await zipData.files[containerPath].async("text"); var parser = new DOMParser(); var xmlDoc = parser.parseFromString(containerXmlText, "application/xml"); var rootfiles = xmlDoc.querySelectorAll("rootfile"); if (!rootfiles.length) { $('html').css('cursor', 'auto'); alert("No elements found in container.xml"); return; } var selectedFile = null; for (const rootfile of rootfiles) { var filePath = rootfile.getAttribute("full-path"); if (filePath && filePath.endsWith(".mscx")) { selectedFile = filePath; break; } } if (!selectedFile) { for (const rootfile of rootfiles) { var filePath = rootfile.getAttribute("full-path"); if (filePath === "score.xml") { selectedFile = filePath; break; } } } if (!selectedFile || !zipData.files[selectedFile]) { $('html').css('cursor', 'auto'); alert("No valid .mscx or score.xml file found in ZIP"); return; } var extractedContent = await zipData.files[selectedFile].async("text"); if (event.shiftKey) { replaceEditorContentWithHumdrumFile(extractedContent); } else { EDITOR.setValue(extractedContent, -1); } $('html').css('cursor', 'auto'); }; } function setupDropArea(target) { if (!target) { target = "#dropArea"; } var droparea = document.querySelector(target); DROPAREA = droparea; window.addEventListener('dragenter', function(event) { showDropArea(); }); droparea.addEventListener('dragenter', allowDrag); droparea.addEventListener('dragover', allowDrag); droparea.addEventListener('dragleave', function(event) { hideDropArea(); }); droparea.addEventListener('drop', handleDrop); } function showDropArea(droparea) { if (!droparea) { droparea = DROPAREA; } droparea.style.visibility = "visible"; }