index.js 31 KB

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