index.js 47 KB

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