generateDiffImagesPuppeteerLocalhost.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. /*
  2. Render each OSMD sample, grab the generated images, and
  3. dump them into a local directory as PNG files.
  4. inspired by Vexflow's generate_png_images and vexflow-tests.js
  5. This is meant to be used with the visual regression test system in
  6. `tools/visual_regression.sh`. (TODO)
  7. */
  8. // function sleep(ms) {
  9. // return new Promise((resolve) => {
  10. // setTimeout(resolve, ms);
  11. // });
  12. // }
  13. const osmdPort = 8000 // OSMD webpack server port. OSMD has to be running (npm start) when this script runs.
  14. // main function
  15. async function init () {
  16. console.log('init')
  17. const fs = require('fs')
  18. const [sampleDir, imageDir, filterRegex] = process.argv.slice(2, 5)
  19. console.log('sampleDir: ' + sampleDir)
  20. console.log('imageDir: ' + imageDir)
  21. if (!sampleDir || !imageDir) {
  22. console.log('usage: node test/Util/generateDiffImagesPuppeteerLocalhost sampleDirectory imageDirectory [filterRegex]')
  23. console.log('Error: need sampleDir and imageDir. Exiting.')
  24. process.exit(-1)
  25. }
  26. // Create the image directory if it doesn't exist.
  27. fs.mkdirSync(imageDir, { recursive: true })
  28. // TODO fetch samples from sampleDir (iterate over all files in folder)
  29. const samples = {
  30. 'Beethoven, L.v. - An die ferne Geliebte': 'Beethoven_AnDieFerneGeliebte.xml',
  31. // ' Beethoven Evil filename test': 'Beethoven&Evil/Filename.xml', // TODO may need decodeURIComponent in OSMD openURL parsing
  32. 'Clementi, M. - Sonatina Op.36 No.1 Pt.1': 'MuzioClementi_SonatinaOpus36No1_Part1.xml',
  33. 'Clementi, M. - Sonatina Op.36 No.1 Pt.2': 'MuzioClementi_SonatinaOpus36No1_Part2.xml',
  34. 'Clementi, M. - Sonatina Op.36 No.3 Pt.1': 'MuzioClementi_SonatinaOpus36No3_Part1.xml',
  35. 'Clementi, M. - Sonatina Op.36 No.3 Pt.2': 'MuzioClementi_SonatinaOpus36No3_Part2.xml',
  36. 'Bach, J.S. - Praeludium in C-Dur BWV846 1': 'JohannSebastianBach_PraeludiumInCDur_BWV846_1.xml',
  37. 'Bach, J.S. - Air': 'JohannSebastianBach_Air.xml',
  38. // 'Gounod, C. - Méditation': 'CharlesGounod_Meditation.xml', // TODO this Gounod sample fails to generate a proper PNG image for some reason
  39. 'Haydn, J. - Concertante Cello': 'JosephHaydn_ConcertanteCello.xml',
  40. 'Joplin, S. - Elite Syncopations': 'ScottJoplin_EliteSyncopations.xml',
  41. 'Joplin, S. - The Entertainer': 'ScottJoplin_The_Entertainer.xml',
  42. 'Mozart, W.A. - An Chloe': 'Mozart_AnChloe.xml',
  43. 'Mozart, W.A. - Das Veilchen': 'Mozart_DasVeilchen.xml',
  44. 'Mozart, W.A. - Clarinet Quintet (Excerpt)': 'Mozart_Clarinet_Quintet_Excerpt.mxl',
  45. 'Mozart, W.A. - String Quartet in G, K. 387, 1st Mvmt Excerpt': 'Mozart_String_Quartet_in_G_K._387_1st_Mvmnt_excerpt.musicxml',
  46. 'Mozart/Holzer - Land der Berge (national anthem of Austria)': 'Land_der_Berge.musicxml',
  47. 'OSMD Function Test - All': 'OSMD_function_test_all.xml',
  48. 'OSMD Function Test - Accidentals': 'OSMD_function_test_accidentals.musicxml',
  49. 'OSMD Function Test - Autobeam': 'OSMD_function_test_autobeam.musicxml',
  50. 'OSMD Function Test - Auto-/Custom-Coloring': 'OSMD_function_test_auto-custom-coloring-entchen.musicxml',
  51. 'OSMD Function Test - Bar lines': 'OSMD_function_test_bar_lines.musicxml',
  52. 'OSMD Function Test - Color (from XML)': 'OSMD_function_test_color.musicxml',
  53. 'OSMD Function Test - Drumset': 'OSMD_function_test_drumset.musicxml',
  54. 'OSMD Function Test - Expressions': 'OSMD_function_test_expressions.musicxml',
  55. 'OSMD Function Test - Expressions Overlap': 'OSMD_function_test_expressions_overlap.musicxml',
  56. 'OSMD Function Test - Grace Notes': 'OSMD_function_test_GraceNotes.xml',
  57. 'OSMD Function Test - Invisible Notes': 'OSMD_function_test_invisible_notes.musicxml',
  58. 'OSMD Function Test - Selecting Measures To Draw': 'OSMD_function_test_measuresToDraw_Beethoven_AnDieFerneGeliebte.xml',
  59. 'OSMD Function Test - Notehead Shapes': 'OSMD_function_test_noteheadShapes.musicxml',
  60. 'OSMD Function Test - Ornaments': 'OSMD_function_test_Ornaments.xml',
  61. 'OSMD Function Test - Tremolo': 'OSMD_Function_Test_Tremolo_2bars.musicxml',
  62. 'Schubert, F. - An Die Musik': 'Schubert_An_die_Musik.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. // 'Hello World': 'HelloWorld.xml',
  70. // 'Clementi, M. - Sonatina Op.36 No.1 Pt.2': 'MuzioClementi_SonatinaOpus36No1_Part2.xml',
  71. }
  72. // const sampleKeys = Object.keys(samples)
  73. let sampleValues = Object.values(samples)
  74. // filter regex if given
  75. if (filterRegex && filterRegex !== '') {
  76. console.log('filtering samples for regex: ' + filterRegex)
  77. sampleValues = sampleValues.filter((filename) => filename.match(filterRegex))
  78. console.log(`found ${sampleValues.length} matches: `)
  79. for (let i = 0; i < sampleValues.length; i++) {
  80. console.log(sampleValues[i])
  81. }
  82. }
  83. const puppeteer = require('puppeteer')
  84. const browser = await puppeteer.launch({ headless: true })
  85. const page = await browser.newPage() // TODO set width/height
  86. const defaultTimeoutInMs = 30000
  87. page.setDefaultNavigationTimeout(defaultTimeoutInMs) // default setting for page navigationtimeout is 30000ms.
  88. // fix navigation error
  89. var responseEventOccurred = false
  90. var responseHandler = function (event) { responseEventOccurred = true }
  91. var responseWatcher = new Promise(function (resolve, reject) {
  92. setTimeout(function () {
  93. if (!responseEventOccurred) {
  94. resolve(true)
  95. } else {
  96. setTimeout(function () { resolve(true) }, defaultTimeoutInMs)
  97. }
  98. page.removeListener('response', responseHandler)
  99. }, 1000)
  100. })
  101. page.on('response', responseHandler)
  102. // get image data
  103. const getDataUrl = async (page) => {
  104. return page.evaluate(async () => {
  105. return new Promise(resolve => {
  106. const canvasImage = document.getElementById('osmdCanvasVexFlowBackendCanvas')
  107. var imageData = canvasImage.toDataURL()
  108. // TODO fetch multiple pages from multiple OSMD backends
  109. resolve(imageData)
  110. })
  111. })
  112. }
  113. // generate png for all given samples
  114. for (let i = 0; i < sampleValues.length; i++) {
  115. const sampleFileName = encodeURIComponent(sampleValues[i]) // escape slashes, '&' and so on
  116. const sampleParameter = `&openUrl=${sampleFileName}&endUrl`
  117. const pageUrl = `http://localhost:${osmdPort}?showHeader=0&debugControls=0&backendType=canvas&pageBackgroundColor=FFFFFF${sampleParameter}`
  118. console.log('puppeteer: page.goto url: ' + pageUrl)
  119. try {
  120. await page.goto(pageUrl, { waitUntil: 'networkidle2' })
  121. } catch (error) {
  122. console.log(error)
  123. console.log('[OSMD.generateImages] Error generating images: could not reach local OSMD server. ' +
  124. 'Make sure to start OSMD local webpack server (npm start) before running this script.')
  125. process.exit(-1) // exit script with error. otherwise process will continue running
  126. }
  127. console.log('puppeteer.page.goto done. (now fetching image data)')
  128. var navigationWatcher = page.waitForNavigation()
  129. await Promise.race([responseWatcher, navigationWatcher])
  130. console.log('navigation race done')
  131. const dataUrl = await getDataUrl(page)
  132. // console.log('dataUrl: ' + dataUrl);
  133. const imageData = dataUrl.split(';base64,').pop()
  134. const imageBuffer = Buffer.from(imageData, 'base64')
  135. var fileName = `${imageDir}/${sampleFileName}.png`
  136. console.log('got image data, saving to: ' + fileName)
  137. fs.writeFileSync(fileName, imageBuffer, { encoding: 'base64' })
  138. }
  139. // const html = await page.content();
  140. // console.log('page content: ' + html);
  141. browser.close()
  142. console.log('puppeteer browser closed. exiting.')
  143. }
  144. // function start() {
  145. // // await (async () => {
  146. // // init();
  147. // // });
  148. // (async function(){
  149. // await init();
  150. // // more code here or the await is useless
  151. // })();
  152. // }
  153. // function resizeCanvas (elementId, width, height) {
  154. // $('#' + elementId).width(width)
  155. // $('#' + elementId).attr('width', width)
  156. // $('#' + elementId).attr('height', height)
  157. // }
  158. init()