index.js 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. import { OpenSheetMusicDisplay } from '../src/OpenSheetMusicDisplay/OpenSheetMusicDisplay';
  2. import { BackendType } from '../src/OpenSheetMusicDisplay/OSMDOptions';
  3. import { PlaybackManager, LinearTimingSource, BasicAudioPlayer, ControlPanel } from '../src/Playback';
  4. import * as jsPDF from '../node_modules/jspdf-yworks/dist/jspdf.min';
  5. import * as svg2pdf from '../node_modules/svg2pdf.js/dist/svg2pdf.min';
  6. import { TransposeCalculator } from '../src/Plugins/Transpose/TransposeCalculator';
  7. /*jslint browser:true */
  8. (function () {
  9. "use strict";
  10. var openSheetMusicDisplay;
  11. var sampleFolder = process.env.STATIC_FILES_SUBFOLDER ? process.env.STATIC_FILES_SUBFOLDER + "/" : "",
  12. samples = {
  13. "Beethoven, L.v. - An die ferne Geliebte": "Beethoven_AnDieFerneGeliebte.xml",
  14. "Clementi, M. - Sonatina Op.36 No.1 Pt.1": "MuzioClementi_SonatinaOpus36No1_Part1.xml",
  15. "Clementi, M. - Sonatina Op.36 No.1 Pt.2": "MuzioClementi_SonatinaOpus36No1_Part2.xml",
  16. "Clementi, M. - Sonatina Op.36 No.3 Pt.1": "MuzioClementi_SonatinaOpus36No3_Part1.xml",
  17. "Clementi, M. - Sonatina Op.36 No.3 Pt.2": "MuzioClementi_SonatinaOpus36No3_Part2.xml",
  18. "Bach, J.S. - Praeludium in C-Dur BWV846 1": "JohannSebastianBach_PraeludiumInCDur_BWV846_1.xml",
  19. "Bach, J.S. - Air": "JohannSebastianBach_Air.xml",
  20. "Gounod, C. - Méditation": "CharlesGounod_Meditation.xml",
  21. "Haydn, J. - Concertante Cello": "JosephHaydn_ConcertanteCello.xml",
  22. "Joplin, S. - Elite Syncopations": "ScottJoplin_EliteSyncopations.xml",
  23. "Joplin, S. - The Entertainer": "ScottJoplin_The_Entertainer.xml",
  24. "Mozart, W.A. - An Chloe": "Mozart_AnChloe.xml",
  25. "Mozart, W.A. - Das Veilchen": "Mozart_DasVeilchen.xml",
  26. "Mozart, W.A. - Clarinet Quintet (Excerpt)": "Mozart_Clarinet_Quintet_Excerpt.mxl",
  27. "Mozart, W.A. - String Quartet in G, K. 387, 1st Mvmt Excerpt": "Mozart_String_Quartet_in_G_K._387_1st_Mvmnt_excerpt.musicxml",
  28. "Mozart/Holzer - Land der Berge (national anthem of Austria)": "Land_der_Berge.musicxml",
  29. "OSMD Function Test - All": "OSMD_function_test_all.xml",
  30. "OSMD Function Test - Accidentals": "OSMD_function_test_accidentals.musicxml",
  31. "OSMD Function Test - Autobeam": "OSMD_function_test_autobeam.musicxml",
  32. "OSMD Function Test - Auto-/Custom-Coloring": "OSMD_function_test_auto-custom-coloring-entchen.musicxml",
  33. "OSMD Function Test - Bar lines": "OSMD_function_test_bar_lines.musicxml",
  34. "OSMD Function Test - Chord Symbols": "OSMD_function_test_chord_symbols.musicxml",
  35. "OSMD Function Test - Chord Spacing": "OSMD_function_test_chord_spacing.mxl",
  36. "OSMD Function Test - Chord Symbols - Various Chords": "OSMD_function_test_chord_tests_various.musicxml",
  37. "OSMD Function Test - Chord Symbols - BrookeWestSample": "BrookeWestSample.mxl",
  38. "OSMD Function Test - Color (from XML)": "OSMD_function_test_color.musicxml",
  39. "OSMD Function Test - Container height (compacttight mode)": "OSMD_Function_Test_Container_height.musicxml",
  40. "OSMD Function Test - Drumset": "OSMD_function_test_drumset.musicxml",
  41. "OSMD Function Test - Drums on one Line": "OSMD_Function_Test_Drums_one_line_snare_plus_piano.musicxml",
  42. "OSMD Function Test - Expressions": "OSMD_function_test_expressions.musicxml",
  43. "OSMD Function Test - Expressions Overlap": "OSMD_function_test_expressions_overlap.musicxml",
  44. "OSMD Function Test - Grace Notes": "OSMD_function_test_GraceNotes.xml",
  45. "OSMD Function Test - Metronome Marks": "OSMD_function_test_metronome_marks.mxl",
  46. "OSMD Function Test - Multiple Rest Measures": "OSMD_function_test_multiple_rest_measures.musicxml",
  47. "OSMD Function Test - Invisible Notes": "OSMD_function_test_invisible_notes.musicxml",
  48. "OSMD Function Test - Notehead Shapes": "OSMD_function_test_noteheadShapes.musicxml",
  49. "OSMD Function Test - Ornaments": "OSMD_function_test_Ornaments.xml",
  50. "OSMD Function Test - Pedals": "OSMD_Function_Test_Pedals.musicxml",
  51. "OSMD Function Test - Selecting Measures To Draw": "OSMD_function_test_measuresToDraw_Beethoven_AnDieFerneGeliebte.xml",
  52. "OSMD Function Test - System and Page Breaks": "OSMD_Function_Test_System_and_Page_Breaks_4_pages.mxl",
  53. "OSMD Function Test - Tabulature": "OSMD_Function_Test_Tabulature_hayden_study_1.mxl",
  54. "OSMD Function Test - Tabulature MultiBends": "OSMD_Function_Test_Tablature_Multibends.musicxml",
  55. "OSMD Function Test - Tabulature All Effects": "OSMD_Function_Test_Tablature_Alleffects.musicxml",
  56. "OSMD Function Test - Tremolo": "OSMD_Function_Test_Tremolo_2bars.musicxml",
  57. "OSMD Function Test - Labels": "OSMD_Function_Test_Labels.musicxml",
  58. "OSMD Function Test - High Slur Test": "test_slurs_highNotes.musicxml",
  59. "OSMD Function Test - Auto Multirest Measures Single Staff": "Test_Auto_Multirest_1.musicxml",
  60. "OSMD Function Test - Auto Multirest Measures Multiple Staves": "Test_Auto_Multirest_2.musicxml",
  61. "OSMD Function Test - String number collisions": "test_string_number_collisions.musicxml",
  62. "OSMD Function Test - Repeat Stave Connectors": "OSMD_function_Test_Repeat.musicxml",
  63. "OSMD Function Test - Trill Lines": "OSMD_Trill_Line_Function_Test.musicxml",
  64. "OSMD Function Test - Voice Alignment": "OSMD_Function_Test_Voice_Alignment.musicxml",
  65. "Schubert, F. - An Die Musik": "Schubert_An_die_Musik.xml",
  66. "Actor, L. - Prelude (Large Sample, loading time)": "ActorPreludeSample.xml",
  67. "Actor, L. - Prelude (Large, No Print Part Names)": "ActorPreludeSample_PartName.xml",
  68. "Anonymous - Saltarello": "Saltarello.mxl",
  69. "Debussy, C. - Mandoline": "Debussy_Mandoline.xml",
  70. "Levasseur, F. - Parlez Mois": "Parlez-moi.mxl",
  71. "Schumann, R. - Dichterliebe": "Dichterliebe01.xml",
  72. "Telemann, G.P. - Sonate-Nr.1.1-Dolce": "TelemannWV40.102_Sonate-Nr.1.1-Dolce.xml",
  73. "Telemann, G.P. - Sonate-Nr.1.2-Allegro": "TelemannWV40.102_Sonate-Nr.1.2-Allegro-F-Dur.xml",
  74. },
  75. comments = {
  76. "Beethoven_AnDieFerneGeliebte.xml": ["Beethoven_AnDieFerneGeliebte_comments.xml", "Beethoven_AnDieFerneGeliebte_comments_2.xml"]
  77. },
  78. zoom = 1.0,
  79. // HTML Elements in the page
  80. divControls,
  81. zoomControls,
  82. header,
  83. err,
  84. error_tr,
  85. canvas,
  86. selectSample,
  87. selectBounding,
  88. skylineDebug,
  89. bottomlineDebug,
  90. zoomIns,
  91. zoomOuts,
  92. zoomDivs,
  93. custom,
  94. nextCursorBtn,
  95. resetCursorBtn,
  96. followCursorCheckbox,
  97. showCursorBtn,
  98. hideCursorBtn,
  99. backendSelect,
  100. backendSelectDiv,
  101. debugReRenderBtn,
  102. debugClearBtn,
  103. selectPageSizes,
  104. printPdfBtns,
  105. transpose,
  106. transposeBtn,
  107. performanceMode,
  108. performanceModeBtn,
  109. playbackControlsButton,
  110. playbackControl;
  111. // manage option setting and resetting for specific samples, e.g. in the autobeam sample autobeam is set to true, otherwise reset to previous state
  112. // TODO design a more elegant option state saving & restoring system, though that requires saving the options state in OSMD
  113. var minMeasureToDrawStashed = 1;
  114. var maxMeasureToDrawStashed = Number.MAX_SAFE_INTEGER;
  115. var measureToDrawRangeNeedsReset = false;
  116. var drawingParametersStashed = "default";
  117. var drawingParametersNeedsReset = false;
  118. var autobeamOptionNeedsReset = false;
  119. var autobeamOptionStashedValue = false;
  120. var autoCustomColoringOptionNeedsReset = false;
  121. var autoCustomColoringOptionStashedValue = false;
  122. var drawPartNamesOptionStashedValue = true;
  123. var drawPartAbbreviationsStashedValue = true;
  124. var drawPartNamesOptionNeedsReset = false;
  125. var pageBreaksOptionStashedValue = false;
  126. var pageBreaksOptionNeedsReset = false;
  127. var systemBreaksOptionStashedValue = false; // reset handled by pageBreaksOptionNeedsReset
  128. var showControls = true;
  129. var showExportPdfControl = false;
  130. var showPageFormatControl = false;
  131. var showZoomControl = true;
  132. var showHeader = true;
  133. var showDebugControls = false;
  134. if (process.env.OSMD_DEMO_TITLE) {
  135. document.title = process.env.OSMD_DEMO_TITLE;
  136. }
  137. // Initialization code
  138. function init() {
  139. var name, option;
  140. // Handle window parameter
  141. var paramEmbedded = findGetParameter('embedded');
  142. var paramShowControls = findGetParameter('showControls');
  143. var paramShowPageFormatControl = findGetParameter('showPageFormatControl');
  144. var paramShowExportPdfControl = findGetParameter('showExportPdfControl');
  145. var paramShowZoomControl = findGetParameter('showZoomControl');
  146. var paramShowHeader = findGetParameter('showHeader');
  147. var paramZoom = findGetParameter('zoom');
  148. var paramOverflow = findGetParameter('overflow');
  149. var paramOpenUrl = findGetParameter('openUrl');
  150. var paramDebugControls = findGetParameter('debugControls');
  151. var paramCompactMode = findGetParameter('compactMode');
  152. var paramMeasureRangeStart = findGetParameter('measureRangeStart');
  153. var paramMeasureRangeEnd = findGetParameter('measureRangeEnd');
  154. var paramPageFormat = findGetParameter('pageFormat');
  155. var paramPageBackgroundColor = findGetParameter('pageBackgroundColor');
  156. var paramBackendType = findGetParameter('backendType');
  157. var paramPageWidth = findGetParameter('pageWidth');
  158. var paramPageHeight = findGetParameter('pageHeight');
  159. var paramHorizontalScrolling = findGetParameter('horizontalScrolling');
  160. var paramSingleHorizontalStaffline = findGetParameter('singleHorizontalStaffline');
  161. showHeader = (paramShowHeader !== '0');
  162. showControls = false;
  163. if (paramEmbedded) {
  164. showControls = paramShowControls !== '0';
  165. showZoomControl = paramShowZoomControl !== '0';
  166. showPageFormatControl = paramShowPageFormatControl !== '0';
  167. showExportPdfControl = paramShowExportPdfControl !== '0';
  168. }
  169. if (paramZoom) {
  170. if (paramZoom > 0.1 && paramZoom < 5.0) {
  171. zoom = paramZoom;
  172. }
  173. }
  174. if (paramOverflow && typeof paramOverflow === 'string') {
  175. if (paramOverflow === 'hidden' || paramOverflow === 'auto' || paramOverflow === 'scroll' || paramOverflow === 'visible') {
  176. document.body.style.overflow = paramOverflow;
  177. }
  178. }
  179. var compactMode = paramCompactMode && paramCompactMode !== '0';
  180. var measureRangeStart = paramMeasureRangeStart ? Number.parseInt(paramMeasureRangeStart) : 0;
  181. var measureRangeEnd = paramMeasureRangeEnd ? Number.parseInt(paramMeasureRangeEnd) : Number.MAX_SAFE_INTEGER;
  182. if (measureRangeStart && measureRangeEnd && measureRangeEnd < measureRangeStart) {
  183. console.log("[OSMD] warning: measure range end parameter should not be smaller than measure range start. We've set start measure = end measure now.")
  184. measureRangeStart = measureRangeEnd;
  185. }
  186. let pageFormat = paramPageFormat ? paramPageFormat : "Endless";
  187. if (paramPageHeight && paramPageWidth) {
  188. pageFormat = `${paramPageWidth}x${paramPageHeight}`
  189. }
  190. var pageBackgroundColor = paramPageBackgroundColor ? "#" + paramPageBackgroundColor : undefined; // vexflow format, see OSMDOptions. can't use # in parameters.
  191. //console.log("demo: osmd pagebgcolor: " + pageBackgroundColor);
  192. var backendType = (paramBackendType && paramBackendType.toLowerCase) ? paramBackendType : "svg";
  193. var horizontalScrolling = paramHorizontalScrolling === '1';
  194. var singleHorizontalStaffline = paramSingleHorizontalStaffline === '1';
  195. // set the backendSelect debug controls dropdown menu selected item
  196. //console.log("true: " + backendSelect && backendType.toLowerCase && backendType.toLowerCase() === "canvas");
  197. // TODO somehow backendSelect becomes undefined here:
  198. /*if (backendSelect && backendType.toLowerCase && backendType.toLowerCase() === "canvas") {
  199. console.log("here1");
  200. for (var i=0; i<backendSelect.options.length; i++) {
  201. if (backendSelect.options[i].value.toLowerCase() === "canvas") {
  202. backendSelect.selectedIndex = i;
  203. }
  204. }
  205. backendSelect.value = "Canvas";
  206. }*/
  207. divControls = document.getElementById('divControls');
  208. zoomControls = document.getElementById('zoomControls');
  209. header = document.getElementById('header');
  210. err = document.getElementById("error-td");
  211. error_tr = document.getElementById("error-tr");
  212. zoomDivs = [];
  213. zoomDivs.push(document.getElementById("zoom-str"));
  214. zoomDivs.push(document.getElementById("zoom-str-optional"));
  215. custom = document.createElement("option");
  216. selectSample = document.getElementById("selectSample");
  217. selectBounding = document.getElementById("selectBounding");
  218. skylineDebug = document.getElementById("skylineDebug");
  219. bottomlineDebug = document.getElementById("bottomlineDebug");
  220. performanceMode = false;
  221. performanceModeBtn = document.getElementById("performanceMode");
  222. zoomIns = [];
  223. zoomIns.push(document.getElementById("zoom-in-btn"));
  224. zoomIns.push(document.getElementById("zoom-in-btn-optional"));
  225. zoomOuts = [];
  226. zoomOuts.push(document.getElementById("zoom-out-btn"));
  227. zoomOuts.push(document.getElementById("zoom-out-btn-optional"));
  228. canvas = document.createElement("div");
  229. if (horizontalScrolling) {
  230. canvas.style.overflowX = 'auto'; // enable horizontal scrolling
  231. }
  232. //canvas.id = 'osmdCanvasDiv';
  233. //canvas.style.overflowX = 'auto'; // enable horizontal scrolling
  234. nextCursorBtn = document.getElementById("next-cursor-btn");
  235. resetCursorBtn = document.getElementById("reset-cursor-btn");
  236. followCursorCheckbox = document.getElementById("follow-cursor-checkbox");
  237. showCursorBtn = document.getElementById("show-cursor-btn");
  238. hideCursorBtn = document.getElementById("hide-cursor-btn");
  239. backendSelect = document.getElementById("backend-select");
  240. backendSelectDiv = document.getElementById("backend-select-div");
  241. debugReRenderBtn = document.getElementById("debug-re-render-btn");
  242. debugClearBtn = document.getElementById("debug-clear-btn");
  243. selectPageSizes = [];
  244. selectPageSizes.push(document.getElementById("selectPageSize"));
  245. selectPageSizes.push(document.getElementById("selectPageSize-optional"));
  246. printPdfBtns = [];
  247. printPdfBtns.push(document.getElementById("print-pdf-btn"));
  248. printPdfBtns.push(document.getElementById("print-pdf-btn-optional"));
  249. transpose = document.getElementById('transpose');
  250. transposeBtn = document.getElementById('transpose-btn');
  251. playbackControlsButton = document.getElementById("playback-settings-button")
  252. //var defaultDisplayVisibleValue = "block"; // TODO in some browsers flow could be the better/default value
  253. var defaultVisibilityValue = "visible";
  254. var devDemoRunning = process.env.OSMD_DEBUG_CONTROLS;
  255. showDebugControls = paramDebugControls === '1' || (devDemoRunning && paramDebugControls !== '0')
  256. if (showDebugControls) {
  257. var elementsToEnable = [
  258. selectSample, selectBounding, selectPageSize, backendSelect, backendSelectDiv, divControls
  259. ];
  260. for (var i=0; i<elementsToEnable.length; i++) {
  261. if (elementsToEnable[i]) { // make sure this element is not null/exists in the index.html, e.g. github.io demo has different index.html
  262. if (elementsToEnable[i].style) {
  263. elementsToEnable[i].style.visibility = defaultVisibilityValue;
  264. elementsToEnable[i].style.opacity = 1.0;
  265. }
  266. }
  267. }
  268. } else {
  269. if (divControls) {
  270. divControls.style.display = "none";
  271. }
  272. }
  273. const optionalControls = document.getElementById('optionalControls');
  274. if (optionalControls) {
  275. if (showControls) {
  276. optionalControls.style.visibility = defaultVisibilityValue;
  277. optionalControls.style.opacity = 0.8;
  278. } else {
  279. optionalControls.style.display = 'none';
  280. }
  281. }
  282. if (!showHeader) {
  283. if (header) {
  284. header.style.display = 'none';
  285. }
  286. } else {
  287. if (header) {
  288. header.style.opacity = 1.0;
  289. }
  290. }
  291. // Hide error
  292. error();
  293. if (showControls) {
  294. const optionalControls = document.getElementById('optionalControls');
  295. if (optionalControls) {
  296. optionalControls.style.opacity = 1.0;
  297. // optionalControls.appendChild(zoomControlsButtons);
  298. // optionalControls.appendChild(zoomControlsString);
  299. optionalControls.style.position = 'absolute';
  300. optionalControls.style.zIndex = '10';
  301. optionalControls.style.right = '10px';
  302. // optionalControls.style.padding = '10px';
  303. }
  304. if (showZoomControl) {
  305. const zoomControlsButtonsColumn = document.getElementById('zoomControlsButtons-optional-column');
  306. zoomControlsButtonsColumn.style.opacity = 1.0;
  307. // const zoomControlsButtons = document.getElementById('zoomControlsButtons-optional');
  308. // zoomControlsButtons.style.opacity = 1.0;
  309. const zoomControlsString = document.getElementById('zoom-str-optional'); // actually === zoomDivs[1] above
  310. if (zoomControlsString) {
  311. zoomControlsString.innerHTML = Math.floor(zoom * 100.0) + "%";
  312. zoomControlsString.style.display = 'inline';
  313. // zoomControlsString.style.padding = '10px';
  314. }
  315. }
  316. if (showExportPdfControl) {
  317. const exportPdfButtonColumn = document.getElementById('print-pdf-btn-optional-column');
  318. if (exportPdfButtonColumn) {
  319. exportPdfButtonColumn.style.opacity = 1.0;
  320. }
  321. }
  322. const pageFormatControlColumn = document.getElementById("selectPageSize-optional-column");
  323. if (pageFormatControlColumn) {
  324. if (showPageFormatControl) {
  325. pageFormatControlColumn.style.opacity = 1.0;
  326. } else {
  327. // showPageFormatControlColumn.innerHTML = "";
  328. // pageFormatControlColumn.style.minWidth = 0;
  329. // pageFormatControlColumn.style.width = 0;
  330. pageFormatControlColumn.style.display = 'none'; // squeezes buttons/columns
  331. // pageFormatControlColumn.style.visibility = 'hidden';
  332. // const optionalControlsColumnContainer = document.getElementById("optionalControlsColumnContainer");
  333. // optionalControlsColumnContainer.removeChild(pageFormatControlColumn);
  334. // optionalControlsColumnContainer.width *= 0.66;
  335. // optionalControls.witdh *= 0.66;
  336. // optionalControls.focus();
  337. }
  338. }
  339. }
  340. // Create select
  341. for (name in samples) {
  342. if (samples.hasOwnProperty(name)) {
  343. option = document.createElement("option");
  344. option.value = samples[name];
  345. option.textContent = name;
  346. }
  347. if (selectSample) {
  348. selectSample.appendChild(option);
  349. }
  350. }
  351. if (selectSample) {
  352. selectSample.onchange = selectSampleOnChange;
  353. }
  354. if (selectBounding) {
  355. selectBounding.onchange = selectBoundingOnChange;
  356. }
  357. for (const selectPageSize of selectPageSizes) {
  358. if (selectPageSize) {
  359. selectPageSize.onchange = function (evt) {
  360. var value = evt.target.value;
  361. openSheetMusicDisplay.setPageFormat(value);
  362. openSheetMusicDisplay.render();
  363. };
  364. }
  365. }
  366. for (const printPdfBtn of printPdfBtns) {
  367. if (printPdfBtn) {
  368. printPdfBtn.onclick = function () {
  369. createPdf();
  370. }
  371. }
  372. }
  373. // Pre-select default music piece
  374. custom.appendChild(document.createTextNode("Custom"));
  375. // Create zoom controls
  376. for (const zoomIn of zoomIns) {
  377. if (zoomIn) {
  378. zoomIn.onclick = function () {
  379. zoom *= 1.2;
  380. scale();
  381. };
  382. }
  383. }
  384. for (const zoomOut of zoomOuts) {
  385. if (zoomOut) {
  386. zoomOut.onclick = function () {
  387. zoom /= 1.2;
  388. scale();
  389. };
  390. }
  391. }
  392. if (skylineDebug) {
  393. skylineDebug.onclick = function () {
  394. openSheetMusicDisplay.DrawSkyLine = !openSheetMusicDisplay.DrawSkyLine;
  395. openSheetMusicDisplay.render();
  396. }
  397. }
  398. if (bottomlineDebug) {
  399. bottomlineDebug.onclick = function () {
  400. openSheetMusicDisplay.DrawBottomLine = !openSheetMusicDisplay.DrawBottomLine;
  401. openSheetMusicDisplay.render();
  402. }
  403. }
  404. if (performanceModeBtn) {
  405. performanceModeBtn.onclick = function () {
  406. performanceMode = !performanceMode;
  407. openSheetMusicDisplay.setOptions({performanceMode});
  408. }
  409. }
  410. if (debugReRenderBtn) {
  411. debugReRenderBtn.onclick = function () {
  412. rerender();
  413. }
  414. }
  415. if (debugClearBtn) {
  416. debugClearBtn.onclick = function () {
  417. openSheetMusicDisplay.clear();
  418. }
  419. }
  420. // Create OSMD object and canvas
  421. openSheetMusicDisplay = new OpenSheetMusicDisplay(canvas, {
  422. autoResize: true,
  423. backend: backendType,
  424. //backend: "canvas",
  425. disableCursor: false,
  426. drawingParameters: compactMode ? "compact" : "default", // try compact (instead of default)
  427. drawPartNames: true, // try false
  428. // drawTitle: false,
  429. // drawSubtitle: false,
  430. drawFingerings: true,
  431. fingeringPosition: "left", // left is default. try right. experimental: auto, above, below.
  432. // fingeringInsideStafflines: "true", // default: false. true draws fingerings directly above/below notes
  433. setWantedStemDirectionByXml: true, // try false, which was previously the default behavior
  434. // drawUpToMeasureNumber: 3, // draws only up to measure 3, meaning it draws measure 1 to 3 of the piece.
  435. drawFromMeasureNumber : measureRangeStart,
  436. drawUpToMeasureNumber : measureRangeEnd,
  437. //drawMeasureNumbers: false, // disable drawing measure numbers
  438. //measureNumberInterval: 4, // draw measure numbers only every 4 bars (and at the beginning of a new system)
  439. useXMLMeasureNumbers: true, // read measure numbers from xml
  440. // coloring options
  441. coloringEnabled: true,
  442. // defaultColorNotehead: "#CC0055", // try setting a default color. default is black (undefined)
  443. // defaultColorStem: "#BB0099",
  444. autoBeam: false, // try true, OSMD Function Test AutoBeam sample
  445. autoBeamOptions: {
  446. beam_rests: false,
  447. beam_middle_rests_only: false,
  448. //groups: [[3,4], [1,1]],
  449. maintain_stem_directions: false
  450. },
  451. pageFormat: pageFormat,
  452. pageBackgroundColor: pageBackgroundColor,
  453. renderSingleHorizontalStaffline: singleHorizontalStaffline,
  454. performanceMode: performanceMode
  455. // tupletsBracketed: true, // creates brackets for all tuplets except triplets, even when not set by xml
  456. // tripletsBracketed: true,
  457. // tupletsRatioed: true, // unconventional; renders ratios for tuplets (3:2 instead of 3 for triplets)
  458. });
  459. openSheetMusicDisplay.setLogLevel('info'); // set this to 'debug' if you want to see more detailed control flow information in console
  460. document.body.appendChild(canvas);
  461. window.addEventListener("keydown", function (e) {
  462. var event = window.event ? window.event : e;
  463. if (event.keyCode === 39) {
  464. openSheetMusicDisplay.cursor.next();
  465. }
  466. });
  467. nextCursorBtn.addEventListener("click", function () {
  468. openSheetMusicDisplay.cursor.next();
  469. });
  470. resetCursorBtn.addEventListener("click", function () {
  471. openSheetMusicDisplay.cursor.reset();
  472. });
  473. if (followCursorCheckbox) {
  474. followCursorCheckbox.onchange = function () {
  475. openSheetMusicDisplay.FollowCursor = !openSheetMusicDisplay.FollowCursor;
  476. }
  477. }
  478. window.addEventListener("wheel", function(e){
  479. if(followCursorCheckbox) {
  480. followCursorCheckbox.checked = false;
  481. openSheetMusicDisplay.FollowCursor = false;
  482. }
  483. });
  484. hideCursorBtn.addEventListener("click", function () {
  485. if (openSheetMusicDisplay.cursor) {
  486. openSheetMusicDisplay.cursor.hide();
  487. } else {
  488. console.info("Can't hide cursor, as it was disabled (e.g. by drawingParameters).");
  489. }
  490. });
  491. showCursorBtn.addEventListener("click", function () {
  492. if (openSheetMusicDisplay.cursor) {
  493. openSheetMusicDisplay.cursor.show();
  494. } else {
  495. console.info("Can't show cursor, as it was disabled (e.g. by drawingParameters).");
  496. }
  497. });
  498. backendSelect.addEventListener("change", function (e) {
  499. var value = e.target.value;
  500. var createNewOsmd = true;
  501. if (createNewOsmd) {
  502. // clears the canvas element
  503. canvas.innerHTML = "";
  504. openSheetMusicDisplay = new OpenSheetMusicDisplay(canvas, { backend: value });
  505. openSheetMusicDisplay.setLogLevel('info'); // set this to 'debug' if you want to get more detailed control flow information
  506. } else {
  507. // alternative, doesn't work yet, see setOptions():
  508. openSheetMusicDisplay.setOptions({ backend: value });
  509. }
  510. console.log("[OSMD] selectSampleOnChange addEventListener change");
  511. // selectSampleOnChange();
  512. });
  513. if(transposeBtn && transpose){
  514. openSheetMusicDisplay.TransposeCalculator = new TransposeCalculator();
  515. transposeBtn.onclick = function(){
  516. var transposeValue = parseInt(transpose.value);
  517. openSheetMusicDisplay.Sheet.Transpose = transposeValue;
  518. openSheetMusicDisplay.updateGraphic();
  519. rerender();
  520. }
  521. }
  522. playbackControl = demoPlaybackControl(openSheetMusicDisplay);
  523. playbackControlsButton.addEventListener("click", function(){
  524. if(!playbackControl.IsClosed()){
  525. playbackControl.hideControls();
  526. } else {
  527. playbackControl.showControls();
  528. }
  529. });
  530. // TODO after selectSampleOnChange, the resize handler triggers immediately,
  531. // so we render twice at the start of the demo.
  532. // maybe delay the first osmd render, e.g. when window ready?
  533. if (paramOpenUrl) {
  534. if (openSheetMusicDisplay.getLogLevel() < 2) { // debug or trace
  535. console.log("[OSMD] selectSampleOnChange with " + paramOpenUrl);
  536. }
  537. // DEBUG: cause an error for a certain sample, for testing
  538. // if (paramOpenUrl.startsWith("Beethoven")) {
  539. // paramOpenUrl.causeError();
  540. // }
  541. selectSampleOnChange(paramOpenUrl);
  542. } else {
  543. if (openSheetMusicDisplay.getLogLevel() < 2) { // debug or trace
  544. console.log("[OSMD] selectSampleOnChange without param");
  545. }
  546. selectSampleOnChange();
  547. }
  548. }
  549. function findGetParameter(parameterName) {
  550. // special treatment for the openUrl parameter, because different systems attach different arguments to an URL.
  551. // because of CORS (cross-origin safety restrictions), you can only load an xml file from the same origin (server).
  552. // test parameter: ?openUrl=https://opensheetmusiceducation.org/index.php?gf-download=2020%2F01%2FJohannSebastianBach_PraeludiumInCDur_BWV846_1.xml&endUrl&form-id=1&field-id=4&hash=c4ba271ef08204a26cbd4cd2d751c53b78f238c25ddbb1f343e1172f2ce2aa53
  553. // (enable the console.log at the end of this method for testing)
  554. // working test parameter in local demo: ?openUrl=OSMD_function_test_all.xml&endUrl
  555. if (parameterName === 'openUrl') {
  556. let startParameterName = 'openUrl=';
  557. let endParameterName = '&endUrl';
  558. let openUrlIndex = location.search.indexOf(startParameterName);
  559. if (openUrlIndex < 0) {
  560. return undefined;
  561. }
  562. let endIndex = location.search.indexOf(endParameterName) + endParameterName.length;
  563. if (endIndex < 0) {
  564. console.log("[OSMD] If using openUrl as a parameter, you have to end it with '&endUrl'. openUrl parameter omitted.");
  565. return undefined;
  566. }
  567. let urlString = location.search.substring(openUrlIndex + startParameterName.length, endIndex - endParameterName.length);
  568. //console.log("openUrl: " + urlString);
  569. return urlString;
  570. }
  571. let result = undefined;
  572. let tmp = [];
  573. location.search
  574. .substr(1)
  575. .split('&')
  576. .forEach(function (item) {
  577. tmp = item.split('=');
  578. if (tmp[0] === parameterName) {
  579. result = decodeURIComponent(tmp[1]);
  580. //console.log('Found param:' + parameterName + ' = ' + result);
  581. }
  582. });
  583. return result;
  584. }
  585. function selectBoundingOnChange(evt) {
  586. var value = evt.target.value;
  587. openSheetMusicDisplay.DrawBoundingBox = value;
  588. }
  589. function selectSampleOnChange(str) {
  590. var comment = undefined;
  591. var sampleStr = undefined;
  592. error();
  593. disable();
  594. var isCustom = typeof str === "string";
  595. if (!isCustom) {
  596. if (selectSample) {
  597. sampleStr = selectSample.value;
  598. str = sampleFolder + sampleStr;
  599. } else {
  600. if (samples && samples.length > 0) {
  601. sampleStr = samples[0];
  602. str = sampleFolder + sampleStr;
  603. } else {
  604. return; // no sample to load right now
  605. }
  606. }
  607. if(comments.hasOwnProperty(sampleStr)){
  608. comment = comments[sampleStr];
  609. }
  610. }
  611. // zoom = 1.0;
  612. setSampleSpecificOptions(str, isCustom);
  613. openSheetMusicDisplay.load(str, comment).then(
  614. function () {
  615. // This gives you access to the osmd object in the console. Do not use in production code
  616. window.osmd = openSheetMusicDisplay;
  617. openSheetMusicDisplay.zoom = zoom;
  618. //openSheetMusicDisplay.Sheet.Transpose = 3; // try transposing between load and first render if you have transpose issues with F# etc
  619. return openSheetMusicDisplay.render();
  620. },
  621. function (e) {
  622. errorLoadingOrRenderingSheet(e, "rendering");
  623. }
  624. ).then(
  625. function () {
  626. return onLoadingEnd(isCustom);
  627. }, function (e) {
  628. errorLoadingOrRenderingSheet(e, "loading");
  629. onLoadingEnd(isCustom);
  630. }
  631. );
  632. }
  633. function setSampleSpecificOptions(str, isCustom) {
  634. if (!isCustom && str.includes("measuresToDraw")) { // set options for measuresToDraw sample
  635. // stash previously set range of measures to draw
  636. if (!measureToDrawRangeNeedsReset) { // only stash once, when measuresToDraw called multiple times in a row
  637. minMeasureToDrawStashed = openSheetMusicDisplay.EngravingRules.MinMeasureToDrawIndex + 1;
  638. maxMeasureToDrawStashed = openSheetMusicDisplay.EngravingRules.MaxMeasureToDrawIndex + 1;
  639. }
  640. measureToDrawRangeNeedsReset = true;
  641. // for debugging: draw from a random range of measures
  642. let minMeasureToDraw = Math.ceil(Math.random() * 15); // measures start at 1 (measureIndex = measure number - 1 elsewhere)
  643. let maxMeasureToDraw = Math.ceil(Math.random() * 15);
  644. if (minMeasureToDraw > maxMeasureToDraw) {
  645. minMeasureToDraw = maxMeasureToDraw;
  646. let a = minMeasureToDraw;
  647. maxMeasureToDraw = a;
  648. }
  649. //minMeasureToDraw = 1; // set your custom indexes here. Drawing only one measure can be a special case
  650. //maxMeasureToDraw = 1;
  651. console.log("drawing measures in the range: [" + minMeasureToDraw + "," + maxMeasureToDraw + "]");
  652. openSheetMusicDisplay.setOptions({
  653. drawFromMeasureNumber: minMeasureToDraw,
  654. drawUpToMeasureNumber: maxMeasureToDraw
  655. });
  656. } else if (measureToDrawRangeNeedsReset) { // reset for other samples
  657. openSheetMusicDisplay.setOptions({
  658. drawFromMeasureNumber: minMeasureToDrawStashed,
  659. drawUpToMeasureNumber: maxMeasureToDrawStashed
  660. });
  661. measureToDrawRangeNeedsReset = false;
  662. }
  663. if (!isCustom && str.includes("Test_Container_height")) {
  664. drawingParametersStashed = openSheetMusicDisplay.drawingParameters.drawingParametersEnum;
  665. openSheetMusicDisplay.setOptions({
  666. drawingParameters: "compacttight"
  667. });
  668. drawingParametersNeedsReset = true;
  669. } else if (drawingParametersNeedsReset) {
  670. openSheetMusicDisplay.setOptions({
  671. drawingParameters: drawingParametersStashed
  672. });
  673. drawingParametersNeedsReset = false;
  674. }
  675. // Enable Boomwhacker-like coloring for OSMD Function Test - Auto-Coloring (Boomwhacker-like, custom color set)
  676. if (!isCustom && str.includes("auto-custom-coloring")) { // set options for auto coloring sample
  677. autoCustomColoringOptionNeedsReset = true;
  678. //openSheetMusicDisplay.setOptions({coloringMode: 1}); // Auto-Coloring with pre-defined colors
  679. openSheetMusicDisplay.setOptions({
  680. coloringMode: 2, // custom coloring set. 0 would be XML, 1 autocoloring
  681. coloringSetCustom: ["#d82c6b", "#F89D15", "#FFE21A", "#4dbd5c", "#009D96", "#43469d", "#76429c", "#ff0000"],
  682. // last color value of coloringSetCustom is for rest notes
  683. colorStemsLikeNoteheads: true
  684. });
  685. } else if (autoCustomColoringOptionNeedsReset) {
  686. openSheetMusicDisplay.setOptions({ // set default values. better would be to restore to stashed values, but unnecessarily complex for demo
  687. coloringMode: 0,
  688. colorStemsLikeNoteheads: false,
  689. coloringSetCustom: null
  690. });
  691. autoCustomColoringOptionNeedsReset = false;
  692. }
  693. if (!isCustom && str.includes("autobeam")) {
  694. autobeamOptionStashedValue = openSheetMusicDisplay.EngravingRules.AutoBeamNotes; // stash previously set value, to restore later
  695. autobeamOptionNeedsReset = true;
  696. openSheetMusicDisplay.setOptions({ autoBeam: true });
  697. } else if (autobeamOptionNeedsReset) {
  698. openSheetMusicDisplay.setOptions({ autoBeam: autobeamOptionStashedValue });
  699. autobeamOptionNeedsReset = false;
  700. }
  701. if (!isCustom && str.includes("OSMD_Function_Test_System_and_Page_Breaks")) {
  702. pageBreaksOptionStashedValue = openSheetMusicDisplay.EngravingRules.NewPageAtXMLNewPageAttribute;
  703. systemBreaksOptionStashedValue = openSheetMusicDisplay.EngravingRules.NewSystemAtXMLNewSystemAttribute;
  704. pageBreaksOptionNeedsReset = true;
  705. openSheetMusicDisplay.setOptions({ newPageFromXML: true, newSystemFromXML: true });
  706. }
  707. else if (pageBreaksOptionNeedsReset) {
  708. openSheetMusicDisplay.setOptions({ newPageFromXML: pageBreaksOptionStashedValue, newSystemFromXML: systemBreaksOptionStashedValue });
  709. pageBreaksOptionNeedsReset = false;
  710. }
  711. if (!isCustom && str.includes("Schubert_An_die_Musik")) { // TODO weird layout bug here with part names. but shouldn't be in score anyways
  712. drawPartNamesOptionStashedValue = openSheetMusicDisplay.EngravingRules.RenderPartNames;
  713. drawPartAbbreviationsStashedValue = openSheetMusicDisplay.EngravingRules.RenderPartAbbreviations;
  714. openSheetMusicDisplay.setOptions({ drawPartNames: false, drawPartAbbreviations: false }); // TODO sets osmd.drawingParameters.DrawPartNames! also check EngravingRules.RenderPartAbbreviations, was false
  715. drawPartNamesOptionNeedsReset = true;
  716. } else if (drawPartNamesOptionNeedsReset) {
  717. openSheetMusicDisplay.setOptions({ drawPartNames: drawPartNamesOptionStashedValue, drawPartAbbreviations: drawPartAbbreviationsStashedValue });
  718. drawPartNamesOptionNeedsReset = false;
  719. }
  720. }
  721. function errorLoadingOrRenderingSheet(e, loadingOrRenderingString) {
  722. var errorString = "Error " + loadingOrRenderingString + " sheet: " + e;
  723. // if (process.env.DEBUG) { // people may not set a debug environment variable for the demo.
  724. // Always giving a StackTrace might give us more and better error reports.
  725. // TODO for a release, StackTrace control could be reenabled
  726. errorString += "\n" + "StackTrace: \n" + e.stack;
  727. // }
  728. console.warn(errorString);
  729. }
  730. function onLoadingEnd(isCustom) {
  731. // Remove option from select
  732. if (!isCustom && custom.parentElement === selectSample) {
  733. selectSample.removeChild(custom);
  734. }
  735. playbackControl.initialize();
  736. // Enable controls again
  737. enable();
  738. }
  739. function logCanvasSize() {
  740. for (const zoomDiv of zoomDivs) {
  741. if (zoomDiv) {
  742. zoomDiv.innerHTML = Math.floor(zoom * 100.0) + "%";
  743. }
  744. }
  745. }
  746. function scale() {
  747. disable();
  748. window.setTimeout(function () {
  749. openSheetMusicDisplay.Zoom = zoom;
  750. openSheetMusicDisplay.render();
  751. enable();
  752. }, 0);
  753. }
  754. function rerender() {
  755. disable();
  756. window.setTimeout(function () {
  757. if (openSheetMusicDisplay.IsReadyToRender()) {
  758. openSheetMusicDisplay.render();
  759. } else {
  760. console.log("[OSMD demo] Loses context!"); // TODO not sure that this message is reasonable, renders fine anyways. maybe vexflow context lost?
  761. selectSampleOnChange(); // reload sample e.g. after osmd.clear()
  762. }
  763. enable();
  764. }, 0);
  765. }
  766. function error(errString) {
  767. if (!errString) {
  768. error_tr.style.display = "none";
  769. } else {
  770. console.log("[OSMD demo] error: " + errString)
  771. err.textContent = errString;
  772. error_tr.style.display = "";
  773. canvas.width = canvas.height = 0;
  774. enable();
  775. }
  776. }
  777. // Enable/Disable Controls
  778. function disable() {
  779. document.body.style.opacity = 0.3;
  780. setDisabledForControls("disabled");
  781. }
  782. function enable() {
  783. document.body.style.opacity = 1;
  784. setDisabledForControls("");
  785. logCanvasSize();
  786. }
  787. function setDisabledForControls(disabledValue) {
  788. if (selectSample) {
  789. selectSample.disabled = disabledValue;
  790. }
  791. for (const zoomIn of zoomIns) {
  792. if (zoomIn) {
  793. zoomIn.disabled = disabledValue;
  794. }
  795. }
  796. for (const zoomOut of zoomOuts) {
  797. if (zoomOut) {
  798. zoomOut.disabled = disabledValue;
  799. }
  800. }
  801. }
  802. /**
  803. * Creates a Pdf of the currently rendered MusicXML
  804. * @param pdfName if no name is given, the composer and title of the piece will be used
  805. */
  806. function createPdf(pdfName) {
  807. if (openSheetMusicDisplay.backendType !== BackendType.SVG) {
  808. console.log("[OSMD] createPdf(): Warning: createPDF is only supported for SVG background for now, not for Canvas." +
  809. " Please use osmd.setOptions({backendType: SVG}).");
  810. return;
  811. }
  812. if (pdfName === undefined) {
  813. pdfName = openSheetMusicDisplay.sheet.FullNameString + ".pdf";
  814. }
  815. const backends = openSheetMusicDisplay.drawer.Backends;
  816. let svgElement = backends[0].getSvgElement();
  817. let pageWidth = 210;
  818. let pageHeight = 297;
  819. const engravingRulesPageFormat = openSheetMusicDisplay.rules.PageFormat;
  820. if (engravingRulesPageFormat && !engravingRulesPageFormat.IsUndefined) {
  821. pageWidth = engravingRulesPageFormat.width;
  822. pageHeight = engravingRulesPageFormat.height;
  823. } else {
  824. pageHeight = pageWidth * svgElement.clientHeight / svgElement.clientWidth;
  825. }
  826. const orientation = pageHeight > pageWidth ? "p" : "l";
  827. // create a new jsPDF instance
  828. const pdf = new jsPDF(orientation, "mm", [pageWidth, pageHeight]);
  829. const scale = pageWidth / svgElement.clientWidth;
  830. for (let idx = 0, len = backends.length; idx < len; ++idx) {
  831. if (idx > 0) {
  832. pdf.addPage();
  833. }
  834. svgElement = backends[idx].getSvgElement();
  835. // render the svg element
  836. svg2pdf(svgElement, pdf, {
  837. scale: scale,
  838. xOffset: 0,
  839. yOffset: 0
  840. });
  841. }
  842. // simply save the created pdf
  843. pdf.save(pdfName);
  844. // note that using jspdf with svg2pdf creates unnecessary console warnings "AcroForm-Classes are not populated into global-namespace..."
  845. // this will hopefully be fixed with a new jspdf release, see https://github.com/yWorks/jsPDF/pull/32
  846. }
  847. var demoPlaybackControl = function(osmd) {
  848. var playbackListener = {
  849. play() {
  850. followCursorCheckbox.checked = true;
  851. openSheetMusicDisplay.FollowCursor = true;
  852. },
  853. pause() {},
  854. reset() {},
  855. bpmChanged() {},
  856. volumeChanged() {},
  857. volumeMute() {},
  858. volumeUnmute() {}
  859. }
  860. var timingSource = new LinearTimingSource();
  861. var playbackManager = new PlaybackManager(timingSource, undefined, new BasicAudioPlayer(), undefined);
  862. playbackManager.DoPlayback = true;
  863. playbackManager.DoPreCount = false;
  864. playbackManager.PreCountMeasures = 1; // note that DoPreCount has to be true for a precount to happen
  865. var playbackControlPanel = new ControlPanel();
  866. playbackControlPanel.addListener(playbackManager);
  867. playbackControlPanel.addListener(playbackListener);
  868. function initialize() {
  869. timingSource.reset();
  870. timingSource.pause();
  871. timingSource.Settings = osmd.sheet.playbackSettings;
  872. playbackManager.initialize(osmd.sheet.musicPartManager);
  873. playbackManager.addListener(osmd.cursor);
  874. playbackManager.reset();
  875. osmd.PlaybackManager = playbackManager;
  876. playbackControlPanel.clearVolumeTracks();
  877. playbackControlPanel.addVolumeTrack(playbackManager.Metronome.Name, playbackManager.Metronome.Id, playbackManager.Metronome.Volume*100);
  878. for(const instrId of playbackManager.InstrumentIdMapping.keys()) {
  879. const instr = playbackManager.InstrumentIdMapping.getValue(instrId);
  880. playbackControlPanel.addVolumeTrack(instr.Name, instrId, instr.Volume * 100);
  881. }
  882. playbackControlPanel.bpmChanged(osmd.sheet.DefaultStartTempoInBpm);
  883. }
  884. function showControls() {
  885. playbackControlPanel.show();
  886. }
  887. function hideControls() {
  888. playbackControlPanel.hideAndClear();
  889. }
  890. function IsClosed() {
  891. return playbackControlPanel.IsClosed;
  892. }
  893. return {
  894. initialize: initialize,
  895. showControls: showControls,
  896. hideControls: hideControls,
  897. IsClosed: IsClosed
  898. }
  899. };
  900. // Register events: load, drag&drop
  901. window.addEventListener("load", function () {
  902. init();
  903. });
  904. window.addEventListener("dragenter", function (event) {
  905. event.preventDefault();
  906. disable();
  907. });
  908. window.addEventListener("dragover", function (event) {
  909. event.preventDefault();
  910. });
  911. window.addEventListener("dragleave", function (event) {
  912. enable();
  913. });
  914. window.addEventListener("drop", function (event) {
  915. event.preventDefault();
  916. if (!event.dataTransfer || !event.dataTransfer.files || event.dataTransfer.files.length === 0) {
  917. return;
  918. }
  919. // Add "Custom..." score
  920. selectSample.appendChild(custom);
  921. custom.selected = "selected";
  922. // Read dragged file
  923. var reader = new FileReader();
  924. reader.onload = function (res) {
  925. selectSampleOnChange(res.target.result);
  926. };
  927. var filename = event.dataTransfer.files[0].name;
  928. if (filename.toLowerCase().indexOf(".xml") > 0
  929. || filename.toLowerCase().indexOf(".musicxml") > 0) {
  930. reader.readAsText(event.dataTransfer.files[0]);
  931. } else if (event.dataTransfer.files[0].name.toLowerCase().indexOf(".mxl") > 0) {
  932. reader.readAsBinaryString(event.dataTransfer.files[0]);
  933. }
  934. else {
  935. alert("No vaild .xml/.mxl/.musicxml file!");
  936. }
  937. });
  938. }());