index.js 39 KB

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