index.js 41 KB

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