123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250 |
- function sleep (ms) {
- return new Promise((resolve) => {
- setTimeout(resolve, ms)
- })
- }
- const osmdPort = 8000
- async function init () {
- console.log('[OSMD.generate] init')
- let [sampleDir, imageDir, pageWidth, pageHeight, filterRegex, debugFlag, debugSleepTimeString] = process.argv.slice(2, 9)
- if (!sampleDir || !imageDir) {
- console.log('usage: node test/Util/generateDiffImagesPuppeteerLocalhost.js sampleDirectory imageDirectory [width|0] [height|0] [filterRegex|all] [--debug] [debugSleepTime]')
- console.log(' (use "all" to skip filterRegex parameter)')
- console.log('example: node ./test/Util/generateDiffImagesPuppeteerLocalhost.js ./test/data/ ./export 210 297 all --debug 5000')
- console.log('Error: need sampleDir and imageDir. Exiting.')
- process.exit(1)
- }
- console.log('sampleDir: ' + sampleDir)
- console.log('imageDir: ' + imageDir)
- let pageFormatParameter = ''
- pageHeight = Number.parseInt(pageHeight)
- pageWidth = Number.parseInt(pageWidth)
- if(!pageWidth || pageWidth === NaN){
- pageWidth = 800
- }
- if(!pageHeight || pageHeight === NaN){
- pageHeight = 600
- }
- const DEBUG = debugFlag === '--debug'
-
- if (DEBUG) {
- console.log('debug sleep time: ' + debugSleepTimeString)
- const debugSleepTimeMs = Number.parseInt(debugSleepTimeString)
- if (debugSleepTimeMs > 0) {
- await sleep(Number.parseInt(debugSleepTimeMs))
-
-
- }
- }
- const fs = require('fs')
-
- fs.mkdirSync(imageDir, { recursive: true })
- const sampleDirFilenames = fs.readdirSync(sampleDir)
- let samplesToProcess = []
- for (const sampleFilename of sampleDirFilenames) {
- if (DEBUG) {
- if (sampleFilename.match('^(Actor)|(Gounod)')) {
- console.log('DEBUG: filtering big file: ' + sampleFilename)
- continue
- }
- }
-
- if (sampleFilename.match('^.*(\.xml)|(\.musicxml)|(\.mxl)$')) {
-
- samplesToProcess.push(sampleFilename)
- } else {
- console.log('discarded file/directory: ' + sampleFilename)
- }
- }
-
- if (filterRegex && filterRegex !== '' && filterRegex !== 'all') {
- console.log('filtering samples for regex: ' + filterRegex)
- samplesToProcess = samplesToProcess.filter((filename) => filename.match(filterRegex))
- console.log(`found ${samplesToProcess.length} matches: `)
- for (let i = 0; i < samplesToProcess.length; i++) {
- console.log(samplesToProcess[i])
- }
- }
- const puppeteer = require('puppeteer')
- const browser = await puppeteer.launch({ headless: true })
- const page = await browser.newPage()
- page.setViewport({
- width: pageWidth,
- height: pageHeight,
- deviceScaleFactor: 1
- });
- const defaultTimeoutInMs = 100000
- page.setDefaultNavigationTimeout(defaultTimeoutInMs)
-
- var responseEventOccurred = false
- var responseHandler = function (event) { responseEventOccurred = true }
- var responseWatcher = new Promise(function (resolve, reject) {
- setTimeout(function () {
- if (!responseEventOccurred) {
- resolve(true)
- } else {
- setTimeout(function () { resolve(true) }, defaultTimeoutInMs)
- }
- page.removeListener('response', responseHandler)
- }, 1000)
- })
- page.on('response', responseHandler)
- if (DEBUG) {
-
- page.on('console', msg => console.log(msg.text()))
- }
- page.on('error', err => console.log(err))
- page.on('pageerror', err => console.log(err))
-
- const getDataUrl = async (page, sampleFilename) => {
- return page.evaluate(async () => {
- return new Promise(resolve => {
- const imageDataArray = []
- let canvasImage
- for (let pageNumber = 1; pageNumber < 999; pageNumber++) {
- canvasImage = document.getElementById('osmdCanvasVexFlowBackendCanvas' + pageNumber)
- if (!canvasImage) {
- break
- }
- if (!canvasImage.toDataURL) {
- console.log(`error: could not get canvas image for page ${pageNumber} for file: ${sampleFilename}`)
- break
- }
- imageDataArray.push(canvasImage.toDataURL())
- }
-
-
-
-
-
- resolve(imageDataArray)
- })
- })
- }
-
- for (let i = 0; i < samplesToProcess.length; i++) {
- const sampleFilename = encodeURIComponent(samplesToProcess[i])
- const sampleParameter = `&openUrl=${sampleFilename}&endUrl`
- const pageUrl = `http://localhost:${osmdPort}?showHeader=0&debugControls=0&backendType=canvas&pageBackgroundColor=FFFFFF` +
- sampleParameter +
- pageFormatParameter
- console.log('puppeteer: page.goto url: ' + pageUrl)
- try {
- await page.goto(pageUrl, { waitUntil: 'networkidle2' })
- } catch (error) {
- console.log(error)
- console.log('[OSMD.generateImages] Error generating images: could not reach local OSMD server. ' +
- 'Make sure to start OSMD local webpack server (npm start) before running this script.')
- process.exit(-1)
- }
- console.log('puppeteer.page.goto done. (now fetching image data)')
- var navigationWatcher = page.waitForNavigation()
- await Promise.race([responseWatcher, navigationWatcher])
- console.log('navigation race done')
- const dataUrls = await getDataUrl(page, sampleFilename)
- if (dataUrls.length === 0) {
- console.log(`error: could not get imageData for sample: ${sampleFilename}`)
- console.log(' (dataUrls was empty list)')
- continue
- }
- for (let urlIndex = 0; urlIndex < dataUrls.length; urlIndex++) {
- const pageNumberingString = `_${urlIndex + 1}`
-
- var pageFilename = `${imageDir}/${sampleFilename}${pageNumberingString}.png`
- const dataUrl = dataUrls[urlIndex]
- if (!dataUrl || !dataUrl.split) {
- console.log(`error: could not get dataUrl (imageData) for page ${urlIndex + 1} of sample: ${sampleFilename}`)
- continue
- }
- const imageData = dataUrl.split(';base64,').pop()
- const imageBuffer = Buffer.from(imageData, 'base64')
- console.log('got image data, saving to: ' + pageFilename)
- fs.writeFileSync(pageFilename, imageBuffer, { encoding: 'base64' })
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
-
-
- browser.close()
- console.log('\n[OSMD.generate] Done. Puppeteer browser closed. Exiting.')
- }
- init()
|