index.js 35 KB

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