index.js 27 KB

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