index.js 39 KB

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