index.js 28 KB

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