index.js 37 KB

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