index.js 40 KB

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