index.js 30 KB

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