index.js 39 KB

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