index.js 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  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/dist/jspdf.es.min';
  5. import * as svg2pdf from '../node_modules/svg2pdf.js/dist/svg2pdf.umd.min';
  6. import { TransposeCalculator } from '../src/Plugins/Transpose/TransposeCalculator';
  7. /*jslint browser:true */
  8. (function () {
  9. "use strict";
  10. var openSheetMusicDisplay;
  11. var sampleFolder = "",
  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. document.title = "OpenSheetMusicDisplay Demo";
  135. // Initialization code
  136. function init() {
  137. var name, option;
  138. // Handle window parameter
  139. var paramEmbedded = findGetParameter('embedded');
  140. var paramShowControls = findGetParameter('showControls');
  141. var paramShowPageFormatControl = findGetParameter('showPageFormatControl');
  142. var paramShowExportPdfControl = findGetParameter('showExportPdfControl');
  143. var paramShowZoomControl = findGetParameter('showZoomControl');
  144. var paramShowHeader = findGetParameter('showHeader');
  145. var paramZoom = findGetParameter('zoom');
  146. var paramOverflow = findGetParameter('overflow');
  147. var paramOpenUrl = findGetParameter('openUrl');
  148. var paramDebugControls = findGetParameter('debugControls');
  149. var paramCompactMode = findGetParameter('compactMode');
  150. var paramMeasureRangeStart = findGetParameter('measureRangeStart');
  151. var paramMeasureRangeEnd = findGetParameter('measureRangeEnd');
  152. var paramPageFormat = findGetParameter('pageFormat');
  153. var paramPageBackgroundColor = findGetParameter('pageBackgroundColor');
  154. var paramBackendType = findGetParameter('backendType');
  155. var paramPageWidth = findGetParameter('pageWidth');
  156. var paramPageHeight = findGetParameter('pageHeight');
  157. var paramHorizontalScrolling = findGetParameter('horizontalScrolling');
  158. var paramSingleHorizontalStaffline = findGetParameter('singleHorizontalStaffline');
  159. showHeader = (paramShowHeader !== '0');
  160. showControls = false;
  161. if (paramEmbedded) {
  162. showControls = paramShowControls !== '0';
  163. showZoomControl = paramShowZoomControl !== '0';
  164. showPageFormatControl = paramShowPageFormatControl !== '0';
  165. showExportPdfControl = paramShowExportPdfControl !== '0';
  166. }
  167. if (paramZoom) {
  168. if (paramZoom > 0.1 && paramZoom < 5.0) {
  169. zoom = paramZoom;
  170. }
  171. }
  172. if (paramOverflow && typeof paramOverflow === 'string') {
  173. if (paramOverflow === 'hidden' || paramOverflow === 'auto' || paramOverflow === 'scroll' || paramOverflow === 'visible') {
  174. document.body.style.overflow = paramOverflow;
  175. }
  176. }
  177. var compactMode = paramCompactMode && paramCompactMode !== '0';
  178. var measureRangeStart = paramMeasureRangeStart ? Number.parseInt(paramMeasureRangeStart) : 0;
  179. var measureRangeEnd = paramMeasureRangeEnd ? Number.parseInt(paramMeasureRangeEnd) : Number.MAX_SAFE_INTEGER;
  180. if (measureRangeStart && measureRangeEnd && measureRangeEnd < measureRangeStart) {
  181. console.log("[OSMD] warning: measure range end parameter should not be smaller than measure range start. We've set start measure = end measure now.")
  182. measureRangeStart = measureRangeEnd;
  183. }
  184. let pageFormat = paramPageFormat ? paramPageFormat : "Endless";
  185. if (paramPageHeight && paramPageWidth) {
  186. pageFormat = `${paramPageWidth}x${paramPageHeight}`
  187. }
  188. var pageBackgroundColor = paramPageBackgroundColor ? "#" + paramPageBackgroundColor : undefined; // vexflow format, see OSMDOptions. can't use # in parameters.
  189. //console.log("demo: osmd pagebgcolor: " + pageBackgroundColor);
  190. var backendType = (paramBackendType && paramBackendType.toLowerCase) ? paramBackendType : "svg";
  191. var horizontalScrolling = paramHorizontalScrolling === '1';
  192. var singleHorizontalStaffline = paramSingleHorizontalStaffline === '1';
  193. // set the backendSelect debug controls dropdown menu selected item
  194. //console.log("true: " + backendSelect && backendType.toLowerCase && backendType.toLowerCase() === "canvas");
  195. // TODO somehow backendSelect becomes undefined here:
  196. /*if (backendSelect && backendType.toLowerCase && backendType.toLowerCase() === "canvas") {
  197. console.log("here1");
  198. for (var i=0; i<backendSelect.options.length; i++) {
  199. if (backendSelect.options[i].value.toLowerCase() === "canvas") {
  200. backendSelect.selectedIndex = i;
  201. }
  202. }
  203. backendSelect.value = "Canvas";
  204. }*/
  205. divControls = document.getElementById('divControls');
  206. zoomControls = document.getElementById('zoomControls');
  207. header = document.getElementById('header');
  208. err = document.getElementById("error-td");
  209. error_tr = document.getElementById("error-tr");
  210. zoomDivs = [];
  211. zoomDivs.push(document.getElementById("zoom-str"));
  212. zoomDivs.push(document.getElementById("zoom-str-optional"));
  213. custom = document.createElement("option");
  214. selectSample = document.getElementById("selectSample");
  215. selectBounding = document.getElementById("selectBounding");
  216. skylineDebug = document.getElementById("skylineDebug");
  217. bottomlineDebug = document.getElementById("bottomlineDebug");
  218. performanceMode = false;
  219. performanceModeBtn = document.getElementById("performanceMode");
  220. zoomIns = [];
  221. zoomIns.push(document.getElementById("zoom-in-btn"));
  222. zoomIns.push(document.getElementById("zoom-in-btn-optional"));
  223. zoomOuts = [];
  224. zoomOuts.push(document.getElementById("zoom-out-btn"));
  225. zoomOuts.push(document.getElementById("zoom-out-btn-optional"));
  226. canvas = document.createElement("div");
  227. if (horizontalScrolling) {
  228. canvas.style.overflowX = 'auto'; // enable horizontal scrolling
  229. }
  230. //canvas.id = 'osmdCanvasDiv';
  231. //canvas.style.overflowX = 'auto'; // enable horizontal scrolling
  232. nextCursorBtn = document.getElementById("next-cursor-btn");
  233. resetCursorBtn = document.getElementById("reset-cursor-btn");
  234. followCursorCheckbox = document.getElementById("follow-cursor-checkbox");
  235. showCursorBtn = document.getElementById("show-cursor-btn");
  236. hideCursorBtn = document.getElementById("hide-cursor-btn");
  237. backendSelect = document.getElementById("backend-select");
  238. backendSelectDiv = document.getElementById("backend-select-div");
  239. debugReRenderBtn = document.getElementById("debug-re-render-btn");
  240. debugClearBtn = document.getElementById("debug-clear-btn");
  241. selectPageSizes = [];
  242. selectPageSizes.push(document.getElementById("selectPageSize"));
  243. selectPageSizes.push(document.getElementById("selectPageSize-optional"));
  244. printPdfBtns = [];
  245. printPdfBtns.push(document.getElementById("print-pdf-btn"));
  246. printPdfBtns.push(document.getElementById("print-pdf-btn-optional"));
  247. transpose = document.getElementById('transpose');
  248. transposeBtn = document.getElementById('transpose-btn');
  249. playbackControlsButton = document.getElementById("playback-settings-button")
  250. //var defaultDisplayVisibleValue = "block"; // TODO in some browsers flow could be the better/default value
  251. var defaultVisibilityValue = "visible";
  252. showDebugControls = paramDebugControls !== '0';
  253. if (showDebugControls) {
  254. var elementsToEnable = [
  255. selectSample, selectBounding, selectPageSizes[0], 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. //cursorsOptions: [{type: 3, color: "#2bb8cd", alpha: 0.6, follow: true}], // highlight current measure instead of just a small vertical bar over approximate notes
  423. disableCursor: false,
  424. drawingParameters: compactMode ? "compact" : "default", // try compact (instead of default)
  425. drawPartNames: true, // try false
  426. // drawTitle: false,
  427. // drawSubtitle: false,
  428. drawFingerings: true,
  429. //fingeringPosition: "left", // Above/Below is default. try left or right. experimental: above, below.
  430. //fingeringPositionFromXML: false, // do this if you want them always left, for example.
  431. // fingeringInsideStafflines: "true", // default: false. true draws fingerings directly above/below notes
  432. setWantedStemDirectionByXml: true, // try false, which was previously the default behavior
  433. // drawUpToMeasureNumber: 3, // draws only up to measure 3, meaning it draws measure 1 to 3 of the piece.
  434. drawFromMeasureNumber : measureRangeStart,
  435. drawUpToMeasureNumber : measureRangeEnd,
  436. //drawMeasureNumbers: false, // disable drawing measure numbers
  437. //measureNumberInterval: 4, // draw measure numbers only every 4 bars (and at the beginning of a new system)
  438. useXMLMeasureNumbers: true, // read measure numbers from xml
  439. // coloring options
  440. coloringEnabled: true,
  441. // defaultColorNotehead: "#CC0055", // try setting a default color. default is black (undefined)
  442. // defaultColorStem: "#BB0099",
  443. autoBeam: false, // try true, OSMD Function Test AutoBeam sample
  444. autoBeamOptions: {
  445. beam_rests: false,
  446. beam_middle_rests_only: false,
  447. //groups: [[3,4], [1,1]],
  448. maintain_stem_directions: false
  449. },
  450. pageFormat: pageFormat,
  451. pageBackgroundColor: pageBackgroundColor,
  452. renderSingleHorizontalStaffline: singleHorizontalStaffline,
  453. performanceMode: performanceMode
  454. // tupletsBracketed: true, // creates brackets for all tuplets except triplets, even when not set by xml
  455. // tripletsBracketed: true,
  456. // tupletsRatioed: true, // unconventional; renders ratios for tuplets (3:2 instead of 3 for triplets)
  457. });
  458. //openSheetMusicDisplay.DrawSkyLine = true;
  459. //openSheetMusicDisplay.DrawBottomLine = true;
  460. //openSheetMusicDisplay.setDrawBoundingBox("GraphicalLabel", false);
  461. openSheetMusicDisplay.setLogLevel('info'); // set this to 'debug' if you want to see more detailed control flow information in console
  462. document.body.appendChild(canvas);
  463. window.addEventListener("keydown", function (e) {
  464. var event = window.event ? window.event : e;
  465. if (event.keyCode === 39) {
  466. openSheetMusicDisplay.cursor.next();
  467. }
  468. });
  469. nextCursorBtn.addEventListener("click", function () {
  470. openSheetMusicDisplay.cursor.next();
  471. });
  472. resetCursorBtn.addEventListener("click", function () {
  473. openSheetMusicDisplay.cursor.reset();
  474. });
  475. if (followCursorCheckbox) {
  476. followCursorCheckbox.onchange = function () {
  477. openSheetMusicDisplay.FollowCursor = !openSheetMusicDisplay.FollowCursor;
  478. }
  479. }
  480. window.addEventListener("wheel", function(e){
  481. if(followCursorCheckbox) {
  482. followCursorCheckbox.checked = false;
  483. openSheetMusicDisplay.FollowCursor = false;
  484. }
  485. });
  486. hideCursorBtn.addEventListener("click", function () {
  487. if (openSheetMusicDisplay.cursor) {
  488. openSheetMusicDisplay.cursor.hide();
  489. } else {
  490. console.info("Can't hide cursor, as it was disabled (e.g. by drawingParameters).");
  491. }
  492. });
  493. showCursorBtn.addEventListener("click", function () {
  494. if (openSheetMusicDisplay.cursor) {
  495. openSheetMusicDisplay.cursor.show();
  496. } else {
  497. console.info("Can't show cursor, as it was disabled (e.g. by drawingParameters).");
  498. }
  499. });
  500. backendSelect.addEventListener("change", function (e) {
  501. var value = e.target.value;
  502. var createNewOsmd = true;
  503. if (createNewOsmd) {
  504. // clears the canvas element
  505. canvas.innerHTML = "";
  506. openSheetMusicDisplay = new OpenSheetMusicDisplay(canvas, { backend: value });
  507. openSheetMusicDisplay.setLogLevel('info'); // set this to 'debug' if you want to get more detailed control flow information
  508. } else {
  509. // alternative, doesn't work yet, see setOptions():
  510. openSheetMusicDisplay.setOptions({ backend: value });
  511. }
  512. console.log("[OSMD] selectSampleOnChange addEventListener change");
  513. // selectSampleOnChange();
  514. });
  515. if(transposeBtn && transpose){
  516. openSheetMusicDisplay.TransposeCalculator = new TransposeCalculator();
  517. transposeBtn.onclick = function(){
  518. var transposeValue = parseInt(transpose.value);
  519. openSheetMusicDisplay.Sheet.Transpose = transposeValue;
  520. openSheetMusicDisplay.updateGraphic();
  521. rerender();
  522. }
  523. }
  524. playbackControl = demoPlaybackControl(openSheetMusicDisplay);
  525. playbackControlsButton.addEventListener("click", function(){
  526. if(!playbackControl.IsClosed()){
  527. playbackControl.hideControls();
  528. } else {
  529. playbackControl.showControls();
  530. }
  531. });
  532. // TODO after selectSampleOnChange, the resize handler triggers immediately,
  533. // so we render twice at the start of the demo.
  534. // maybe delay the first osmd render, e.g. when window ready?
  535. if (paramOpenUrl) {
  536. if (openSheetMusicDisplay.getLogLevel() < 2) { // debug or trace
  537. console.log("[OSMD] selectSampleOnChange with " + paramOpenUrl);
  538. }
  539. // DEBUG: cause an error for a certain sample, for testing
  540. // if (paramOpenUrl.startsWith("Beethoven")) {
  541. // paramOpenUrl.causeError();
  542. // }
  543. selectSampleOnChange(paramOpenUrl);
  544. } else {
  545. if (openSheetMusicDisplay.getLogLevel() < 2) { // debug or trace
  546. console.log("[OSMD] selectSampleOnChange without param");
  547. }
  548. selectSampleOnChange();
  549. }
  550. }
  551. function findGetParameter(parameterName) {
  552. // special treatment for the openUrl parameter, because different systems attach different arguments to an URL.
  553. // because of CORS (cross-origin safety restrictions), you can only load an xml file from the same origin (server).
  554. // 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
  555. // (enable the console.log at the end of this method for testing)
  556. // working test parameter in local demo: ?openUrl=OSMD_function_test_all.xml&endUrl
  557. if (parameterName === 'openUrl') {
  558. let startParameterName = 'openUrl=';
  559. let endParameterName = '&endUrl';
  560. let openUrlIndex = location.search.indexOf(startParameterName);
  561. if (openUrlIndex < 0) {
  562. return undefined;
  563. }
  564. let endIndex = location.search.indexOf(endParameterName) + endParameterName.length;
  565. if (endIndex < 0) {
  566. console.log("[OSMD] If using openUrl as a parameter, you have to end it with '&endUrl'. openUrl parameter omitted.");
  567. return undefined;
  568. }
  569. let urlString = location.search.substring(openUrlIndex + startParameterName.length, endIndex - endParameterName.length);
  570. //console.log("openUrl: " + urlString);
  571. return urlString;
  572. }
  573. let result = undefined;
  574. let tmp = [];
  575. location.search
  576. .substr(1)
  577. .split('&')
  578. .forEach(function (item) {
  579. tmp = item.split('=');
  580. if (tmp[0] === parameterName) {
  581. result = decodeURIComponent(tmp[1]);
  582. //console.log('Found param:' + parameterName + ' = ' + result);
  583. }
  584. });
  585. return result;
  586. }
  587. function selectBoundingOnChange(evt) {
  588. var value = evt.target.value;
  589. openSheetMusicDisplay.DrawBoundingBox = value;
  590. }
  591. function selectSampleOnChange(str) {
  592. var comment = undefined;
  593. var sampleStr = undefined;
  594. error();
  595. disable();
  596. var isCustom = typeof str === "string";
  597. if (!isCustom) {
  598. if (selectSample) {
  599. sampleStr = selectSample.value;
  600. str = sampleFolder + sampleStr;
  601. } else {
  602. if (samples && samples.length > 0) {
  603. sampleStr = samples[0];
  604. str = sampleFolder + sampleStr;
  605. } else {
  606. return; // no sample to load right now
  607. }
  608. }
  609. if(comments.hasOwnProperty(sampleStr)){
  610. comment = comments[sampleStr];
  611. }
  612. }
  613. // zoom = 1.0;
  614. setSampleSpecificOptions(str, isCustom);
  615. openSheetMusicDisplay.load(str, comment).then(
  616. function () {
  617. // This gives you access to the osmd object in the console. Do not use in production code
  618. window.osmd = openSheetMusicDisplay;
  619. openSheetMusicDisplay.zoom = zoom;
  620. //openSheetMusicDisplay.Sheet.Transpose = 3; // try transposing between load and first render if you have transpose issues with F# etc
  621. return openSheetMusicDisplay.render();
  622. },
  623. function (e) {
  624. errorLoadingOrRenderingSheet(e, "rendering");
  625. }
  626. ).then(
  627. function () {
  628. return onLoadingEnd(isCustom);
  629. }, function (e) {
  630. errorLoadingOrRenderingSheet(e, "loading");
  631. onLoadingEnd(isCustom);
  632. }
  633. );
  634. }
  635. function setSampleSpecificOptions(str, isCustom) {
  636. if (!isCustom && str.includes("measuresToDraw")) { // set options for measuresToDraw sample
  637. // stash previously set range of measures to draw
  638. if (!measureToDrawRangeNeedsReset) { // only stash once, when measuresToDraw called multiple times in a row
  639. minMeasureToDrawStashed = openSheetMusicDisplay.EngravingRules.MinMeasureToDrawIndex + 1;
  640. maxMeasureToDrawStashed = openSheetMusicDisplay.EngravingRules.MaxMeasureToDrawIndex + 1;
  641. }
  642. measureToDrawRangeNeedsReset = true;
  643. // for debugging: draw from a random range of measures
  644. let minMeasureToDraw = Math.ceil(Math.random() * 15); // measures start at 1 (measureIndex = measure number - 1 elsewhere)
  645. let maxMeasureToDraw = Math.ceil(Math.random() * 15);
  646. if (minMeasureToDraw > maxMeasureToDraw) {
  647. minMeasureToDraw = maxMeasureToDraw;
  648. let a = minMeasureToDraw;
  649. maxMeasureToDraw = a;
  650. }
  651. //minMeasureToDraw = 1; // set your custom indexes here. Drawing only one measure can be a special case
  652. //maxMeasureToDraw = 1;
  653. console.log("drawing measures in the range: [" + minMeasureToDraw + "," + maxMeasureToDraw + "]");
  654. openSheetMusicDisplay.setOptions({
  655. drawFromMeasureNumber: minMeasureToDraw,
  656. drawUpToMeasureNumber: maxMeasureToDraw
  657. });
  658. } else if (measureToDrawRangeNeedsReset) { // reset for other samples
  659. openSheetMusicDisplay.setOptions({
  660. drawFromMeasureNumber: minMeasureToDrawStashed,
  661. drawUpToMeasureNumber: maxMeasureToDrawStashed
  662. });
  663. measureToDrawRangeNeedsReset = false;
  664. }
  665. if (!isCustom && str.includes("Test_Container_height")) {
  666. drawingParametersStashed = openSheetMusicDisplay.drawingParameters.drawingParametersEnum;
  667. openSheetMusicDisplay.setOptions({
  668. drawingParameters: "compacttight"
  669. });
  670. drawingParametersNeedsReset = true;
  671. } else if (drawingParametersNeedsReset) {
  672. openSheetMusicDisplay.setOptions({
  673. drawingParameters: drawingParametersStashed
  674. });
  675. drawingParametersNeedsReset = false;
  676. }
  677. // Enable Boomwhacker-like coloring for OSMD Function Test - Auto-Coloring (Boomwhacker-like, custom color set)
  678. if (!isCustom && str.includes("auto-custom-coloring")) { // set options for auto coloring sample
  679. autoCustomColoringOptionNeedsReset = true;
  680. //openSheetMusicDisplay.setOptions({coloringMode: 1}); // Auto-Coloring with pre-defined colors
  681. openSheetMusicDisplay.setOptions({
  682. coloringMode: 2, // custom coloring set. 0 would be XML, 1 autocoloring
  683. coloringSetCustom: ["#d82c6b", "#F89D15", "#FFE21A", "#4dbd5c", "#009D96", "#43469d", "#76429c", "#ff0000"],
  684. // last color value of coloringSetCustom is for rest notes
  685. colorStemsLikeNoteheads: true
  686. });
  687. } else if (autoCustomColoringOptionNeedsReset) {
  688. openSheetMusicDisplay.setOptions({ // set default values. better would be to restore to stashed values, but unnecessarily complex for demo
  689. coloringMode: 0,
  690. colorStemsLikeNoteheads: false,
  691. coloringSetCustom: null
  692. });
  693. autoCustomColoringOptionNeedsReset = false;
  694. }
  695. if (!isCustom && str.includes("autobeam")) {
  696. autobeamOptionStashedValue = openSheetMusicDisplay.EngravingRules.AutoBeamNotes; // stash previously set value, to restore later
  697. autobeamOptionNeedsReset = true;
  698. openSheetMusicDisplay.setOptions({ autoBeam: true });
  699. } else if (autobeamOptionNeedsReset) {
  700. openSheetMusicDisplay.setOptions({ autoBeam: autobeamOptionStashedValue });
  701. autobeamOptionNeedsReset = false;
  702. }
  703. if (!isCustom && str.includes("OSMD_Function_Test_System_and_Page_Breaks")) {
  704. pageBreaksOptionStashedValue = openSheetMusicDisplay.EngravingRules.NewPageAtXMLNewPageAttribute;
  705. systemBreaksOptionStashedValue = openSheetMusicDisplay.EngravingRules.NewSystemAtXMLNewSystemAttribute;
  706. pageBreaksOptionNeedsReset = true;
  707. openSheetMusicDisplay.setOptions({ newPageFromXML: true, newSystemFromXML: true });
  708. }
  709. else if (pageBreaksOptionNeedsReset) {
  710. openSheetMusicDisplay.setOptions({ newPageFromXML: pageBreaksOptionStashedValue, newSystemFromXML: systemBreaksOptionStashedValue });
  711. pageBreaksOptionNeedsReset = false;
  712. }
  713. if (!isCustom && str.includes("Schubert_An_die_Musik")) { // TODO weird layout bug here with part names. but shouldn't be in score anyways
  714. drawPartNamesOptionStashedValue = openSheetMusicDisplay.EngravingRules.RenderPartNames;
  715. drawPartAbbreviationsStashedValue = openSheetMusicDisplay.EngravingRules.RenderPartAbbreviations;
  716. openSheetMusicDisplay.setOptions({ drawPartNames: false, drawPartAbbreviations: false }); // TODO sets osmd.drawingParameters.DrawPartNames! also check EngravingRules.RenderPartAbbreviations, was false
  717. drawPartNamesOptionNeedsReset = true;
  718. } else if (drawPartNamesOptionNeedsReset) {
  719. openSheetMusicDisplay.setOptions({ drawPartNames: drawPartNamesOptionStashedValue, drawPartAbbreviations: drawPartAbbreviationsStashedValue });
  720. drawPartNamesOptionNeedsReset = false;
  721. }
  722. }
  723. function errorLoadingOrRenderingSheet(e, loadingOrRenderingString) {
  724. var errorString = "Error " + loadingOrRenderingString + " sheet: " + e;
  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. async 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.jsPDF({
  830. orientation: orientation,
  831. unit: "mm",
  832. format: [pageWidth, pageHeight]
  833. });
  834. //const scale = pageWidth / svgElement.clientWidth;
  835. for (let idx = 0, len = backends.length; idx < len; ++idx) {
  836. if (idx > 0) {
  837. pdf.addPage();
  838. }
  839. svgElement = backends[idx].getSvgElement();
  840. if (!pdf.svg && !svg2pdf) { // this line also serves to make the svg2pdf not unused, though it's still necessary
  841. // we need svg2pdf to have pdf.svg defined
  842. console.log("svg2pdf missing, necessary for jspdf.svg().");
  843. return;
  844. }
  845. await pdf.svg(svgElement, {
  846. x: 0,
  847. y: 0,
  848. width: pageWidth,
  849. height: pageHeight,
  850. })
  851. }
  852. pdf.save(pdfName); // save/download the created pdf
  853. //pdf.output("pdfobjectnewwindow", {filename: "osmd_createPDF.pdf"}); // open PDF in new tab/window
  854. // note that using jspdf with svg2pdf creates unnecessary console warnings "AcroForm-Classes are not populated into global-namespace..."
  855. // this will hopefully be fixed with a new jspdf release, see https://github.com/yWorks/jsPDF/pull/32
  856. }
  857. var demoPlaybackControl = function(osmd) {
  858. var playbackListener = {
  859. play() {
  860. followCursorCheckbox.checked = true;
  861. openSheetMusicDisplay.FollowCursor = true;
  862. },
  863. pause() {},
  864. reset() {},
  865. bpmChanged() {},
  866. volumeChanged() {},
  867. volumeMute() {},
  868. volumeUnmute() {}
  869. }
  870. var timingSource = new LinearTimingSource();
  871. var playbackManager = new PlaybackManager(timingSource, undefined, new BasicAudioPlayer(), undefined);
  872. playbackManager.DoPlayback = true;
  873. playbackManager.DoPreCount = false;
  874. playbackManager.PreCountMeasures = 1; // note that DoPreCount has to be true for a precount to happen
  875. var playbackControlPanel = new ControlPanel();
  876. playbackControlPanel.addListener(playbackManager);
  877. playbackControlPanel.addListener(playbackListener);
  878. function initialize() {
  879. timingSource.reset();
  880. timingSource.pause();
  881. timingSource.Settings = osmd.Sheet.playbackSettings;
  882. playbackManager.initialize(osmd.Sheet.musicPartManager);
  883. playbackManager.addListener(osmd.cursor);
  884. playbackManager.reset();
  885. osmd.PlaybackManager = playbackManager;
  886. playbackControlPanel.clearVolumeTracks();
  887. playbackControlPanel.addVolumeTrack(playbackManager.Metronome.Name, playbackManager.Metronome.Id, playbackManager.Metronome.Volume*100);
  888. for(const instrId of playbackManager.InstrumentIdMapping.keys()) {
  889. const instr = playbackManager.InstrumentIdMapping.getValue(instrId);
  890. playbackControlPanel.addVolumeTrack(instr.Name, instrId, instr.Volume * 100);
  891. }
  892. playbackControlPanel.bpmChanged(osmd.Sheet.DefaultStartTempoInBpm);
  893. }
  894. function showControls() {
  895. playbackControlPanel.show();
  896. }
  897. function hideControls() {
  898. playbackControlPanel.hideAndClear();
  899. }
  900. function IsClosed() {
  901. return playbackControlPanel.IsClosed;
  902. }
  903. return {
  904. initialize: initialize,
  905. showControls: showControls,
  906. hideControls: hideControls,
  907. IsClosed: IsClosed
  908. }
  909. };
  910. // Register events: load, drag&drop
  911. window.addEventListener("load", function () {
  912. init();
  913. });
  914. window.addEventListener("dragenter", function (event) {
  915. event.preventDefault();
  916. disable();
  917. });
  918. window.addEventListener("dragover", function (event) {
  919. event.preventDefault();
  920. });
  921. window.addEventListener("dragleave", function (event) {
  922. enable();
  923. });
  924. window.addEventListener("drop", function (event) {
  925. event.preventDefault();
  926. if (!event.dataTransfer || !event.dataTransfer.files || event.dataTransfer.files.length === 0) {
  927. return;
  928. }
  929. // Add "Custom..." score
  930. selectSample.appendChild(custom);
  931. custom.selected = "selected";
  932. // Read dragged file
  933. var reader = new FileReader();
  934. reader.onload = function (res) {
  935. selectSampleOnChange(res.target.result);
  936. };
  937. var filename = event.dataTransfer.files[0].name;
  938. if (filename.toLowerCase().indexOf(".xml") > 0
  939. || filename.toLowerCase().indexOf(".musicxml") > 0) {
  940. reader.readAsText(event.dataTransfer.files[0]);
  941. } else if (event.dataTransfer.files[0].name.toLowerCase().indexOf(".mxl") > 0) {
  942. reader.readAsBinaryString(event.dataTransfer.files[0]);
  943. }
  944. else {
  945. alert("No vaild .xml/.mxl/.musicxml file!");
  946. }
  947. });
  948. }());