index.js 40 KB

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