index.js 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  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. //cursorsOptions: [{type: 3, color: "#2bb8cd", alpha: 0.6, follow: true}], // highlight current measure instead of just a small vertical bar over approximate notes
  426. disableCursor: false,
  427. drawingParameters: compactMode ? "compact" : "default", // try compact (instead of default)
  428. drawPartNames: true, // try false
  429. // drawTitle: false,
  430. // drawSubtitle: false,
  431. drawFingerings: true,
  432. fingeringPosition: "left", // left is default. try right. experimental: auto, above, below.
  433. // fingeringInsideStafflines: "true", // default: false. true draws fingerings directly above/below notes
  434. setWantedStemDirectionByXml: true, // try false, which was previously the default behavior
  435. // drawUpToMeasureNumber: 3, // draws only up to measure 3, meaning it draws measure 1 to 3 of the piece.
  436. drawFromMeasureNumber : measureRangeStart,
  437. drawUpToMeasureNumber : measureRangeEnd,
  438. //drawMeasureNumbers: false, // disable drawing measure numbers
  439. //measureNumberInterval: 4, // draw measure numbers only every 4 bars (and at the beginning of a new system)
  440. useXMLMeasureNumbers: true, // read measure numbers from xml
  441. // coloring options
  442. coloringEnabled: true,
  443. // defaultColorNotehead: "#CC0055", // try setting a default color. default is black (undefined)
  444. // defaultColorStem: "#BB0099",
  445. autoBeam: false, // try true, OSMD Function Test AutoBeam sample
  446. autoBeamOptions: {
  447. beam_rests: false,
  448. beam_middle_rests_only: false,
  449. //groups: [[3,4], [1,1]],
  450. maintain_stem_directions: false
  451. },
  452. pageFormat: pageFormat,
  453. pageBackgroundColor: pageBackgroundColor,
  454. renderSingleHorizontalStaffline: singleHorizontalStaffline,
  455. performanceMode: performanceMode
  456. // tupletsBracketed: true, // creates brackets for all tuplets except triplets, even when not set by xml
  457. // tripletsBracketed: true,
  458. // tupletsRatioed: true, // unconventional; renders ratios for tuplets (3:2 instead of 3 for triplets)
  459. });
  460. openSheetMusicDisplay.setLogLevel('info'); // set this to 'debug' if you want to see more detailed control flow information in console
  461. document.body.appendChild(canvas);
  462. window.addEventListener("keydown", function (e) {
  463. var event = window.event ? window.event : e;
  464. if (event.keyCode === 39) {
  465. openSheetMusicDisplay.cursor.next();
  466. }
  467. });
  468. nextCursorBtn.addEventListener("click", function () {
  469. openSheetMusicDisplay.cursor.next();
  470. });
  471. resetCursorBtn.addEventListener("click", function () {
  472. openSheetMusicDisplay.cursor.reset();
  473. });
  474. if (followCursorCheckbox) {
  475. followCursorCheckbox.onchange = function () {
  476. openSheetMusicDisplay.FollowCursor = !openSheetMusicDisplay.FollowCursor;
  477. }
  478. }
  479. window.addEventListener("wheel", function(e){
  480. if(followCursorCheckbox) {
  481. followCursorCheckbox.checked = false;
  482. openSheetMusicDisplay.FollowCursor = false;
  483. }
  484. });
  485. hideCursorBtn.addEventListener("click", function () {
  486. if (openSheetMusicDisplay.cursor) {
  487. openSheetMusicDisplay.cursor.hide();
  488. } else {
  489. console.info("Can't hide cursor, as it was disabled (e.g. by drawingParameters).");
  490. }
  491. });
  492. showCursorBtn.addEventListener("click", function () {
  493. if (openSheetMusicDisplay.cursor) {
  494. openSheetMusicDisplay.cursor.show();
  495. } else {
  496. console.info("Can't show cursor, as it was disabled (e.g. by drawingParameters).");
  497. }
  498. });
  499. backendSelect.addEventListener("change", function (e) {
  500. var value = e.target.value;
  501. var createNewOsmd = true;
  502. if (createNewOsmd) {
  503. // clears the canvas element
  504. canvas.innerHTML = "";
  505. openSheetMusicDisplay = new OpenSheetMusicDisplay(canvas, { backend: value });
  506. openSheetMusicDisplay.setLogLevel('info'); // set this to 'debug' if you want to get more detailed control flow information
  507. } else {
  508. // alternative, doesn't work yet, see setOptions():
  509. openSheetMusicDisplay.setOptions({ backend: value });
  510. }
  511. console.log("[OSMD] selectSampleOnChange addEventListener change");
  512. // selectSampleOnChange();
  513. });
  514. if(transposeBtn && transpose){
  515. openSheetMusicDisplay.TransposeCalculator = new TransposeCalculator();
  516. transposeBtn.onclick = function(){
  517. var transposeValue = parseInt(transpose.value);
  518. openSheetMusicDisplay.Sheet.Transpose = transposeValue;
  519. openSheetMusicDisplay.updateGraphic();
  520. rerender();
  521. }
  522. }
  523. playbackControl = demoPlaybackControl(openSheetMusicDisplay);
  524. playbackControlsButton.addEventListener("click", function(){
  525. if(!playbackControl.IsClosed()){
  526. playbackControl.hideControls();
  527. } else {
  528. playbackControl.showControls();
  529. }
  530. });
  531. // TODO after selectSampleOnChange, the resize handler triggers immediately,
  532. // so we render twice at the start of the demo.
  533. // maybe delay the first osmd render, e.g. when window ready?
  534. if (paramOpenUrl) {
  535. if (openSheetMusicDisplay.getLogLevel() < 2) { // debug or trace
  536. console.log("[OSMD] selectSampleOnChange with " + paramOpenUrl);
  537. }
  538. // DEBUG: cause an error for a certain sample, for testing
  539. // if (paramOpenUrl.startsWith("Beethoven")) {
  540. // paramOpenUrl.causeError();
  541. // }
  542. selectSampleOnChange(paramOpenUrl);
  543. } else {
  544. if (openSheetMusicDisplay.getLogLevel() < 2) { // debug or trace
  545. console.log("[OSMD] selectSampleOnChange without param");
  546. }
  547. selectSampleOnChange();
  548. }
  549. }
  550. function findGetParameter(parameterName) {
  551. // special treatment for the openUrl parameter, because different systems attach different arguments to an URL.
  552. // because of CORS (cross-origin safety restrictions), you can only load an xml file from the same origin (server).
  553. // 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
  554. // (enable the console.log at the end of this method for testing)
  555. // working test parameter in local demo: ?openUrl=OSMD_function_test_all.xml&endUrl
  556. if (parameterName === 'openUrl') {
  557. let startParameterName = 'openUrl=';
  558. let endParameterName = '&endUrl';
  559. let openUrlIndex = location.search.indexOf(startParameterName);
  560. if (openUrlIndex < 0) {
  561. return undefined;
  562. }
  563. let endIndex = location.search.indexOf(endParameterName) + endParameterName.length;
  564. if (endIndex < 0) {
  565. console.log("[OSMD] If using openUrl as a parameter, you have to end it with '&endUrl'. openUrl parameter omitted.");
  566. return undefined;
  567. }
  568. let urlString = location.search.substring(openUrlIndex + startParameterName.length, endIndex - endParameterName.length);
  569. //console.log("openUrl: " + urlString);
  570. return urlString;
  571. }
  572. let result = undefined;
  573. let tmp = [];
  574. location.search
  575. .substr(1)
  576. .split('&')
  577. .forEach(function (item) {
  578. tmp = item.split('=');
  579. if (tmp[0] === parameterName) {
  580. result = decodeURIComponent(tmp[1]);
  581. //console.log('Found param:' + parameterName + ' = ' + result);
  582. }
  583. });
  584. return result;
  585. }
  586. function selectBoundingOnChange(evt) {
  587. var value = evt.target.value;
  588. openSheetMusicDisplay.DrawBoundingBox = value;
  589. }
  590. function selectSampleOnChange(str) {
  591. var comment = undefined;
  592. var sampleStr = undefined;
  593. error();
  594. disable();
  595. var isCustom = typeof str === "string";
  596. if (!isCustom) {
  597. if (selectSample) {
  598. sampleStr = selectSample.value;
  599. str = sampleFolder + sampleStr;
  600. } else {
  601. if (samples && samples.length > 0) {
  602. sampleStr = samples[0];
  603. str = sampleFolder + sampleStr;
  604. } else {
  605. return; // no sample to load right now
  606. }
  607. }
  608. if(comments.hasOwnProperty(sampleStr)){
  609. comment = comments[sampleStr];
  610. }
  611. }
  612. // zoom = 1.0;
  613. setSampleSpecificOptions(str, isCustom);
  614. openSheetMusicDisplay.load(str, comment).then(
  615. function () {
  616. // This gives you access to the osmd object in the console. Do not use in production code
  617. window.osmd = openSheetMusicDisplay;
  618. openSheetMusicDisplay.zoom = zoom;
  619. //openSheetMusicDisplay.Sheet.Transpose = 3; // try transposing between load and first render if you have transpose issues with F# etc
  620. return openSheetMusicDisplay.render();
  621. },
  622. function (e) {
  623. errorLoadingOrRenderingSheet(e, "rendering");
  624. }
  625. ).then(
  626. function () {
  627. return onLoadingEnd(isCustom);
  628. }, function (e) {
  629. errorLoadingOrRenderingSheet(e, "loading");
  630. onLoadingEnd(isCustom);
  631. }
  632. );
  633. }
  634. function setSampleSpecificOptions(str, isCustom) {
  635. if (!isCustom && str.includes("measuresToDraw")) { // set options for measuresToDraw sample
  636. // stash previously set range of measures to draw
  637. if (!measureToDrawRangeNeedsReset) { // only stash once, when measuresToDraw called multiple times in a row
  638. minMeasureToDrawStashed = openSheetMusicDisplay.EngravingRules.MinMeasureToDrawIndex + 1;
  639. maxMeasureToDrawStashed = openSheetMusicDisplay.EngravingRules.MaxMeasureToDrawIndex + 1;
  640. }
  641. measureToDrawRangeNeedsReset = true;
  642. // for debugging: draw from a random range of measures
  643. let minMeasureToDraw = Math.ceil(Math.random() * 15); // measures start at 1 (measureIndex = measure number - 1 elsewhere)
  644. let maxMeasureToDraw = Math.ceil(Math.random() * 15);
  645. if (minMeasureToDraw > maxMeasureToDraw) {
  646. minMeasureToDraw = maxMeasureToDraw;
  647. let a = minMeasureToDraw;
  648. maxMeasureToDraw = a;
  649. }
  650. //minMeasureToDraw = 1; // set your custom indexes here. Drawing only one measure can be a special case
  651. //maxMeasureToDraw = 1;
  652. console.log("drawing measures in the range: [" + minMeasureToDraw + "," + maxMeasureToDraw + "]");
  653. openSheetMusicDisplay.setOptions({
  654. drawFromMeasureNumber: minMeasureToDraw,
  655. drawUpToMeasureNumber: maxMeasureToDraw
  656. });
  657. } else if (measureToDrawRangeNeedsReset) { // reset for other samples
  658. openSheetMusicDisplay.setOptions({
  659. drawFromMeasureNumber: minMeasureToDrawStashed,
  660. drawUpToMeasureNumber: maxMeasureToDrawStashed
  661. });
  662. measureToDrawRangeNeedsReset = false;
  663. }
  664. if (!isCustom && str.includes("Test_Container_height")) {
  665. drawingParametersStashed = openSheetMusicDisplay.drawingParameters.drawingParametersEnum;
  666. openSheetMusicDisplay.setOptions({
  667. drawingParameters: "compacttight"
  668. });
  669. drawingParametersNeedsReset = true;
  670. } else if (drawingParametersNeedsReset) {
  671. openSheetMusicDisplay.setOptions({
  672. drawingParameters: drawingParametersStashed
  673. });
  674. drawingParametersNeedsReset = false;
  675. }
  676. // Enable Boomwhacker-like coloring for OSMD Function Test - Auto-Coloring (Boomwhacker-like, custom color set)
  677. if (!isCustom && str.includes("auto-custom-coloring")) { // set options for auto coloring sample
  678. autoCustomColoringOptionNeedsReset = true;
  679. //openSheetMusicDisplay.setOptions({coloringMode: 1}); // Auto-Coloring with pre-defined colors
  680. openSheetMusicDisplay.setOptions({
  681. coloringMode: 2, // custom coloring set. 0 would be XML, 1 autocoloring
  682. coloringSetCustom: ["#d82c6b", "#F89D15", "#FFE21A", "#4dbd5c", "#009D96", "#43469d", "#76429c", "#ff0000"],
  683. // last color value of coloringSetCustom is for rest notes
  684. colorStemsLikeNoteheads: true
  685. });
  686. } else if (autoCustomColoringOptionNeedsReset) {
  687. openSheetMusicDisplay.setOptions({ // set default values. better would be to restore to stashed values, but unnecessarily complex for demo
  688. coloringMode: 0,
  689. colorStemsLikeNoteheads: false,
  690. coloringSetCustom: null
  691. });
  692. autoCustomColoringOptionNeedsReset = false;
  693. }
  694. if (!isCustom && str.includes("autobeam")) {
  695. autobeamOptionStashedValue = openSheetMusicDisplay.EngravingRules.AutoBeamNotes; // stash previously set value, to restore later
  696. autobeamOptionNeedsReset = true;
  697. openSheetMusicDisplay.setOptions({ autoBeam: true });
  698. } else if (autobeamOptionNeedsReset) {
  699. openSheetMusicDisplay.setOptions({ autoBeam: autobeamOptionStashedValue });
  700. autobeamOptionNeedsReset = false;
  701. }
  702. if (!isCustom && str.includes("OSMD_Function_Test_System_and_Page_Breaks")) {
  703. pageBreaksOptionStashedValue = openSheetMusicDisplay.EngravingRules.NewPageAtXMLNewPageAttribute;
  704. systemBreaksOptionStashedValue = openSheetMusicDisplay.EngravingRules.NewSystemAtXMLNewSystemAttribute;
  705. pageBreaksOptionNeedsReset = true;
  706. openSheetMusicDisplay.setOptions({ newPageFromXML: true, newSystemFromXML: true });
  707. }
  708. else if (pageBreaksOptionNeedsReset) {
  709. openSheetMusicDisplay.setOptions({ newPageFromXML: pageBreaksOptionStashedValue, newSystemFromXML: systemBreaksOptionStashedValue });
  710. pageBreaksOptionNeedsReset = false;
  711. }
  712. if (!isCustom && str.includes("Schubert_An_die_Musik")) { // TODO weird layout bug here with part names. but shouldn't be in score anyways
  713. drawPartNamesOptionStashedValue = openSheetMusicDisplay.EngravingRules.RenderPartNames;
  714. drawPartAbbreviationsStashedValue = openSheetMusicDisplay.EngravingRules.RenderPartAbbreviations;
  715. openSheetMusicDisplay.setOptions({ drawPartNames: false, drawPartAbbreviations: false }); // TODO sets osmd.drawingParameters.DrawPartNames! also check EngravingRules.RenderPartAbbreviations, was false
  716. drawPartNamesOptionNeedsReset = true;
  717. } else if (drawPartNamesOptionNeedsReset) {
  718. openSheetMusicDisplay.setOptions({ drawPartNames: drawPartNamesOptionStashedValue, drawPartAbbreviations: drawPartAbbreviationsStashedValue });
  719. drawPartNamesOptionNeedsReset = false;
  720. }
  721. }
  722. function errorLoadingOrRenderingSheet(e, loadingOrRenderingString) {
  723. var errorString = "Error " + loadingOrRenderingString + " sheet: " + e;
  724. // if (process.env.DEBUG) { // people may not set a debug environment variable for the demo.
  725. // Always giving a StackTrace might give us more and better error reports.
  726. // TODO for a release, StackTrace control could be reenabled
  727. errorString += "\n" + "StackTrace: \n" + e.stack;
  728. // }
  729. console.warn(errorString);
  730. }
  731. function onLoadingEnd(isCustom) {
  732. // Remove option from select
  733. if (!isCustom && custom.parentElement === selectSample) {
  734. selectSample.removeChild(custom);
  735. }
  736. playbackControl.initialize();
  737. // Enable controls again
  738. enable();
  739. }
  740. function logCanvasSize() {
  741. for (const zoomDiv of zoomDivs) {
  742. if (zoomDiv) {
  743. zoomDiv.innerHTML = Math.floor(zoom * 100.0) + "%";
  744. }
  745. }
  746. }
  747. function scale() {
  748. disable();
  749. window.setTimeout(function () {
  750. openSheetMusicDisplay.Zoom = zoom;
  751. openSheetMusicDisplay.render();
  752. enable();
  753. }, 0);
  754. }
  755. function rerender() {
  756. disable();
  757. window.setTimeout(function () {
  758. if (openSheetMusicDisplay.IsReadyToRender()) {
  759. openSheetMusicDisplay.render();
  760. } else {
  761. console.log("[OSMD demo] Loses context!"); // TODO not sure that this message is reasonable, renders fine anyways. maybe vexflow context lost?
  762. selectSampleOnChange(); // reload sample e.g. after osmd.clear()
  763. }
  764. enable();
  765. }, 0);
  766. }
  767. function error(errString) {
  768. if (!errString) {
  769. error_tr.style.display = "none";
  770. } else {
  771. console.log("[OSMD demo] error: " + errString)
  772. err.textContent = errString;
  773. error_tr.style.display = "";
  774. canvas.width = canvas.height = 0;
  775. enable();
  776. }
  777. }
  778. // Enable/Disable Controls
  779. function disable() {
  780. document.body.style.opacity = 0.3;
  781. setDisabledForControls("disabled");
  782. }
  783. function enable() {
  784. document.body.style.opacity = 1;
  785. setDisabledForControls("");
  786. logCanvasSize();
  787. }
  788. function setDisabledForControls(disabledValue) {
  789. if (selectSample) {
  790. selectSample.disabled = disabledValue;
  791. }
  792. for (const zoomIn of zoomIns) {
  793. if (zoomIn) {
  794. zoomIn.disabled = disabledValue;
  795. }
  796. }
  797. for (const zoomOut of zoomOuts) {
  798. if (zoomOut) {
  799. zoomOut.disabled = disabledValue;
  800. }
  801. }
  802. }
  803. /**
  804. * Creates a Pdf of the currently rendered MusicXML
  805. * @param pdfName if no name is given, the composer and title of the piece will be used
  806. */
  807. function createPdf(pdfName) {
  808. if (openSheetMusicDisplay.backendType !== BackendType.SVG) {
  809. console.log("[OSMD] createPdf(): Warning: createPDF is only supported for SVG background for now, not for Canvas." +
  810. " Please use osmd.setOptions({backendType: SVG}).");
  811. return;
  812. }
  813. if (pdfName === undefined) {
  814. pdfName = openSheetMusicDisplay.sheet.FullNameString + ".pdf";
  815. }
  816. const backends = openSheetMusicDisplay.drawer.Backends;
  817. let svgElement = backends[0].getSvgElement();
  818. let pageWidth = 210;
  819. let pageHeight = 297;
  820. const engravingRulesPageFormat = openSheetMusicDisplay.rules.PageFormat;
  821. if (engravingRulesPageFormat && !engravingRulesPageFormat.IsUndefined) {
  822. pageWidth = engravingRulesPageFormat.width;
  823. pageHeight = engravingRulesPageFormat.height;
  824. } else {
  825. pageHeight = pageWidth * svgElement.clientHeight / svgElement.clientWidth;
  826. }
  827. const orientation = pageHeight > pageWidth ? "p" : "l";
  828. // create a new jsPDF instance
  829. const pdf = new jsPDF(orientation, "mm", [pageWidth, pageHeight]);
  830. const scale = pageWidth / svgElement.clientWidth;
  831. for (let idx = 0, len = backends.length; idx < len; ++idx) {
  832. if (idx > 0) {
  833. pdf.addPage();
  834. }
  835. svgElement = backends[idx].getSvgElement();
  836. // render the svg element
  837. svg2pdf(svgElement, pdf, {
  838. scale: scale,
  839. xOffset: 0,
  840. yOffset: 0
  841. });
  842. }
  843. // simply save the created pdf
  844. pdf.save(pdfName);
  845. // note that using jspdf with svg2pdf creates unnecessary console warnings "AcroForm-Classes are not populated into global-namespace..."
  846. // this will hopefully be fixed with a new jspdf release, see https://github.com/yWorks/jsPDF/pull/32
  847. }
  848. var demoPlaybackControl = function(osmd) {
  849. var playbackListener = {
  850. play() {
  851. followCursorCheckbox.checked = true;
  852. openSheetMusicDisplay.FollowCursor = true;
  853. },
  854. pause() {},
  855. reset() {},
  856. bpmChanged() {},
  857. volumeChanged() {},
  858. volumeMute() {},
  859. volumeUnmute() {}
  860. }
  861. var timingSource = new LinearTimingSource();
  862. var playbackManager = new PlaybackManager(timingSource, undefined, new BasicAudioPlayer(), undefined);
  863. playbackManager.DoPlayback = true;
  864. playbackManager.DoPreCount = false;
  865. playbackManager.PreCountMeasures = 1; // note that DoPreCount has to be true for a precount to happen
  866. var playbackControlPanel = new ControlPanel();
  867. playbackControlPanel.addListener(playbackManager);
  868. playbackControlPanel.addListener(playbackListener);
  869. function initialize() {
  870. timingSource.reset();
  871. timingSource.pause();
  872. timingSource.Settings = osmd.sheet.playbackSettings;
  873. playbackManager.initialize(osmd.sheet.musicPartManager);
  874. playbackManager.addListener(osmd.cursor);
  875. playbackManager.reset();
  876. osmd.PlaybackManager = playbackManager;
  877. playbackControlPanel.clearVolumeTracks();
  878. playbackControlPanel.addVolumeTrack(playbackManager.Metronome.Name, playbackManager.Metronome.Id, playbackManager.Metronome.Volume*100);
  879. for(const instrId of playbackManager.InstrumentIdMapping.keys()) {
  880. const instr = playbackManager.InstrumentIdMapping.getValue(instrId);
  881. playbackControlPanel.addVolumeTrack(instr.Name, instrId, instr.Volume * 100);
  882. }
  883. playbackControlPanel.bpmChanged(osmd.sheet.DefaultStartTempoInBpm);
  884. }
  885. function showControls() {
  886. playbackControlPanel.show();
  887. }
  888. function hideControls() {
  889. playbackControlPanel.hideAndClear();
  890. }
  891. function IsClosed() {
  892. return playbackControlPanel.IsClosed;
  893. }
  894. return {
  895. initialize: initialize,
  896. showControls: showControls,
  897. hideControls: hideControls,
  898. IsClosed: IsClosed
  899. }
  900. };
  901. // Register events: load, drag&drop
  902. window.addEventListener("load", function () {
  903. init();
  904. });
  905. window.addEventListener("dragenter", function (event) {
  906. event.preventDefault();
  907. disable();
  908. });
  909. window.addEventListener("dragover", function (event) {
  910. event.preventDefault();
  911. });
  912. window.addEventListener("dragleave", function (event) {
  913. enable();
  914. });
  915. window.addEventListener("drop", function (event) {
  916. event.preventDefault();
  917. if (!event.dataTransfer || !event.dataTransfer.files || event.dataTransfer.files.length === 0) {
  918. return;
  919. }
  920. // Add "Custom..." score
  921. selectSample.appendChild(custom);
  922. custom.selected = "selected";
  923. // Read dragged file
  924. var reader = new FileReader();
  925. reader.onload = function (res) {
  926. selectSampleOnChange(res.target.result);
  927. };
  928. var filename = event.dataTransfer.files[0].name;
  929. if (filename.toLowerCase().indexOf(".xml") > 0
  930. || filename.toLowerCase().indexOf(".musicxml") > 0) {
  931. reader.readAsText(event.dataTransfer.files[0]);
  932. } else if (event.dataTransfer.files[0].name.toLowerCase().indexOf(".mxl") > 0) {
  933. reader.readAsBinaryString(event.dataTransfer.files[0]);
  934. }
  935. else {
  936. alert("No vaild .xml/.mxl/.musicxml file!");
  937. }
  938. });
  939. }());