index.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. import { OpenSheetMusicDisplay } from '../src/OpenSheetMusicDisplay/OpenSheetMusicDisplay';
  2. /*jslint browser:true */
  3. (function () {
  4. "use strict";
  5. var openSheetMusicDisplay;
  6. var sampleFolder = process.env.STATIC_FILES_SUBFOLDER ? process.env.STATIC_FILES_SUBFOLDER + "/" : "",
  7. samples = {
  8. "Beethoven, L.v. - An die ferne Geliebte": "Beethoven_AnDieFerneGeliebte.xml",
  9. "Clementi, M. - Sonatina Op.36 No.1 Pt.1": "MuzioClementi_SonatinaOpus36No1_Part1.xml",
  10. "Clementi, M. - Sonatina Op.36 No.1 Pt.2": "MuzioClementi_SonatinaOpus36No1_Part2.xml",
  11. "Clementi, M. - Sonatina Op.36 No.3 Pt.1": "MuzioClementi_SonatinaOpus36No3_Part1.xml",
  12. "Clementi, M. - Sonatina Op.36 No.3 Pt.2": "MuzioClementi_SonatinaOpus36No3_Part2.xml",
  13. "Bach, J.S. - Praeludium in C-Dur BWV846 1": "JohannSebastianBach_PraeludiumInCDur_BWV846_1.xml",
  14. "Bach, J.S. - Air": "JohannSebastianBach_Air.xml",
  15. "Gounod, C. - Méditation": "CharlesGounod_Meditation.xml",
  16. "Haydn, J. - Concertante Cello": "JosephHaydn_ConcertanteCello.xml",
  17. "Joplin, S. - Elite Syncopations": "ScottJoplin_EliteSyncopations.xml",
  18. "Joplin, S. - The Entertainer": "ScottJoplin_The_Entertainer.xml",
  19. "Mozart, W.A. - An Chloe": "Mozart_AnChloe.xml",
  20. "Mozart, W.A. - Das Veilchen": "Mozart_DasVeilchen.xml",
  21. "Mozart, W.A. - Clarinet Quintet (Excerpt)": "Mozart_Clarinet_Quintet_Excerpt.mxl",
  22. "Mozart, W.A. - String Quartet in G, K. 387, 1st Mvmt Excerpt": "Mozart_String_Quartet_in_G_K._387_1st_Mvmnt_excerpt.musicxml",
  23. "Mozart/Holzer - Land der Berge (national anthem of Austria)": "Land_der_Berge.musicxml",
  24. "OSMD Function Test - All": "OSMD_function_test_all.xml",
  25. "OSMD Function Test - Accidentals": "OSMD_function_test_accidentals.musicxml",
  26. "OSMD Function Test - Autobeam": "OSMD_function_test_autobeam.musicxml",
  27. "OSMD Function Test - Auto-/Custom-Coloring": "OSMD_function_test_auto-custom-coloring-entchen.musicxml",
  28. "OSMD Function Test - Bar lines": "OSMD_function_test_bar_lines.musicxml",
  29. "OSMD Function Test - Color (from XML)": "OSMD_function_test_color.musicxml",
  30. "OSMD Function Test - Drumset": "OSMD_function_test_drumset.musicxml",
  31. "OSMD Function Test - Expressions": "OSMD_function_test_expressions.musicxml",
  32. "OSMD Function Test - Expressions Overlap": "OSMD_function_test_expressions_overlap.musicxml",
  33. "OSMD Function Test - Grace Notes": "OSMD_function_test_GraceNotes.xml",
  34. "OSMD Function Test - Invisible Notes": "OSMD_function_test_invisible_notes.musicxml",
  35. "OSMD Function Test - Selecting Measures To Draw": "OSMD_function_test_measuresToDraw_Beethoven_AnDieFerneGeliebte.xml",
  36. "OSMD Function Test - Notehead Shapes": "OSMD_function_test_noteheadShapes.musicxml",
  37. "OSMD Function Test - Ornaments": "OSMD_function_test_Ornaments.xml",
  38. "OSMD Function Test - Tremolo": "OSMD_Function_Test_Tremolo_2bars.musicxml",
  39. "Schubert, F. - An Die Musik": "Schubert_An_die_Musik.xml",
  40. "Actor, L. - Prelude (Large Sample, loading time)": "ActorPreludeSample.xml",
  41. "Anonymous - Saltarello": "Saltarello.mxl",
  42. "Debussy, C. - Mandoline": "Debussy_Mandoline.xml",
  43. "Levasseur, F. - Parlez Mois": "Parlez-moi.mxl",
  44. "Schumann, R. - Dichterliebe": "Dichterliebe01.xml",
  45. "Telemann, G.P. - Sonate-Nr.1.1-Dolce": "TelemannWV40.102_Sonate-Nr.1.1-Dolce.xml",
  46. "Telemann, G.P. - Sonate-Nr.1.2-Allegro": "TelemannWV40.102_Sonate-Nr.1.2-Allegro-F-Dur.xml",
  47. },
  48. zoom = 1.0,
  49. // HTML Elements in the page
  50. divControls,
  51. zoomControls,
  52. header,
  53. err,
  54. error_tr,
  55. canvas,
  56. selectSample,
  57. selectBounding,
  58. skylineDebug,
  59. bottomlineDebug,
  60. zoomIns,
  61. zoomOuts,
  62. zoomDivs,
  63. custom,
  64. nextCursorBtn,
  65. resetCursorBtn,
  66. followCursorCheckbox,
  67. showCursorBtn,
  68. hideCursorBtn,
  69. backendSelect,
  70. backendSelectDiv,
  71. debugReRenderBtn,
  72. debugClearBtn,
  73. selectPageSizes,
  74. printPdfBtns;
  75. // manage option setting and resetting for specific samples, e.g. in the autobeam sample autobeam is set to true, otherwise reset to previous state
  76. // TODO design a more elegant option state saving & restoring system, though that requires saving the options state in OSMD
  77. var minMeasureToDrawStashed = 1;
  78. var maxMeasureToDrawStashed = Number.MAX_SAFE_INTEGER;
  79. var measureToDrawRangeNeedsReset = false;
  80. var autobeamOptionNeedsReset = false;
  81. var autobeamOptionStashedValue = false;
  82. var autoCustomColoringOptionNeedsReset = false;
  83. var autoCustomColoringOptionStashedValue = false;
  84. var drawPartNamesOptionStashedValue = true;
  85. var drawPartAbbreviationsStashedValue = true;
  86. var drawPartNamesOptionNeedsReset = false;
  87. var showControls = true;
  88. var showExportPdfControl = false;
  89. var showPageFormatControl = false;
  90. var showZoomControl = true;
  91. var showHeader = true;
  92. var showDebugControls = false;
  93. if (process.env.OSMD_DEMO_TITLE) {
  94. document.title = process.env.OSMD_DEMO_TITLE;
  95. }
  96. // Initialization code
  97. function init() {
  98. var name, option;
  99. // Handle window parameter
  100. var paramEmbedded = findGetParameter('embedded');
  101. var paramShowControls = findGetParameter('showControls');
  102. var paramShowPageFormatControl = findGetParameter('showPageFormatControl');
  103. var paramShowExportPdfControl = findGetParameter('showExportPdfControl');
  104. var paramShowZoomControl = findGetParameter('showZoomControl');
  105. var paramShowHeader = findGetParameter('showHeader');
  106. var paramZoom = findGetParameter('zoom');
  107. var paramOverflow = findGetParameter('overflow');
  108. var paramOpenUrl = findGetParameter('openUrl');
  109. var paramDebugControls = findGetParameter('debugControls');
  110. var paramCompactMode = findGetParameter('compactMode');
  111. var paramMeasureRangeStart = findGetParameter('measureRangeStart');
  112. var paramMeasureRangeEnd = findGetParameter('measureRangeEnd');
  113. var paramPageFormat = findGetParameter('pageFormat');
  114. var paramPageBackgroundColor = findGetParameter('pageBackgroundColor');
  115. var paramBackendType = findGetParameter('backendType');
  116. var paramPageWidth = findGetParameter('pageWidth');
  117. var paramPageHeight = findGetParameter('pageHeight');
  118. showHeader = (paramShowHeader !== '0');
  119. showControls = false;
  120. if (paramEmbedded !== undefined) {
  121. showControls = paramShowControls !== '0';
  122. showZoomControl = paramShowZoomControl !== '0';
  123. showPageFormatControl = paramShowPageFormatControl !== '0';
  124. showExportPdfControl = paramShowExportPdfControl !== '0';
  125. }
  126. if (paramZoom !== undefined) {
  127. if (paramZoom > 0.1 && paramZoom < 5.0) {
  128. zoom = paramZoom;
  129. }
  130. }
  131. if (paramOverflow !== undefined && typeof paramOverflow === 'string') {
  132. if (paramOverflow === 'hidden' || paramOverflow === 'auto' || paramOverflow === 'scroll' || paramOverflow === 'visible') {
  133. document.body.style.overflow = paramOverflow;
  134. }
  135. }
  136. var compactMode = paramCompactMode && paramCompactMode !== '0';
  137. var measureRangeStart = paramMeasureRangeStart ? Number.parseInt(paramMeasureRangeStart) : 0;
  138. var measureRangeEnd = paramMeasureRangeEnd ? Number.parseInt(paramMeasureRangeEnd) : Number.MAX_SAFE_INTEGER;
  139. if (measureRangeStart && measureRangeEnd && measureRangeEnd < measureRangeStart) {
  140. console.log("[OSMD] warning: measure range end parameter should not be smaller than measure range start. We've set start measure = end measure now.")
  141. measureRangeStart = measureRangeEnd;
  142. }
  143. let pageFormat = paramPageFormat ? paramPageFormat : "Endless";
  144. if (paramPageHeight && paramPageWidth) {
  145. pageFormat = `${paramPageWidth}x${paramPageHeight}`
  146. }
  147. var pageBackgroundColor = paramPageBackgroundColor ? "#" + paramPageBackgroundColor : undefined; // vexflow format, see OSMDOptions. can't use # in parameters.
  148. //console.log("demo: osmd pagebgcolor: " + pageBackgroundColor);
  149. var backendType = (paramBackendType && paramBackendType.toLowerCase) ? paramBackendType : "svg";
  150. // set the backendSelect debug controls dropdown menu selected item
  151. //console.log("true: " + backendSelect && backendType.toLowerCase && backendType.toLowerCase() === "canvas");
  152. // TODO somehow backendSelect becomes undefined here:
  153. /*if (backendSelect && backendType.toLowerCase && backendType.toLowerCase() === "canvas") {
  154. console.log("here1");
  155. for (var i=0; i<backendSelect.options.length; i++) {
  156. if (backendSelect.options[i].value.toLowerCase() === "canvas") {
  157. backendSelect.selectedIndex = i;
  158. }
  159. }
  160. backendSelect.value = "Canvas";
  161. }*/
  162. divControls = document.getElementById('divControls');
  163. zoomControls = document.getElementById('zoomControls');
  164. header = document.getElementById('header');
  165. err = document.getElementById("error-td");
  166. error_tr = document.getElementById("error-tr");
  167. zoomDivs = [];
  168. zoomDivs.push(document.getElementById("zoom-str"));
  169. zoomDivs.push(document.getElementById("zoom-str-optional"));
  170. custom = document.createElement("option");
  171. selectSample = document.getElementById("selectSample");
  172. selectBounding = document.getElementById("selectBounding");
  173. skylineDebug = document.getElementById("skylineDebug");
  174. bottomlineDebug = document.getElementById("bottomlineDebug");
  175. zoomIns = [];
  176. zoomIns.push(document.getElementById("zoom-in-btn"));
  177. zoomIns.push(document.getElementById("zoom-in-btn-optional"));
  178. zoomOuts = [];
  179. zoomOuts.push(document.getElementById("zoom-out-btn"));
  180. zoomOuts.push(document.getElementById("zoom-out-btn-optional"));
  181. canvas = document.createElement("div");
  182. //canvas.id = 'osmdCanvasDiv';
  183. //canvas.style.overflowX = 'auto'; // enable horizontal scrolling
  184. nextCursorBtn = document.getElementById("next-cursor-btn");
  185. resetCursorBtn = document.getElementById("reset-cursor-btn");
  186. followCursorCheckbox = document.getElementById("follow-cursor-checkbox");
  187. showCursorBtn = document.getElementById("show-cursor-btn");
  188. hideCursorBtn = document.getElementById("hide-cursor-btn");
  189. backendSelect = document.getElementById("backend-select");
  190. backendSelectDiv = document.getElementById("backend-select-div");
  191. debugReRenderBtn = document.getElementById("debug-re-render-btn");
  192. debugClearBtn = document.getElementById("debug-clear-btn");
  193. selectPageSizes = [];
  194. selectPageSizes.push(document.getElementById("selectPageSize"));
  195. selectPageSizes.push(document.getElementById("selectPageSize-optional"));
  196. printPdfBtns = [];
  197. printPdfBtns.push(document.getElementById("print-pdf-btn"));
  198. printPdfBtns.push(document.getElementById("print-pdf-btn-optional"));
  199. //var defaultDisplayVisibleValue = "block"; // TODO in some browsers flow could be the better/default value
  200. var defaultVisibilityValue = "visible";
  201. var devDemoRunning = process.env.OSMD_DEBUG_CONTROLS;
  202. showDebugControls = paramDebugControls === '1' || (devDemoRunning && paramDebugControls !== '0')
  203. if (showDebugControls) {
  204. var elementsToEnable = [
  205. selectSample, selectBounding, selectPageSize, backendSelect, backendSelectDiv, divControls
  206. ];
  207. for (var i=0; i<elementsToEnable.length; i++) {
  208. if (elementsToEnable[i]) { // make sure this element is not null/exists in the index.html, e.g. github.io demo has different index.html
  209. if (elementsToEnable[i].style) {
  210. elementsToEnable[i].style.visibility = defaultVisibilityValue;
  211. elementsToEnable[i].style.opacity = 1.0;
  212. }
  213. }
  214. }
  215. } else {
  216. if (divControls) {
  217. divControls.style.display = "none";
  218. }
  219. }
  220. const optionalControls = document.getElementById('optionalControls');
  221. if (optionalControls) {
  222. if (showControls) {
  223. optionalControls.style.visibility = defaultVisibilityValue;
  224. optionalControls.style.opacity = 0.8;
  225. } else {
  226. optionalControls.style.display = 'none';
  227. }
  228. }
  229. if (!showHeader) {
  230. if (header) {
  231. header.style.display = 'none';
  232. }
  233. } else {
  234. if (header) {
  235. header.style.opacity = 1.0;
  236. }
  237. }
  238. // Hide error
  239. error();
  240. if (showControls) {
  241. const optionalControls = document.getElementById('optionalControls');
  242. if (optionalControls) {
  243. optionalControls.style.opacity = 1.0;
  244. // optionalControls.appendChild(zoomControlsButtons);
  245. // optionalControls.appendChild(zoomControlsString);
  246. optionalControls.style.position = 'absolute';
  247. optionalControls.style.zIndex = '10';
  248. optionalControls.style.right = '10px';
  249. // optionalControls.style.padding = '10px';
  250. }
  251. if (showZoomControl) {
  252. const zoomControlsButtonsColumn = document.getElementById('zoomControlsButtons-optional-column');
  253. zoomControlsButtonsColumn.style.opacity = 1.0;
  254. // const zoomControlsButtons = document.getElementById('zoomControlsButtons-optional');
  255. // zoomControlsButtons.style.opacity = 1.0;
  256. const zoomControlsString = document.getElementById('zoom-str-optional'); // actually === zoomDivs[1] above
  257. if (zoomControlsString) {
  258. zoomControlsString.innerHTML = Math.floor(zoom * 100.0) + "%";
  259. zoomControlsString.style.display = 'inline';
  260. // zoomControlsString.style.padding = '10px';
  261. }
  262. }
  263. if (showExportPdfControl) {
  264. const exportPdfButtonColumn = document.getElementById('print-pdf-btn-optional-column');
  265. if (exportPdfButtonColumn) {
  266. exportPdfButtonColumn.style.opacity = 1.0;
  267. }
  268. }
  269. const pageFormatControlColumn = document.getElementById("selectPageSize-optional-column");
  270. if (pageFormatControlColumn) {
  271. if (showPageFormatControl) {
  272. pageFormatControlColumn.style.opacity = 1.0;
  273. } else {
  274. // showPageFormatControlColumn.innerHTML = "";
  275. // pageFormatControlColumn.style.minWidth = 0;
  276. // pageFormatControlColumn.style.width = 0;
  277. pageFormatControlColumn.style.display = 'none'; // squeezes buttons/columns
  278. // pageFormatControlColumn.style.visibility = 'hidden';
  279. // const optionalControlsColumnContainer = document.getElementById("optionalControlsColumnContainer");
  280. // optionalControlsColumnContainer.removeChild(pageFormatControlColumn);
  281. // optionalControlsColumnContainer.width *= 0.66;
  282. // optionalControls.witdh *= 0.66;
  283. // optionalControls.focus();
  284. }
  285. }
  286. }
  287. // Create select
  288. for (name in samples) {
  289. if (samples.hasOwnProperty(name)) {
  290. option = document.createElement("option");
  291. option.value = samples[name];
  292. option.textContent = name;
  293. }
  294. if (selectSample) {
  295. selectSample.appendChild(option);
  296. }
  297. }
  298. if (selectSample) {
  299. selectSample.onchange = selectSampleOnChange;
  300. }
  301. if (selectBounding) {
  302. selectBounding.onchange = selectBoundingOnChange;
  303. }
  304. for (const selectPageSize of selectPageSizes) {
  305. if (selectPageSize) {
  306. selectPageSize.onchange = function (evt) {
  307. var value = evt.target.value;
  308. openSheetMusicDisplay.setPageFormat(value);
  309. openSheetMusicDisplay.render();
  310. };
  311. }
  312. }
  313. for (const printPdfBtn of printPdfBtns) {
  314. if (printPdfBtn) {
  315. printPdfBtn.onclick = function () {
  316. openSheetMusicDisplay.createPdf();
  317. }
  318. }
  319. }
  320. // Pre-select default music piece
  321. custom.appendChild(document.createTextNode("Custom"));
  322. // Create zoom controls
  323. for (const zoomIn of zoomIns) {
  324. if (zoomIn) {
  325. zoomIn.onclick = function () {
  326. zoom *= 1.2;
  327. scale();
  328. };
  329. }
  330. }
  331. for (const zoomOut of zoomOuts) {
  332. if (zoomOut) {
  333. zoomOut.onclick = function () {
  334. zoom /= 1.2;
  335. scale();
  336. };
  337. }
  338. }
  339. if (skylineDebug) {
  340. skylineDebug.onclick = function () {
  341. openSheetMusicDisplay.DrawSkyLine = !openSheetMusicDisplay.DrawSkyLine;
  342. }
  343. }
  344. if (bottomlineDebug) {
  345. bottomlineDebug.onclick = function () {
  346. openSheetMusicDisplay.DrawBottomLine = !openSheetMusicDisplay.DrawBottomLine;
  347. }
  348. }
  349. if (debugReRenderBtn) {
  350. debugReRenderBtn.onclick = function () {
  351. rerender();
  352. }
  353. }
  354. if (debugClearBtn) {
  355. debugClearBtn.onclick = function () {
  356. openSheetMusicDisplay.clear();
  357. }
  358. }
  359. // Create OSMD object and canvas
  360. openSheetMusicDisplay = new OpenSheetMusicDisplay(canvas, {
  361. autoResize: true,
  362. backend: backendType,
  363. //backend: "canvas",
  364. disableCursor: false,
  365. drawingParameters: compactMode ? "compact" : "default", // try compact (instead of default)
  366. drawPartNames: true, // try false
  367. // drawTitle: false,
  368. // drawSubtitle: false,
  369. drawFingerings: true,
  370. fingeringPosition: "left", // left is default. try right. experimental: auto, above, below.
  371. // fingeringInsideStafflines: "true", // default: false. true draws fingerings directly above/below notes
  372. setWantedStemDirectionByXml: true, // try false, which was previously the default behavior
  373. // drawUpToMeasureNumber: 3, // draws only up to measure 3, meaning it draws measure 1 to 3 of the piece.
  374. drawFromMeasureNumber : measureRangeStart,
  375. drawUpToMeasureNumber : measureRangeEnd,
  376. //drawMeasureNumbers: false, // disable drawing measure numbers
  377. //measureNumberInterval: 4, // draw measure numbers only every 4 bars (and at the beginning of a new system)
  378. // coloring options
  379. coloringEnabled: true,
  380. // defaultColorNotehead: "#CC0055", // try setting a default color. default is black (undefined)
  381. // defaultColorStem: "#BB0099",
  382. autoBeam: false, // try true, OSMD Function Test AutoBeam sample
  383. autoBeamOptions: {
  384. beam_rests: false,
  385. beam_middle_rests_only: false,
  386. //groups: [[3,4], [1,1]],
  387. maintain_stem_directions: false
  388. },
  389. pageFormat: pageFormat,
  390. pageBackgroundColor: pageBackgroundColor,
  391. // tupletsBracketed: true, // creates brackets for all tuplets except triplets, even when not set by xml
  392. // tripletsBracketed: true,
  393. // tupletsRatioed: true, // unconventional; renders ratios for tuplets (3:2 instead of 3 for triplets)
  394. });
  395. openSheetMusicDisplay.setLogLevel('info'); // set this to 'debug' if you want to see more detailed control flow information in console
  396. document.body.appendChild(canvas);
  397. window.addEventListener("keydown", function (e) {
  398. var event = window.event ? window.event : e;
  399. if (event.keyCode === 39) {
  400. openSheetMusicDisplay.cursor.next();
  401. }
  402. });
  403. nextCursorBtn.addEventListener("click", function () {
  404. openSheetMusicDisplay.cursor.next();
  405. });
  406. resetCursorBtn.addEventListener("click", function () {
  407. openSheetMusicDisplay.cursor.reset();
  408. });
  409. if (followCursorCheckbox) {
  410. followCursorCheckbox.onclick = function () {
  411. openSheetMusicDisplay.FollowCursor = !openSheetMusicDisplay.FollowCursor;
  412. }
  413. }
  414. hideCursorBtn.addEventListener("click", function () {
  415. if (openSheetMusicDisplay.cursor) {
  416. openSheetMusicDisplay.cursor.hide();
  417. } else {
  418. console.info("Can't hide cursor, as it was disabled (e.g. by drawingParameters).");
  419. }
  420. });
  421. showCursorBtn.addEventListener("click", function () {
  422. if (openSheetMusicDisplay.cursor) {
  423. openSheetMusicDisplay.cursor.show();
  424. } else {
  425. console.info("Can't show cursor, as it was disabled (e.g. by drawingParameters).");
  426. }
  427. });
  428. backendSelect.addEventListener("change", function (e) {
  429. var value = e.target.value;
  430. var createNewOsmd = true;
  431. if (createNewOsmd) {
  432. // clears the canvas element
  433. canvas.innerHTML = "";
  434. openSheetMusicDisplay = new OpenSheetMusicDisplay(canvas, { backend: value });
  435. openSheetMusicDisplay.setLogLevel('info'); // set this to 'debug' if you want to get more detailed control flow information
  436. } else {
  437. // alternative, doesn't work yet, see setOptions():
  438. openSheetMusicDisplay.setOptions({ backend: value });
  439. }
  440. console.log("[OSMD] selectSampleOnChange addEventListener change");
  441. // selectSampleOnChange();
  442. });
  443. if (paramOpenUrl !== undefined) {
  444. if (openSheetMusicDisplay.getLogLevel() < 2) { // debug or trace
  445. console.log("[OSMD] selectSampleOnChange with " + paramOpenUrl);
  446. }
  447. // DEBUG: cause an error for a certain sample, for testing
  448. // if (paramOpenUrl.startsWith("Beethoven")) {
  449. // paramOpenUrl.causeError();
  450. // }
  451. selectSampleOnChange(paramOpenUrl);
  452. } else {
  453. if (openSheetMusicDisplay.getLogLevel() < 2) { // debug or trace
  454. console.log("[OSMD] selectSampleOnChange without param");
  455. }
  456. selectSampleOnChange();
  457. }
  458. }
  459. function findGetParameter(parameterName) {
  460. // special treatment for the openUrl parameter, because different systems attach different arguments to an URL.
  461. // because of CORS (cross-origin safety restrictions), you can only load an xml file from the same origin (server).
  462. // test parameter: ?openUrl=https://opensheetmusiceducation.org/index.php?gf-download=2020%2F01%2FJohannSebastianBach_PraeludiumInCDur_BWV846_1.xml&endUrl&form-id=1&field-id=4&hash=c4ba271ef08204a26cbd4cd2d751c53b78f238c25ddbb1f343e1172f2ce2aa53
  463. // (enable the console.log at the end of this method for testing)
  464. // working test parameter in local demo: ?openUrl=OSMD_function_test_all.xml&endUrl
  465. if (parameterName === 'openUrl') {
  466. let startParameterName = 'openUrl=';
  467. let endParameterName = '&endUrl';
  468. let openUrlIndex = location.search.indexOf(startParameterName);
  469. if (openUrlIndex < 0) {
  470. return undefined;
  471. }
  472. let endIndex = location.search.indexOf(endParameterName) + endParameterName.length;
  473. if (endIndex < 0) {
  474. console.log("[OSMD] If using openUrl as a parameter, you have to end it with '&endUrl'. openUrl parameter omitted.");
  475. return undefined;
  476. }
  477. let urlString = location.search.substring(openUrlIndex + startParameterName.length, endIndex - endParameterName.length);
  478. //console.log("openUrl: " + urlString);
  479. return urlString;
  480. }
  481. let result = undefined;
  482. let tmp = [];
  483. location.search
  484. .substr(1)
  485. .split('&')
  486. .forEach(function (item) {
  487. tmp = item.split('=');
  488. if (tmp[0] === parameterName) {
  489. result = decodeURIComponent(tmp[1]);
  490. //console.log('Found param:' + parameterName + ' = ' + result);
  491. }
  492. });
  493. return result;
  494. }
  495. function selectBoundingOnChange(evt) {
  496. var value = evt.target.value;
  497. openSheetMusicDisplay.DrawBoundingBox = value;
  498. }
  499. function selectSampleOnChange(str) {
  500. error();
  501. disable();
  502. var isCustom = typeof str === "string";
  503. if (!isCustom) {
  504. if (selectSample) {
  505. str = sampleFolder + selectSample.value;
  506. } else {
  507. if (samples && samples.length > 0) {
  508. str = sampleFolder + samples[0];
  509. } else {
  510. return; // no sample to load right now
  511. }
  512. }
  513. }
  514. // zoom = 1.0;
  515. setSampleSpecificOptions(str, isCustom);
  516. openSheetMusicDisplay.load(str).then(
  517. function () {
  518. // This gives you access to the osmd object in the console. Do not use in productive code
  519. window.osmd = openSheetMusicDisplay;
  520. openSheetMusicDisplay.zoom = zoom;
  521. return openSheetMusicDisplay.render();
  522. },
  523. function (e) {
  524. errorLoadingOrRenderingSheet(e, "rendering");
  525. }
  526. ).then(
  527. function () {
  528. return onLoadingEnd(isCustom);
  529. }, function (e) {
  530. errorLoadingOrRenderingSheet(e, "loading");
  531. onLoadingEnd(isCustom);
  532. }
  533. );
  534. }
  535. function setSampleSpecificOptions(str, isCustom) {
  536. if (!isCustom && str.includes("measuresToDraw")) { // set options for measuresToDraw sample
  537. // stash previously set range of measures to draw
  538. if (!measureToDrawRangeNeedsReset) { // only stash once, when measuresToDraw called multiple times in a row
  539. minMeasureToDrawStashed = openSheetMusicDisplay.EngravingRules.MinMeasureToDrawIndex + 1;
  540. maxMeasureToDrawStashed = openSheetMusicDisplay.EngravingRules.MaxMeasureToDrawIndex + 1;
  541. }
  542. measureToDrawRangeNeedsReset = true;
  543. // for debugging: draw from a random range of measures
  544. let minMeasureToDraw = Math.ceil(Math.random() * 15); // measures start at 1 (measureIndex = measure number - 1 elsewhere)
  545. let maxMeasureToDraw = Math.ceil(Math.random() * 15);
  546. if (minMeasureToDraw > maxMeasureToDraw) {
  547. minMeasureToDraw = maxMeasureToDraw;
  548. let a = minMeasureToDraw;
  549. maxMeasureToDraw = a;
  550. }
  551. //minMeasureToDraw = 1; // set your custom indexes here. Drawing only one measure can be a special case
  552. //maxMeasureToDraw = 1;
  553. console.log("drawing measures in the range: [" + minMeasureToDraw + "," + maxMeasureToDraw + "]");
  554. openSheetMusicDisplay.setOptions({
  555. drawFromMeasureNumber: minMeasureToDraw,
  556. drawUpToMeasureNumber: maxMeasureToDraw
  557. });
  558. } else if (measureToDrawRangeNeedsReset) { // reset for other samples
  559. openSheetMusicDisplay.setOptions({
  560. drawFromMeasureNumber: minMeasureToDrawStashed,
  561. drawUpToMeasureNumber: maxMeasureToDrawStashed
  562. });
  563. measureToDrawRangeNeedsReset = false;
  564. }
  565. // Enable Boomwhacker-like coloring for OSMD Function Test - Auto-Coloring (Boomwhacker-like, custom color set)
  566. if (!isCustom && str.includes("auto-custom-coloring")) { // set options for auto coloring sample
  567. autoCustomColoringOptionNeedsReset = true;
  568. //openSheetMusicDisplay.setOptions({coloringMode: 1}); // Auto-Coloring with pre-defined colors
  569. openSheetMusicDisplay.setOptions({
  570. coloringMode: 2, // custom coloring set. 0 would be XML, 1 autocoloring
  571. coloringSetCustom: ["#d82c6b", "#F89D15", "#FFE21A", "#4dbd5c", "#009D96", "#43469d", "#76429c", "#ff0000"],
  572. // last color value of coloringSetCustom is for rest notes
  573. colorStemsLikeNoteheads: true
  574. });
  575. } else if (autoCustomColoringOptionNeedsReset) {
  576. openSheetMusicDisplay.setOptions({ // set default values. better would be to restore to stashed values, but unnecessarily complex for demo
  577. coloringMode: 0,
  578. colorStemsLikeNoteheads: false,
  579. coloringSetCustom: null
  580. });
  581. autoCustomColoringOptionNeedsReset = false;
  582. }
  583. if (!isCustom && str.includes("autobeam")) {
  584. autobeamOptionStashedValue = openSheetMusicDisplay.EngravingRules.AutoBeamNotes; // stash previously set value, to restore later
  585. autobeamOptionNeedsReset = true;
  586. openSheetMusicDisplay.setOptions({ autoBeam: true });
  587. } else if (autobeamOptionNeedsReset) {
  588. openSheetMusicDisplay.setOptions({ autoBeam: autobeamOptionStashedValue });
  589. autobeamOptionNeedsReset = false;
  590. }
  591. if (!isCustom && str.includes("Schubert_An_die_Musik")) { // TODO weird layout bug here with part names. but shouldn't be in score anyways
  592. drawPartNamesOptionStashedValue = openSheetMusicDisplay.EngravingRules.RenderPartNames;
  593. drawPartAbbreviationsStashedValue = openSheetMusicDisplay.EngravingRules.RenderPartAbbreviations;
  594. openSheetMusicDisplay.setOptions({ drawPartNames: false, drawPartAbbreviations: false }); // TODO sets osmd.drawingParameters.DrawPartNames! also check EngravingRules.RenderPartAbbreviations, was false
  595. drawPartNamesOptionNeedsReset = true;
  596. } else if (drawPartNamesOptionNeedsReset) {
  597. openSheetMusicDisplay.setOptions({ drawPartNames: drawPartNamesOptionStashedValue, drawPartAbbreviations: drawPartAbbreviationsStashedValue });
  598. drawPartNamesOptionNeedsReset = false;
  599. }
  600. }
  601. function errorLoadingOrRenderingSheet(e, loadingOrRenderingString) {
  602. var errorString = "Error " + loadingOrRenderingString + " sheet: " + e;
  603. // if (process.env.DEBUG) { // people may not set a debug environment variable for the demo.
  604. // Always giving a StackTrace might give us more and better error reports.
  605. // TODO for a release, StackTrace control could be reenabled
  606. errorString += "\n" + "StackTrace: \n" + e.stack;
  607. // }
  608. console.warn(errorString);
  609. }
  610. function onLoadingEnd(isCustom) {
  611. // Remove option from select
  612. if (!isCustom && custom.parentElement === selectSample) {
  613. selectSample.removeChild(custom);
  614. }
  615. // Enable controls again
  616. enable();
  617. }
  618. function logCanvasSize() {
  619. for (const zoomDiv of zoomDivs) {
  620. if (zoomDiv) {
  621. zoomDiv.innerHTML = Math.floor(zoom * 100.0) + "%";
  622. }
  623. }
  624. }
  625. function scale() {
  626. disable();
  627. window.setTimeout(function () {
  628. openSheetMusicDisplay.zoom = zoom;
  629. openSheetMusicDisplay.render();
  630. enable();
  631. }, 0);
  632. }
  633. function rerender() {
  634. disable();
  635. window.setTimeout(function () {
  636. if (openSheetMusicDisplay.IsReadyToRender()) {
  637. openSheetMusicDisplay.render();
  638. } else {
  639. console.log("[OSMD demo] Looses context!"); // TODO not sure that this message is reasonable, renders fine anyways. maybe vexflow context lost?
  640. selectSampleOnChange(); // reload sample e.g. after osmd.clear()
  641. }
  642. enable();
  643. }, 0);
  644. }
  645. function error(errString) {
  646. if (!errString) {
  647. error_tr.style.display = "none";
  648. } else {
  649. console.log("[OSMD demo] error: " + errString)
  650. err.textContent = errString;
  651. error_tr.style.display = "";
  652. canvas.width = canvas.height = 0;
  653. enable();
  654. }
  655. }
  656. // Enable/Disable Controls
  657. function disable() {
  658. document.body.style.opacity = 0.3;
  659. setDisabledForControls("disabled");
  660. }
  661. function enable() {
  662. document.body.style.opacity = 1;
  663. setDisabledForControls("");
  664. logCanvasSize();
  665. }
  666. function setDisabledForControls(disabledValue) {
  667. if (selectSample) {
  668. selectSample.disabled = disabledValue;
  669. }
  670. for (const zoomIn of zoomIns) {
  671. if (zoomIn) {
  672. zoomIn.disabled = disabledValue;
  673. }
  674. }
  675. for (const zoomOut of zoomOuts) {
  676. if (zoomOut) {
  677. zoomOut.disabled = disabledValue;
  678. }
  679. }
  680. }
  681. // Register events: load, drag&drop
  682. window.addEventListener("load", function () {
  683. init();
  684. });
  685. window.addEventListener("dragenter", function (event) {
  686. event.preventDefault();
  687. disable();
  688. });
  689. window.addEventListener("dragover", function (event) {
  690. event.preventDefault();
  691. });
  692. window.addEventListener("dragleave", function (event) {
  693. enable();
  694. });
  695. window.addEventListener("drop", function (event) {
  696. event.preventDefault();
  697. if (!event.dataTransfer || !event.dataTransfer.files || event.dataTransfer.files.length === 0) {
  698. return;
  699. }
  700. // Add "Custom..." score
  701. selectSample.appendChild(custom);
  702. custom.selected = "selected";
  703. // Read dragged file
  704. var reader = new FileReader();
  705. reader.onload = function (res) {
  706. selectSampleOnChange(res.target.result);
  707. };
  708. var filename = event.dataTransfer.files[0].name;
  709. if (filename.toLowerCase().indexOf(".xml") > 0
  710. || filename.toLowerCase().indexOf(".musicxml") > 0) {
  711. reader.readAsText(event.dataTransfer.files[0]);
  712. } else if (event.dataTransfer.files[0].name.toLowerCase().indexOf(".mxl") > 0) {
  713. reader.readAsBinaryString(event.dataTransfer.files[0]);
  714. }
  715. else {
  716. alert("No vaild .xml/.mxl/.musicxml file!");
  717. }
  718. });
  719. }());