index.js 37 KB

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