generateDiffImagesPuppeteerLocalhost.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. /*
  2. Render each OSMD sample in a headless browser
  3. (using puppeteer, requires ~100MB chromium download),
  4. grab the generated images, and
  5. dump them into a local directory as PNG files.
  6. You may have to install puppeteer as dev dependency to run this:
  7. npm i puppeteer --save-dev
  8. (will download ~100MB for Chromium)
  9. This script is made obsolete by the ~2x faster generateImages_browserless.mjs,
  10. but may be useful for comparison.
  11. inspired by Vexflow's generate_png_images and vexflow-tests.js
  12. This is meant to be used with the visual regression test system in
  13. `tools/visual_regression.sh`.
  14. */
  15. function sleep (ms) {
  16. return new Promise((resolve) => {
  17. setTimeout(resolve, ms)
  18. })
  19. }
  20. const osmdPort = 8000 // OSMD webpack server port. OSMD has to be running (npm start) when this script runs.
  21. // try this to debug: node --inspect=9229 test/Util/generateDiffImagesPuppeteerLocalhost.js test/data/ export/ 5000
  22. // main function
  23. async function init () {
  24. console.log('[OSMD.generate] init')
  25. let [sampleDir, imageDir, pageWidth, pageHeight, filterRegex, debugFlag, debugSleepTimeString] = process.argv.slice(2, 9)
  26. if (!sampleDir || !imageDir) {
  27. console.log('usage: node test/Util/generateDiffImagesPuppeteerLocalhost.js sampleDirectory imageDirectory [width|0] [height|0] [filterRegex|all] [--debug] [debugSleepTime]')
  28. console.log(' (use "all" to skip filterRegex parameter)')
  29. console.log('example: node ./test/Util/generateDiffImagesPuppeteerLocalhost.js ./test/data/ ./export 210 297 all --debug 5000')
  30. console.log('Error: need sampleDir and imageDir. Exiting.')
  31. process.exit(1)
  32. }
  33. console.log('sampleDir: ' + sampleDir)
  34. console.log('imageDir: ' + imageDir)
  35. let pageFormatParameter = ''
  36. pageHeight = Number.parseInt(pageHeight)
  37. pageWidth = Number.parseInt(pageWidth)
  38. if(!pageWidth || pageWidth === NaN){
  39. pageWidth = 800
  40. }
  41. if(!pageHeight || pageHeight === NaN){
  42. pageHeight = 600
  43. }
  44. const DEBUG = debugFlag === '--debug'
  45. // const debugSleepTime = Number.parseInt(process.env.GENERATE_DEBUG_SLEEP_TIME) || 0; // 5000 works for me [sschmidTU]
  46. if (DEBUG) {
  47. console.log('debug sleep time: ' + debugSleepTimeString)
  48. const debugSleepTimeMs = Number.parseInt(debugSleepTimeString)
  49. if (debugSleepTimeMs > 0) {
  50. await sleep(Number.parseInt(debugSleepTimeMs))
  51. // [VSCode] apparently this is necessary for the debugger to attach itself in time before the program closes.
  52. // sometimes this is not enough, so you may have to try multiple times or increase the sleep timer. Unfortunately debugging nodejs isn't easy.
  53. }
  54. }
  55. const fs = require('fs')
  56. // Create the image directory if it doesn't exist.
  57. fs.mkdirSync(imageDir, { recursive: true })
  58. const sampleDirFilenames = fs.readdirSync(sampleDir)
  59. let samplesToProcess = [] // samples we want to process/generate pngs of, excluding the filtered out files/filenames
  60. for (const sampleFilename of sampleDirFilenames) {
  61. if (DEBUG) {
  62. if (sampleFilename.match('^(Actor)|(Gounod)')) {
  63. console.log('DEBUG: filtering big file: ' + sampleFilename)
  64. continue
  65. }
  66. }
  67. // eslint-disable-next-line no-useless-escape
  68. if (sampleFilename.match('^.*(\.xml)|(\.musicxml)|(\.mxl)$')) {
  69. // console.log('found musicxml/mxl: ' + sampleFilename)
  70. samplesToProcess.push(sampleFilename)
  71. } else {
  72. console.log('discarded file/directory: ' + sampleFilename)
  73. }
  74. }
  75. // filter samples to process by regex if given
  76. if (filterRegex && filterRegex !== '' && filterRegex !== 'all') {
  77. console.log('filtering samples for regex: ' + filterRegex)
  78. samplesToProcess = samplesToProcess.filter((filename) => filename.match(filterRegex))
  79. console.log(`found ${samplesToProcess.length} matches: `)
  80. for (let i = 0; i < samplesToProcess.length; i++) {
  81. console.log(samplesToProcess[i])
  82. }
  83. }
  84. const puppeteer = require('puppeteer')
  85. const browser = await puppeteer.launch({ headless: true })
  86. const page = await browser.newPage()
  87. page.setViewport({
  88. width: pageWidth,
  89. height: pageHeight,
  90. deviceScaleFactor: 1
  91. });
  92. const defaultTimeoutInMs = 100000
  93. page.setDefaultNavigationTimeout(defaultTimeoutInMs) // default setting for page navigationtimeout is 30000ms.
  94. // fix navigation error
  95. var responseEventOccurred = false
  96. var responseHandler = function (event) { responseEventOccurred = true }
  97. var responseWatcher = new Promise(function (resolve, reject) {
  98. setTimeout(function () {
  99. if (!responseEventOccurred) {
  100. resolve(true)
  101. } else {
  102. setTimeout(function () { resolve(true) }, defaultTimeoutInMs)
  103. }
  104. page.removeListener('response', responseHandler)
  105. }, 1000)
  106. })
  107. page.on('response', responseHandler)
  108. if (DEBUG) {
  109. // pipe console output on the page to the console node is running from, otherwise these logs from the headless browser aren't visible
  110. page.on('console', msg => console.log(msg.text()))
  111. }
  112. page.on('error', err => console.log(err))
  113. page.on('pageerror', err => console.log(err)) // this one triggers for js errors in index.js, for example
  114. // get image data
  115. const getDataUrl = async (page, sampleFilename) => {
  116. return page.evaluate(async () => {
  117. return new Promise(resolve => {
  118. const imageDataArray = []
  119. let canvasImage
  120. for (let pageNumber = 1; pageNumber < 999; pageNumber++) {
  121. canvasImage = document.getElementById('osmdCanvasVexFlowBackendCanvas' + pageNumber)
  122. if (!canvasImage) {
  123. break
  124. }
  125. if (!canvasImage.toDataURL) {
  126. console.log(`error: could not get canvas image for page ${pageNumber} for file: ${sampleFilename}`)
  127. break
  128. }
  129. imageDataArray.push(canvasImage.toDataURL())
  130. }
  131. // while (canvasImage = document.getElementById('osmdCanvasVexFlowBackendCanvas' + pageNumber)) {
  132. // imageData = canvasImage.toDataURL()
  133. // console.log("got em. " + pageNumber)
  134. // }
  135. // TODO fetch multiple pages from multiple OSMD backends
  136. resolve(imageDataArray)
  137. })
  138. })
  139. }
  140. // generate png for all given samples
  141. for (let i = 0; i < samplesToProcess.length; i++) {
  142. const sampleFilename = encodeURIComponent(samplesToProcess[i]) // escape slashes, '&' and so on
  143. const sampleParameter = `&openUrl=${sampleFilename}&endUrl`
  144. const pageUrl = `http://localhost:${osmdPort}?showHeader=0&debugControls=0&backendType=canvas&pageBackgroundColor=FFFFFF` +
  145. sampleParameter +
  146. pageFormatParameter
  147. console.log('puppeteer: page.goto url: ' + pageUrl)
  148. try {
  149. await page.goto(pageUrl, { waitUntil: 'networkidle2' })
  150. } catch (error) {
  151. console.log(error)
  152. console.log('[OSMD.generateImages] Error generating images: could not reach local OSMD server. ' +
  153. 'Make sure to start OSMD local webpack server (npm start) before running this script.')
  154. process.exit(-1) // exit script with error. otherwise process will continue running
  155. }
  156. console.log('puppeteer.page.goto done. (now fetching image data)')
  157. var navigationWatcher = page.waitForNavigation()
  158. await Promise.race([responseWatcher, navigationWatcher])
  159. console.log('navigation race done')
  160. const dataUrls = await getDataUrl(page, sampleFilename)
  161. if (dataUrls.length === 0) {
  162. console.log(`error: could not get imageData for sample: ${sampleFilename}`)
  163. console.log(' (dataUrls was empty list)')
  164. continue
  165. }
  166. for (let urlIndex = 0; urlIndex < dataUrls.length; urlIndex++) {
  167. const pageNumberingString = `_${urlIndex + 1}`
  168. // pageNumberingString = dataUrls.length > 0 ? pageNumberingString : '' // don't put '_1' at the end if only one page. though that may cause more work
  169. var pageFilename = `${imageDir}/${sampleFilename}${pageNumberingString}.png`
  170. const dataUrl = dataUrls[urlIndex]
  171. if (!dataUrl || !dataUrl.split) {
  172. console.log(`error: could not get dataUrl (imageData) for page ${urlIndex + 1} of sample: ${sampleFilename}`)
  173. continue
  174. }
  175. const imageData = dataUrl.split(';base64,').pop()
  176. const imageBuffer = Buffer.from(imageData, 'base64')
  177. console.log('got image data, saving to: ' + pageFilename)
  178. fs.writeFileSync(pageFilename, imageBuffer, { encoding: 'base64' })
  179. }
  180. /* bneumann's SVG method */
  181. // const clone = this.ctx.svg.cloneNode(true) // SVGElement
  182. // // create a doctype that is SVG
  183. // const svgDocType = document.implementation.createDocumentType(
  184. // 'svg',
  185. // '-//W3C//DTD SVG 1.1//EN',
  186. // 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'
  187. // )
  188. // // Create a new svg document
  189. // const svgDoc = document.implementation.createDocument('http://www.w3.org/2000/svg', 'svg', svgDocType)
  190. // // replace the documentElement with our clone
  191. // svgDoc.replaceChild(clone, svgDoc.documentElement)
  192. // // get the data
  193. // const svgData = (new XMLSerializer()).serializeToString(svgDoc)
  194. // var blob = new Blob([svgData.replace(/></g, '>\n\r<')])
  195. // fs.writeFileSync(filename, blob)
  196. // //fs.writeFileSync(filename, svgData)
  197. // return
  198. /* end bneumann's svg method */
  199. }
  200. // const html = await page.content();
  201. // console.log('page content: ' + html);
  202. browser.close()
  203. console.log('\n[OSMD.generate] Done. Puppeteer browser closed. Exiting.')
  204. }
  205. init()
  206. // function start() {
  207. // // await (async () => {
  208. // // init();
  209. // // });
  210. // (async function(){
  211. // await init();
  212. // // more code here or the await is useless
  213. // })();
  214. // }
  215. // function resizeCanvas (elementId, width, height) {
  216. // $('#' + elementId).width(width)
  217. // $('#' + elementId).attr('width', width)
  218. // $('#' + elementId).attr('height', height)
  219. // }