index.js 24 KB

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