index.js 25 KB

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