index.js 41 KB

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