index.js 47 KB

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