index.js 31 KB

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