index.js 40 KB

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