index.js 39 KB

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