index.js 26 KB

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