index.js 46 KB

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