index.js 37 KB

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