index.js 41 KB

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