index.js 48 KB

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