index.js 40 KB

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