index.js 39 KB

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