index.js 41 KB

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