index.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. import { OpenSheetMusicDisplay } from '../src/OpenSheetMusicDisplay/OpenSheetMusicDisplay';
  2. /*jslint browser:true */
  3. (function () {
  4. "use strict";
  5. var openSheetMusicDisplay;
  6. var sampleFolder = process.env.STATIC_FILES_SUBFOLDER ? process.env.STATIC_FILES_SUBFOLDER + "/" : "",
  7. samples = {
  8. "Beethoven, L.v. - An die ferne Geliebte": "Beethoven_AnDieFerneGeliebte.xml",
  9. "Clementi, M. - Sonatina Op.36 No.1 Pt.1": "MuzioClementi_SonatinaOpus36No1_Part1.xml",
  10. "Clementi, M. - Sonatina Op.36 No.1 Pt.2": "MuzioClementi_SonatinaOpus36No1_Part2.xml",
  11. "Clementi, M. - Sonatina Op.36 No.3 Pt.1": "MuzioClementi_SonatinaOpus36No3_Part1.xml",
  12. "Clementi, M. - Sonatina Op.36 No.3 Pt.2": "MuzioClementi_SonatinaOpus36No3_Part2.xml",
  13. "Bach, J.S. - Praeludium in C-Dur BWV846 1": "JohannSebastianBach_PraeludiumInCDur_BWV846_1.xml",
  14. "Bach, J.S. - Air": "JohannSebastianBach_Air.xml",
  15. "Gounod, C. - Méditation": "CharlesGounod_Meditation.xml",
  16. "Haydn, J. - Concertante Cello": "JosephHaydn_ConcertanteCello.xml",
  17. "Joplin, S. - Elite Syncopations": "ScottJoplin_EliteSyncopations.xml",
  18. "Joplin, S. - The Entertainer": "ScottJoplin_The_Entertainer.xml",
  19. "Mozart, W.A. - An Chloe": "Mozart_AnChloe.xml",
  20. "Mozart, W.A. - Das Veilchen": "Mozart_DasVeilchen.xml",
  21. "Mozart, W.A. - Clarinet Quintet (Excerpt)": "Mozart_Clarinet_Quintet_Excerpt.mxl",
  22. "Mozart, W.A. - String Quartet in G, K. 387, 1st Mvmt Excerpt": "Mozart_String_Quartet_in_G_K._387_1st_Mvmnt_excerpt.musicxml",
  23. "Mozart/Holzer - Land der Berge (national anthem of Austria)": "Land_der_Berge.musicxml",
  24. "OSMD Function Test - All": "OSMD_function_test_all.xml",
  25. "OSMD Function Test - Accidentals": "OSMD_function_test_accidentals.musicxml",
  26. "OSMD Function Test - Autobeam": "OSMD_function_test_autobeam.musicxml",
  27. "OSMD Function Test - Auto-/Custom-Coloring": "OSMD_function_test_auto-custom-coloring-entchen.musicxml",
  28. "OSMD Function Test - Bar lines": "OSMD_function_test_bar_lines.musicxml",
  29. "OSMD Function Test - Color (from XML)": "OSMD_function_test_color.musicxml",
  30. "OSMD Function Test - Drumset": "OSMD_function_test_drumset.musicxml",
  31. "OSMD Function Test - Expressions": "OSMD_function_test_expressions.musicxml",
  32. "OSMD Function Test - Expressions Overlap": "OSMD_function_test_expressions_overlap.musicxml",
  33. "OSMD Function Test - Grace Notes": "OSMD_function_test_GraceNotes.xml",
  34. "OSMD Function Test - Invisible Notes": "OSMD_function_test_invisible_notes.musicxml",
  35. "OSMD Function Test - Selecting Measures To Draw": "OSMD_function_test_measuresToDraw_Beethoven_AnDieFerneGeliebte.xml",
  36. "OSMD Function Test - Notehead Shapes": "OSMD_function_test_noteheadShapes.musicxml",
  37. "OSMD Function Test - Ornaments": "OSMD_function_test_Ornaments.xml",
  38. "OSMD Function Test - Tabulature": "OSMD_Function_Test_Tabulature_hayden_study_1.mxl",
  39. "OSMD Function Test - Tremolo": "OSMD_Function_Test_Tremolo_2bars.musicxml",
  40. "Schubert, F. - An Die Musik": "Schubert_An_die_Musik.xml",
  41. "Actor, L. - Prelude (Large Sample, loading time)": "ActorPreludeSample.xml",
  42. "Anonymous - Saltarello": "Saltarello.mxl",
  43. "Debussy, C. - Mandoline": "Debussy_Mandoline.xml",
  44. "Levasseur, F. - Parlez Mois": "Parlez-moi.mxl",
  45. "Schumann, R. - Dichterliebe": "Dichterliebe01.xml",
  46. "Telemann, G.P. - Sonate-Nr.1.1-Dolce": "TelemannWV40.102_Sonate-Nr.1.1-Dolce.xml",
  47. "Telemann, G.P. - Sonate-Nr.1.2-Allegro": "TelemannWV40.102_Sonate-Nr.1.2-Allegro-F-Dur.xml",
  48. },
  49. zoom = 1.0,
  50. // HTML Elements in the page
  51. divControls,
  52. zoomControls,
  53. header,
  54. err,
  55. error_tr,
  56. canvas,
  57. selectSample,
  58. selectBounding,
  59. skylineDebug,
  60. bottomlineDebug,
  61. zoomIns,
  62. zoomOuts,
  63. zoomDivs,
  64. custom,
  65. nextCursorBtn,
  66. resetCursorBtn,
  67. followCursorCheckbox,
  68. showCursorBtn,
  69. hideCursorBtn,
  70. backendSelect,
  71. backendSelectDiv,
  72. debugReRenderBtn,
  73. debugClearBtn,
  74. selectPageSizes,
  75. printPdfBtns;
  76. // manage option setting and resetting for specific samples, e.g. in the autobeam sample autobeam is set to true, otherwise reset to previous state
  77. // TODO design a more elegant option state saving & restoring system, though that requires saving the options state in OSMD
  78. var minMeasureToDrawStashed = 1;
  79. var maxMeasureToDrawStashed = Number.MAX_SAFE_INTEGER;
  80. var measureToDrawRangeNeedsReset = false;
  81. var autobeamOptionNeedsReset = false;
  82. var autobeamOptionStashedValue = false;
  83. var autoCustomColoringOptionNeedsReset = false;
  84. var autoCustomColoringOptionStashedValue = false;
  85. var drawPartNamesOptionStashedValue = true;
  86. var drawPartAbbreviationsStashedValue = true;
  87. var drawPartNamesOptionNeedsReset = false;
  88. var showControls = true;
  89. var showExportPdfControl = false;
  90. var showPageFormatControl = false;
  91. var showZoomControl = true;
  92. var showHeader = true;
  93. var showDebugControls = false;
  94. if (process.env.OSMD_DEMO_TITLE) {
  95. document.title = process.env.OSMD_DEMO_TITLE;
  96. }
  97. // Initialization code
  98. function init() {
  99. var name, option;
  100. // Handle window parameter
  101. var paramEmbedded = findGetParameter('embedded');
  102. var paramShowControls = findGetParameter('showControls');
  103. var paramShowPageFormatControl = findGetParameter('showPageFormatControl');
  104. var paramShowExportPdfControl = findGetParameter('showExportPdfControl');
  105. var paramShowZoomControl = findGetParameter('showZoomControl');
  106. var paramShowHeader = findGetParameter('showHeader');
  107. var paramZoom = findGetParameter('zoom');
  108. var paramOverflow = findGetParameter('overflow');
  109. var paramOpenUrl = findGetParameter('openUrl');
  110. var paramDebugControls = findGetParameter('debugControls');
  111. var paramCompactMode = findGetParameter('compactMode');
  112. var paramMeasureRangeStart = findGetParameter('measureRangeStart');
  113. var paramMeasureRangeEnd = findGetParameter('measureRangeEnd');
  114. var paramPageFormat = findGetParameter('pageFormat');
  115. var paramPageBackgroundColor = findGetParameter('pageBackgroundColor');
  116. var paramBackendType = findGetParameter('backendType');
  117. var paramPageWidth = findGetParameter('pageWidth');
  118. var paramPageHeight = findGetParameter('pageHeight');
  119. var paramHorizontalScrolling = findGetParameter('horizontalScrolling');
  120. var paramSingleHorizontalStaffline = findGetParameter('singleHorizontalStaffline');
  121. showHeader = (paramShowHeader !== '0');
  122. showControls = false;
  123. if (paramEmbedded !== undefined) {
  124. showControls = paramShowControls !== '0';
  125. showZoomControl = paramShowZoomControl !== '0';
  126. showPageFormatControl = paramShowPageFormatControl !== '0';
  127. showExportPdfControl = paramShowExportPdfControl !== '0';
  128. }
  129. if (paramZoom !== undefined) {
  130. if (paramZoom > 0.1 && paramZoom < 5.0) {
  131. zoom = paramZoom;
  132. }
  133. }
  134. if (paramOverflow !== undefined && typeof paramOverflow === 'string') {
  135. if (paramOverflow === 'hidden' || paramOverflow === 'auto' || paramOverflow === 'scroll' || paramOverflow === 'visible') {
  136. document.body.style.overflow = paramOverflow;
  137. }
  138. }
  139. var compactMode = paramCompactMode && paramCompactMode !== '0';
  140. var measureRangeStart = paramMeasureRangeStart ? Number.parseInt(paramMeasureRangeStart) : 0;
  141. var measureRangeEnd = paramMeasureRangeEnd ? Number.parseInt(paramMeasureRangeEnd) : Number.MAX_SAFE_INTEGER;
  142. if (measureRangeStart && measureRangeEnd && measureRangeEnd < measureRangeStart) {
  143. console.log("[OSMD] warning: measure range end parameter should not be smaller than measure range start. We've set start measure = end measure now.")
  144. measureRangeStart = measureRangeEnd;
  145. }
  146. let pageFormat = paramPageFormat ? paramPageFormat : "Endless";
  147. if (paramPageHeight && paramPageWidth) {
  148. pageFormat = `${paramPageWidth}x${paramPageHeight}`
  149. }
  150. var pageBackgroundColor = paramPageBackgroundColor ? "#" + paramPageBackgroundColor : undefined; // vexflow format, see OSMDOptions. can't use # in parameters.
  151. //console.log("demo: osmd pagebgcolor: " + pageBackgroundColor);
  152. var backendType = (paramBackendType && paramBackendType.toLowerCase) ? paramBackendType : "svg";
  153. var horizontalScrolling = paramHorizontalScrolling === '1';
  154. var singleHorizontalStaffline = paramSingleHorizontalStaffline === '1';
  155. // set the backendSelect debug controls dropdown menu selected item
  156. //console.log("true: " + backendSelect && backendType.toLowerCase && backendType.toLowerCase() === "canvas");
  157. // TODO somehow backendSelect becomes undefined here:
  158. /*if (backendSelect && backendType.toLowerCase && backendType.toLowerCase() === "canvas") {
  159. console.log("here1");
  160. for (var i=0; i<backendSelect.options.length; i++) {
  161. if (backendSelect.options[i].value.toLowerCase() === "canvas") {
  162. backendSelect.selectedIndex = i;
  163. }
  164. }
  165. backendSelect.value = "Canvas";
  166. }*/
  167. divControls = document.getElementById('divControls');
  168. zoomControls = document.getElementById('zoomControls');
  169. header = document.getElementById('header');
  170. err = document.getElementById("error-td");
  171. error_tr = document.getElementById("error-tr");
  172. zoomDivs = [];
  173. zoomDivs.push(document.getElementById("zoom-str"));
  174. zoomDivs.push(document.getElementById("zoom-str-optional"));
  175. custom = document.createElement("option");
  176. selectSample = document.getElementById("selectSample");
  177. selectBounding = document.getElementById("selectBounding");
  178. skylineDebug = document.getElementById("skylineDebug");
  179. bottomlineDebug = document.getElementById("bottomlineDebug");
  180. zoomIns = [];
  181. zoomIns.push(document.getElementById("zoom-in-btn"));
  182. zoomIns.push(document.getElementById("zoom-in-btn-optional"));
  183. zoomOuts = [];
  184. zoomOuts.push(document.getElementById("zoom-out-btn"));
  185. zoomOuts.push(document.getElementById("zoom-out-btn-optional"));
  186. canvas = document.createElement("div");
  187. if (horizontalScrolling) {
  188. canvas.style.overflowX = 'auto'; // enable horizontal scrolling
  189. }
  190. //canvas.id = 'osmdCanvasDiv';
  191. //canvas.style.overflowX = 'auto'; // enable horizontal scrolling
  192. nextCursorBtn = document.getElementById("next-cursor-btn");
  193. resetCursorBtn = document.getElementById("reset-cursor-btn");
  194. followCursorCheckbox = document.getElementById("follow-cursor-checkbox");
  195. showCursorBtn = document.getElementById("show-cursor-btn");
  196. hideCursorBtn = document.getElementById("hide-cursor-btn");
  197. backendSelect = document.getElementById("backend-select");
  198. backendSelectDiv = document.getElementById("backend-select-div");
  199. debugReRenderBtn = document.getElementById("debug-re-render-btn");
  200. debugClearBtn = document.getElementById("debug-clear-btn");
  201. selectPageSizes = [];
  202. selectPageSizes.push(document.getElementById("selectPageSize"));
  203. selectPageSizes.push(document.getElementById("selectPageSize-optional"));
  204. printPdfBtns = [];
  205. printPdfBtns.push(document.getElementById("print-pdf-btn"));
  206. printPdfBtns.push(document.getElementById("print-pdf-btn-optional"));
  207. //var defaultDisplayVisibleValue = "block"; // TODO in some browsers flow could be the better/default value
  208. var defaultVisibilityValue = "visible";
  209. var devDemoRunning = process.env.OSMD_DEBUG_CONTROLS;
  210. showDebugControls = paramDebugControls === '1' || (devDemoRunning && paramDebugControls !== '0')
  211. if (showDebugControls) {
  212. var elementsToEnable = [
  213. selectSample, selectBounding, selectPageSize, backendSelect, backendSelectDiv, divControls
  214. ];
  215. for (var i=0; i<elementsToEnable.length; i++) {
  216. if (elementsToEnable[i]) { // make sure this element is not null/exists in the index.html, e.g. github.io demo has different index.html
  217. if (elementsToEnable[i].style) {
  218. elementsToEnable[i].style.visibility = defaultVisibilityValue;
  219. elementsToEnable[i].style.opacity = 1.0;
  220. }
  221. }
  222. }
  223. } else {
  224. if (divControls) {
  225. divControls.style.display = "none";
  226. }
  227. }
  228. const optionalControls = document.getElementById('optionalControls');
  229. if (optionalControls) {
  230. if (showControls) {
  231. optionalControls.style.visibility = defaultVisibilityValue;
  232. optionalControls.style.opacity = 0.8;
  233. } else {
  234. optionalControls.style.display = 'none';
  235. }
  236. }
  237. if (!showHeader) {
  238. if (header) {
  239. header.style.display = 'none';
  240. }
  241. } else {
  242. if (header) {
  243. header.style.opacity = 1.0;
  244. }
  245. }
  246. // Hide error
  247. error();
  248. if (showControls) {
  249. const optionalControls = document.getElementById('optionalControls');
  250. if (optionalControls) {
  251. optionalControls.style.opacity = 1.0;
  252. // optionalControls.appendChild(zoomControlsButtons);
  253. // optionalControls.appendChild(zoomControlsString);
  254. optionalControls.style.position = 'absolute';
  255. optionalControls.style.zIndex = '10';
  256. optionalControls.style.right = '10px';
  257. // optionalControls.style.padding = '10px';
  258. }
  259. if (showZoomControl) {
  260. const zoomControlsButtonsColumn = document.getElementById('zoomControlsButtons-optional-column');
  261. zoomControlsButtonsColumn.style.opacity = 1.0;
  262. // const zoomControlsButtons = document.getElementById('zoomControlsButtons-optional');
  263. // zoomControlsButtons.style.opacity = 1.0;
  264. const zoomControlsString = document.getElementById('zoom-str-optional'); // actually === zoomDivs[1] above
  265. if (zoomControlsString) {
  266. zoomControlsString.innerHTML = Math.floor(zoom * 100.0) + "%";
  267. zoomControlsString.style.display = 'inline';
  268. // zoomControlsString.style.padding = '10px';
  269. }
  270. }
  271. if (showExportPdfControl) {
  272. const exportPdfButtonColumn = document.getElementById('print-pdf-btn-optional-column');
  273. if (exportPdfButtonColumn) {
  274. exportPdfButtonColumn.style.opacity = 1.0;
  275. }
  276. }
  277. const pageFormatControlColumn = document.getElementById("selectPageSize-optional-column");
  278. if (pageFormatControlColumn) {
  279. if (showPageFormatControl) {
  280. pageFormatControlColumn.style.opacity = 1.0;
  281. } else {
  282. // showPageFormatControlColumn.innerHTML = "";
  283. // pageFormatControlColumn.style.minWidth = 0;
  284. // pageFormatControlColumn.style.width = 0;
  285. pageFormatControlColumn.style.display = 'none'; // squeezes buttons/columns
  286. // pageFormatControlColumn.style.visibility = 'hidden';
  287. // const optionalControlsColumnContainer = document.getElementById("optionalControlsColumnContainer");
  288. // optionalControlsColumnContainer.removeChild(pageFormatControlColumn);
  289. // optionalControlsColumnContainer.width *= 0.66;
  290. // optionalControls.witdh *= 0.66;
  291. // optionalControls.focus();
  292. }
  293. }
  294. }
  295. // Create select
  296. for (name in samples) {
  297. if (samples.hasOwnProperty(name)) {
  298. option = document.createElement("option");
  299. option.value = samples[name];
  300. option.textContent = name;
  301. }
  302. if (selectSample) {
  303. selectSample.appendChild(option);
  304. }
  305. }
  306. if (selectSample) {
  307. selectSample.onchange = selectSampleOnChange;
  308. }
  309. if (selectBounding) {
  310. selectBounding.onchange = selectBoundingOnChange;
  311. }
  312. for (const selectPageSize of selectPageSizes) {
  313. if (selectPageSize) {
  314. selectPageSize.onchange = function (evt) {
  315. var value = evt.target.value;
  316. openSheetMusicDisplay.setPageFormat(value);
  317. openSheetMusicDisplay.render();
  318. };
  319. }
  320. }
  321. for (const printPdfBtn of printPdfBtns) {
  322. if (printPdfBtn) {
  323. printPdfBtn.onclick = function () {
  324. openSheetMusicDisplay.createPdf();
  325. }
  326. }
  327. }
  328. // Pre-select default music piece
  329. custom.appendChild(document.createTextNode("Custom"));
  330. // Create zoom controls
  331. for (const zoomIn of zoomIns) {
  332. if (zoomIn) {
  333. zoomIn.onclick = function () {
  334. zoom *= 1.2;
  335. scale();
  336. };
  337. }
  338. }
  339. for (const zoomOut of zoomOuts) {
  340. if (zoomOut) {
  341. zoomOut.onclick = function () {
  342. zoom /= 1.2;
  343. scale();
  344. };
  345. }
  346. }
  347. if (skylineDebug) {
  348. skylineDebug.onclick = function () {
  349. openSheetMusicDisplay.DrawSkyLine = !openSheetMusicDisplay.DrawSkyLine;
  350. }
  351. }
  352. if (bottomlineDebug) {
  353. bottomlineDebug.onclick = function () {
  354. openSheetMusicDisplay.DrawBottomLine = !openSheetMusicDisplay.DrawBottomLine;
  355. }
  356. }
  357. if (debugReRenderBtn) {
  358. debugReRenderBtn.onclick = function () {
  359. rerender();
  360. }
  361. }
  362. if (debugClearBtn) {
  363. debugClearBtn.onclick = function () {
  364. openSheetMusicDisplay.clear();
  365. }
  366. }
  367. // Create OSMD object and canvas
  368. openSheetMusicDisplay = new OpenSheetMusicDisplay(canvas, {
  369. autoResize: true,
  370. backend: backendType,
  371. //backend: "canvas",
  372. disableCursor: false,
  373. drawingParameters: compactMode ? "compact" : "default", // try compact (instead of default)
  374. drawPartNames: true, // try false
  375. // drawTitle: false,
  376. // drawSubtitle: false,
  377. drawFingerings: true,
  378. fingeringPosition: "left", // left is default. try right. experimental: auto, above, below.
  379. // fingeringInsideStafflines: "true", // default: false. true draws fingerings directly above/below notes
  380. setWantedStemDirectionByXml: true, // try false, which was previously the default behavior
  381. // drawUpToMeasureNumber: 3, // draws only up to measure 3, meaning it draws measure 1 to 3 of the piece.
  382. drawFromMeasureNumber : measureRangeStart,
  383. drawUpToMeasureNumber : measureRangeEnd,
  384. //drawMeasureNumbers: false, // disable drawing measure numbers
  385. //measureNumberInterval: 4, // draw measure numbers only every 4 bars (and at the beginning of a new system)
  386. // coloring options
  387. coloringEnabled: true,
  388. // defaultColorNotehead: "#CC0055", // try setting a default color. default is black (undefined)
  389. // defaultColorStem: "#BB0099",
  390. autoBeam: false, // try true, OSMD Function Test AutoBeam sample
  391. autoBeamOptions: {
  392. beam_rests: false,
  393. beam_middle_rests_only: false,
  394. //groups: [[3,4], [1,1]],
  395. maintain_stem_directions: false
  396. },
  397. pageFormat: pageFormat,
  398. pageBackgroundColor: pageBackgroundColor,
  399. renderSingleHorizontalStaffline: singleHorizontalStaffline
  400. // tupletsBracketed: true, // creates brackets for all tuplets except triplets, even when not set by xml
  401. // tripletsBracketed: true,
  402. // tupletsRatioed: true, // unconventional; renders ratios for tuplets (3:2 instead of 3 for triplets)
  403. });
  404. openSheetMusicDisplay.setLogLevel('info'); // set this to 'debug' if you want to see more detailed control flow information in console
  405. document.body.appendChild(canvas);
  406. window.addEventListener("keydown", function (e) {
  407. var event = window.event ? window.event : e;
  408. if (event.keyCode === 39) {
  409. openSheetMusicDisplay.cursor.next();
  410. }
  411. });
  412. nextCursorBtn.addEventListener("click", function () {
  413. openSheetMusicDisplay.cursor.next();
  414. });
  415. resetCursorBtn.addEventListener("click", function () {
  416. openSheetMusicDisplay.cursor.reset();
  417. });
  418. if (followCursorCheckbox) {
  419. followCursorCheckbox.onclick = function () {
  420. openSheetMusicDisplay.FollowCursor = !openSheetMusicDisplay.FollowCursor;
  421. }
  422. }
  423. hideCursorBtn.addEventListener("click", function () {
  424. if (openSheetMusicDisplay.cursor) {
  425. openSheetMusicDisplay.cursor.hide();
  426. } else {
  427. console.info("Can't hide cursor, as it was disabled (e.g. by drawingParameters).");
  428. }
  429. });
  430. showCursorBtn.addEventListener("click", function () {
  431. if (openSheetMusicDisplay.cursor) {
  432. openSheetMusicDisplay.cursor.show();
  433. } else {
  434. console.info("Can't show cursor, as it was disabled (e.g. by drawingParameters).");
  435. }
  436. });
  437. backendSelect.addEventListener("change", function (e) {
  438. var value = e.target.value;
  439. var createNewOsmd = true;
  440. if (createNewOsmd) {
  441. // clears the canvas element
  442. canvas.innerHTML = "";
  443. openSheetMusicDisplay = new OpenSheetMusicDisplay(canvas, { backend: value });
  444. openSheetMusicDisplay.setLogLevel('info'); // set this to 'debug' if you want to get more detailed control flow information
  445. } else {
  446. // alternative, doesn't work yet, see setOptions():
  447. openSheetMusicDisplay.setOptions({ backend: value });
  448. }
  449. console.log("[OSMD] selectSampleOnChange addEventListener change");
  450. // selectSampleOnChange();
  451. });
  452. if (paramOpenUrl !== undefined) {
  453. if (openSheetMusicDisplay.getLogLevel() < 2) { // debug or trace
  454. console.log("[OSMD] selectSampleOnChange with " + paramOpenUrl);
  455. }
  456. // DEBUG: cause an error for a certain sample, for testing
  457. // if (paramOpenUrl.startsWith("Beethoven")) {
  458. // paramOpenUrl.causeError();
  459. // }
  460. selectSampleOnChange(paramOpenUrl);
  461. } else {
  462. if (openSheetMusicDisplay.getLogLevel() < 2) { // debug or trace
  463. console.log("[OSMD] selectSampleOnChange without param");
  464. }
  465. selectSampleOnChange();
  466. }
  467. }
  468. function findGetParameter(parameterName) {
  469. // special treatment for the openUrl parameter, because different systems attach different arguments to an URL.
  470. // because of CORS (cross-origin safety restrictions), you can only load an xml file from the same origin (server).
  471. // 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
  472. // (enable the console.log at the end of this method for testing)
  473. // working test parameter in local demo: ?openUrl=OSMD_function_test_all.xml&endUrl
  474. if (parameterName === 'openUrl') {
  475. let startParameterName = 'openUrl=';
  476. let endParameterName = '&endUrl';
  477. let openUrlIndex = location.search.indexOf(startParameterName);
  478. if (openUrlIndex < 0) {
  479. return undefined;
  480. }
  481. let endIndex = location.search.indexOf(endParameterName) + endParameterName.length;
  482. if (endIndex < 0) {
  483. console.log("[OSMD] If using openUrl as a parameter, you have to end it with '&endUrl'. openUrl parameter omitted.");
  484. return undefined;
  485. }
  486. let urlString = location.search.substring(openUrlIndex + startParameterName.length, endIndex - endParameterName.length);
  487. //console.log("openUrl: " + urlString);
  488. return urlString;
  489. }
  490. let result = undefined;
  491. let tmp = [];
  492. location.search
  493. .substr(1)
  494. .split('&')
  495. .forEach(function (item) {
  496. tmp = item.split('=');
  497. if (tmp[0] === parameterName) {
  498. result = decodeURIComponent(tmp[1]);
  499. //console.log('Found param:' + parameterName + ' = ' + result);
  500. }
  501. });
  502. return result;
  503. }
  504. function selectBoundingOnChange(evt) {
  505. var value = evt.target.value;
  506. openSheetMusicDisplay.DrawBoundingBox = value;
  507. }
  508. function selectSampleOnChange(str) {
  509. error();
  510. disable();
  511. var isCustom = typeof str === "string";
  512. if (!isCustom) {
  513. if (selectSample) {
  514. str = sampleFolder + selectSample.value;
  515. } else {
  516. if (samples && samples.length > 0) {
  517. str = sampleFolder + samples[0];
  518. } else {
  519. return; // no sample to load right now
  520. }
  521. }
  522. }
  523. // zoom = 1.0;
  524. setSampleSpecificOptions(str, isCustom);
  525. openSheetMusicDisplay.load(str).then(
  526. function () {
  527. // This gives you access to the osmd object in the console. Do not use in productive code
  528. window.osmd = openSheetMusicDisplay;
  529. openSheetMusicDisplay.zoom = zoom;
  530. return openSheetMusicDisplay.render();
  531. },
  532. function (e) {
  533. errorLoadingOrRenderingSheet(e, "rendering");
  534. }
  535. ).then(
  536. function () {
  537. return onLoadingEnd(isCustom);
  538. }, function (e) {
  539. errorLoadingOrRenderingSheet(e, "loading");
  540. onLoadingEnd(isCustom);
  541. }
  542. );
  543. }
  544. function setSampleSpecificOptions(str, isCustom) {
  545. if (!isCustom && str.includes("measuresToDraw")) { // set options for measuresToDraw sample
  546. // stash previously set range of measures to draw
  547. if (!measureToDrawRangeNeedsReset) { // only stash once, when measuresToDraw called multiple times in a row
  548. minMeasureToDrawStashed = openSheetMusicDisplay.EngravingRules.MinMeasureToDrawIndex + 1;
  549. maxMeasureToDrawStashed = openSheetMusicDisplay.EngravingRules.MaxMeasureToDrawIndex + 1;
  550. }
  551. measureToDrawRangeNeedsReset = true;
  552. // for debugging: draw from a random range of measures
  553. let minMeasureToDraw = Math.ceil(Math.random() * 15); // measures start at 1 (measureIndex = measure number - 1 elsewhere)
  554. let maxMeasureToDraw = Math.ceil(Math.random() * 15);
  555. if (minMeasureToDraw > maxMeasureToDraw) {
  556. minMeasureToDraw = maxMeasureToDraw;
  557. let a = minMeasureToDraw;
  558. maxMeasureToDraw = a;
  559. }
  560. //minMeasureToDraw = 1; // set your custom indexes here. Drawing only one measure can be a special case
  561. //maxMeasureToDraw = 1;
  562. console.log("drawing measures in the range: [" + minMeasureToDraw + "," + maxMeasureToDraw + "]");
  563. openSheetMusicDisplay.setOptions({
  564. drawFromMeasureNumber: minMeasureToDraw,
  565. drawUpToMeasureNumber: maxMeasureToDraw
  566. });
  567. } else if (measureToDrawRangeNeedsReset) { // reset for other samples
  568. openSheetMusicDisplay.setOptions({
  569. drawFromMeasureNumber: minMeasureToDrawStashed,
  570. drawUpToMeasureNumber: maxMeasureToDrawStashed
  571. });
  572. measureToDrawRangeNeedsReset = false;
  573. }
  574. // Enable Boomwhacker-like coloring for OSMD Function Test - Auto-Coloring (Boomwhacker-like, custom color set)
  575. if (!isCustom && str.includes("auto-custom-coloring")) { // set options for auto coloring sample
  576. autoCustomColoringOptionNeedsReset = true;
  577. //openSheetMusicDisplay.setOptions({coloringMode: 1}); // Auto-Coloring with pre-defined colors
  578. openSheetMusicDisplay.setOptions({
  579. coloringMode: 2, // custom coloring set. 0 would be XML, 1 autocoloring
  580. coloringSetCustom: ["#d82c6b", "#F89D15", "#FFE21A", "#4dbd5c", "#009D96", "#43469d", "#76429c", "#ff0000"],
  581. // last color value of coloringSetCustom is for rest notes
  582. colorStemsLikeNoteheads: true
  583. });
  584. } else if (autoCustomColoringOptionNeedsReset) {
  585. openSheetMusicDisplay.setOptions({ // set default values. better would be to restore to stashed values, but unnecessarily complex for demo
  586. coloringMode: 0,
  587. colorStemsLikeNoteheads: false,
  588. coloringSetCustom: null
  589. });
  590. autoCustomColoringOptionNeedsReset = false;
  591. }
  592. if (!isCustom && str.includes("autobeam")) {
  593. autobeamOptionStashedValue = openSheetMusicDisplay.EngravingRules.AutoBeamNotes; // stash previously set value, to restore later
  594. autobeamOptionNeedsReset = true;
  595. openSheetMusicDisplay.setOptions({ autoBeam: true });
  596. } else if (autobeamOptionNeedsReset) {
  597. openSheetMusicDisplay.setOptions({ autoBeam: autobeamOptionStashedValue });
  598. autobeamOptionNeedsReset = false;
  599. }
  600. if (!isCustom && str.includes("Schubert_An_die_Musik")) { // TODO weird layout bug here with part names. but shouldn't be in score anyways
  601. drawPartNamesOptionStashedValue = openSheetMusicDisplay.EngravingRules.RenderPartNames;
  602. drawPartAbbreviationsStashedValue = openSheetMusicDisplay.EngravingRules.RenderPartAbbreviations;
  603. openSheetMusicDisplay.setOptions({ drawPartNames: false, drawPartAbbreviations: false }); // TODO sets osmd.drawingParameters.DrawPartNames! also check EngravingRules.RenderPartAbbreviations, was false
  604. drawPartNamesOptionNeedsReset = true;
  605. } else if (drawPartNamesOptionNeedsReset) {
  606. openSheetMusicDisplay.setOptions({ drawPartNames: drawPartNamesOptionStashedValue, drawPartAbbreviations: drawPartAbbreviationsStashedValue });
  607. drawPartNamesOptionNeedsReset = false;
  608. }
  609. }
  610. function errorLoadingOrRenderingSheet(e, loadingOrRenderingString) {
  611. var errorString = "Error " + loadingOrRenderingString + " sheet: " + e;
  612. // if (process.env.DEBUG) { // people may not set a debug environment variable for the demo.
  613. // Always giving a StackTrace might give us more and better error reports.
  614. // TODO for a release, StackTrace control could be reenabled
  615. errorString += "\n" + "StackTrace: \n" + e.stack;
  616. // }
  617. console.warn(errorString);
  618. }
  619. function onLoadingEnd(isCustom) {
  620. // Remove option from select
  621. if (!isCustom && custom.parentElement === selectSample) {
  622. selectSample.removeChild(custom);
  623. }
  624. // Enable controls again
  625. enable();
  626. }
  627. function logCanvasSize() {
  628. for (const zoomDiv of zoomDivs) {
  629. if (zoomDiv) {
  630. zoomDiv.innerHTML = Math.floor(zoom * 100.0) + "%";
  631. }
  632. }
  633. }
  634. function scale() {
  635. disable();
  636. window.setTimeout(function () {
  637. openSheetMusicDisplay.Zoom = zoom;
  638. openSheetMusicDisplay.render();
  639. enable();
  640. }, 0);
  641. }
  642. function rerender() {
  643. disable();
  644. window.setTimeout(function () {
  645. if (openSheetMusicDisplay.IsReadyToRender()) {
  646. openSheetMusicDisplay.render();
  647. } else {
  648. console.log("[OSMD demo] Looses context!"); // TODO not sure that this message is reasonable, renders fine anyways. maybe vexflow context lost?
  649. selectSampleOnChange(); // reload sample e.g. after osmd.clear()
  650. }
  651. enable();
  652. }, 0);
  653. }
  654. function error(errString) {
  655. if (!errString) {
  656. error_tr.style.display = "none";
  657. } else {
  658. console.log("[OSMD demo] error: " + errString)
  659. err.textContent = errString;
  660. error_tr.style.display = "";
  661. canvas.width = canvas.height = 0;
  662. enable();
  663. }
  664. }
  665. // Enable/Disable Controls
  666. function disable() {
  667. document.body.style.opacity = 0.3;
  668. setDisabledForControls("disabled");
  669. }
  670. function enable() {
  671. document.body.style.opacity = 1;
  672. setDisabledForControls("");
  673. logCanvasSize();
  674. }
  675. function setDisabledForControls(disabledValue) {
  676. if (selectSample) {
  677. selectSample.disabled = disabledValue;
  678. }
  679. for (const zoomIn of zoomIns) {
  680. if (zoomIn) {
  681. zoomIn.disabled = disabledValue;
  682. }
  683. }
  684. for (const zoomOut of zoomOuts) {
  685. if (zoomOut) {
  686. zoomOut.disabled = disabledValue;
  687. }
  688. }
  689. }
  690. // Register events: load, drag&drop
  691. window.addEventListener("load", function () {
  692. init();
  693. });
  694. window.addEventListener("dragenter", function (event) {
  695. event.preventDefault();
  696. disable();
  697. });
  698. window.addEventListener("dragover", function (event) {
  699. event.preventDefault();
  700. });
  701. window.addEventListener("dragleave", function (event) {
  702. enable();
  703. });
  704. window.addEventListener("drop", function (event) {
  705. event.preventDefault();
  706. if (!event.dataTransfer || !event.dataTransfer.files || event.dataTransfer.files.length === 0) {
  707. return;
  708. }
  709. // Add "Custom..." score
  710. selectSample.appendChild(custom);
  711. custom.selected = "selected";
  712. // Read dragged file
  713. var reader = new FileReader();
  714. reader.onload = function (res) {
  715. selectSampleOnChange(res.target.result);
  716. };
  717. var filename = event.dataTransfer.files[0].name;
  718. if (filename.toLowerCase().indexOf(".xml") > 0
  719. || filename.toLowerCase().indexOf(".musicxml") > 0) {
  720. reader.readAsText(event.dataTransfer.files[0]);
  721. } else if (event.dataTransfer.files[0].name.toLowerCase().indexOf(".mxl") > 0) {
  722. reader.readAsBinaryString(event.dataTransfer.files[0]);
  723. }
  724. else {
  725. alert("No vaild .xml/.mxl/.musicxml file!");
  726. }
  727. });
  728. }());