generateImages_browserless.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 can be used to generate PNGs from OSMD without a browser.
  6. It's also used with the visual regression test system in
  7. `tools/visual_regression.sh`.
  8. Note: this script needs to "fake" quite a few browser elements, like window, document, and a Canvas HTMLElement.
  9. For that it needs the canvas package installed.
  10. There are also some hacks needed to set the container size (offsetWidth) correctly.
  11. */
  12. function sleep (ms) {
  13. return new Promise((resolve) => {
  14. setTimeout(resolve, ms)
  15. })
  16. }
  17. async function init () {
  18. console.log('[OSMD.generate] init')
  19. let [osmdBuildDir, sampleDir, imageDir, pageWidth, pageHeight, filterRegex, debugFlag, debugSleepTimeString] = process.argv.slice(2, 10)
  20. if (!osmdBuildDir || !sampleDir || !imageDir) {
  21. console.log('usage: ' +
  22. 'node test/Util/generateImages_browserless.js osmdBuildDir sampleDirectory imageDirectory [width|0] [height|0] [filterRegex|all|allSmall] [--debug] [debugSleepTime]')
  23. console.log(' (use "all" to skip filterRegex parameter)')
  24. console.log('example: node test/Util/generateImages_browserless.js ../../build ./test/data/ ./export 210 297 allSmall --debug 5000')
  25. console.log('Error: need sampleDir and imageDir. Exiting.')
  26. process.exit(1)
  27. }
  28. console.log('sampleDir: ' + sampleDir)
  29. console.log('imageDir: ' + imageDir)
  30. let pageFormat = 'Endless'
  31. pageWidth = Number.parseInt(pageWidth)
  32. pageHeight = Number.parseInt(pageHeight)
  33. const endlessPage = !(pageHeight > 0 && pageWidth > 0)
  34. if (!endlessPage) {
  35. pageFormat = `${pageWidth}x${pageHeight}`
  36. }
  37. const DEBUG = debugFlag === '--debug'
  38. // const debugSleepTime = Number.parseInt(process.env.GENERATE_DEBUG_SLEEP_TIME) || 0; // 5000 works for me [sschmidTU]
  39. if (DEBUG) {
  40. console.log(' note that --debug slows down the script by about 0.3s per file (through console.logs).')
  41. console.log('debug sleep time: ' + debugSleepTimeString)
  42. const debugSleepTimeMs = Number.parseInt(debugSleepTimeString)
  43. if (debugSleepTimeMs > 0) {
  44. await sleep(Number.parseInt(debugSleepTimeMs))
  45. // [VSCode] apparently this is necessary for the debugger to attach itself in time before the program closes.
  46. // sometimes this is not enough, so you may have to try multiple times or increase the sleep timer. Unfortunately debugging nodejs isn't easy.
  47. }
  48. }
  49. // ---- hacks to fake Browser elements OSMD and Vexflow need, like window, document, and a canvas HTMLElement ----
  50. const { JSDOM } = require('jsdom')
  51. const dom = new JSDOM('<!DOCTYPE html></html>')
  52. // eslint-disable-next-line no-global-assign
  53. window = dom.window
  54. // eslint-disable-next-line no-global-assign
  55. document = dom.window.document
  56. // eslint-disable-next-line no-global-assign
  57. global.window = dom.window
  58. // eslint-disable-next-line no-global-assign
  59. global.document = window.document
  60. global.HTMLElement = window.HTMLElement
  61. global.HTMLAnchorElement = window.HTMLAnchorElement
  62. global.XMLHttpRequest = window.XMLHttpRequest
  63. global.DOMParser = window.DOMParser
  64. global.Node = window.Node
  65. global.Canvas = window.Canvas
  66. // fix Blob not found
  67. const Blob = require('cross-blob')
  68. // eslint-disable-next-line no-new
  69. new Blob([])
  70. // => Blob {size: 0, type: ''}
  71. // Global patch (to support external modules like is-blob).
  72. global.Blob = Blob
  73. const div = document.createElement('div')
  74. div.id = 'browserlessDiv'
  75. document.body.appendChild(div)
  76. // const canvas = document.createElement('canvas')
  77. // div.canvas = document.createElement('canvas')
  78. const zoom = 1.0
  79. // somehow, witdh * 5 will preserve the aspect ratio (0.7070 repeating, *1 will be way too short, *10 too long)
  80. // there's width * zoom * 10 in the OSMD code because Vexflow's pixels are OSMD's size units * 10, so i thought it should be * 10.
  81. // not sure where the / 2 factor comes from.
  82. let width = pageWidth * zoom * 5
  83. if (endlessPage) {
  84. width = 1440
  85. }
  86. let height = pageHeight
  87. if (endlessPage) {
  88. height = 32767
  89. }
  90. div.width = width
  91. div.height = height
  92. div.offsetWidth = width // doesn't work, offsetWidth is always 0 from this. see below
  93. div.clientWidth = width
  94. div.clientHeight = height
  95. div.scrollHeight = height
  96. div.scrollWidth = width
  97. div.setAttribute('width', width)
  98. div.setAttribute('height', height)
  99. div.setAttribute('offsetWidth', width)
  100. debug('div.offsetWidth: ' + div.offsetWidth, DEBUG)
  101. debug('div.height: ' + div.height, DEBUG)
  102. // hack: set offsetWidth reliably
  103. Object.defineProperties(window.HTMLElement.prototype, {
  104. offsetLeft: {
  105. get: function () { return parseFloat(window.getComputedStyle(this).marginTop) || 0 }
  106. },
  107. offsetTop: {
  108. get: function () { return parseFloat(window.getComputedStyle(this).marginTop) || 0 }
  109. },
  110. offsetHeight: {
  111. get: function () { return height }
  112. },
  113. offsetWidth: {
  114. get: function () { return width }
  115. }
  116. })
  117. debug('div.offsetWidth: ' + div.offsetWidth, DEBUG)
  118. debug('div.height: ' + div.height, DEBUG)
  119. if (!DEBUG) {
  120. // deactivate console logs (mostly)
  121. console.log = (msg) => {}
  122. }
  123. // ---- end browser hacks (hopefully) ----
  124. const OSMD = require(`${osmdBuildDir}/opensheetmusicdisplay.min.js`)
  125. const fs = require('fs')
  126. // Create the image directory if it doesn't exist.
  127. fs.mkdirSync(imageDir, { recursive: true })
  128. const sampleDirFilenames = fs.readdirSync(sampleDir)
  129. let samplesToProcess = [] // samples we want to process/generate pngs of, excluding the filtered out files/filenames
  130. for (const sampleFilename of sampleDirFilenames) {
  131. if (filterRegex === 'allSmall') {
  132. if (sampleFilename.match('^(Actor)|(Gounod)')) { // TODO maybe filter by file size instead
  133. console.log('DEBUG: filtering big file: ' + sampleFilename)
  134. continue
  135. }
  136. }
  137. // eslint-disable-next-line no-useless-escape
  138. if (sampleFilename.match('^.*(\.xml)|(\.musicxml)|(\.mxl)$')) {
  139. // console.log('found musicxml/mxl: ' + sampleFilename)
  140. samplesToProcess.push(sampleFilename)
  141. } else {
  142. console.log('discarded file/directory: ' + sampleFilename)
  143. }
  144. }
  145. // filter samples to process by regex if given
  146. if (filterRegex && filterRegex !== '' && filterRegex !== 'all' && filterRegex !== 'allSmall') {
  147. console.log('filtering samples for regex: ' + filterRegex)
  148. samplesToProcess = samplesToProcess.filter((filename) => filename.match(filterRegex))
  149. console.log(`found ${samplesToProcess.length} matches: `)
  150. for (let i = 0; i < samplesToProcess.length; i++) {
  151. console.log(samplesToProcess[i])
  152. }
  153. }
  154. const osmdInstance = new OSMD.OpenSheetMusicDisplay(div, {
  155. autoResize: false,
  156. backend: 'canvas',
  157. pageBackgroundColor: '#FFFFFF',
  158. pageFormat: pageFormat
  159. })
  160. // await sleep(5000)
  161. if (DEBUG) {
  162. osmdInstance.setLogLevel('debug')
  163. // console.log(`osmd PageFormat: ${osmdInstance.EngravingRules.PageFormat.width}x${osmdInstance.EngravingRules.PageFormat.height}`)
  164. console.log(`osmd PageFormat idString: ${osmdInstance.EngravingRules.PageFormat.idString}`)
  165. console.log('PageHeight: ' + osmdInstance.EngravingRules.PageHeight)
  166. } else {
  167. osmdInstance.setLogLevel('info') // doesn't seem to work, log.debug still logs
  168. }
  169. debug('generateImages', DEBUG)
  170. for (let i = 0; i < samplesToProcess.length; i++) {
  171. var sampleFilename = samplesToProcess[i]
  172. debug('sampleFilename: ' + sampleFilename, DEBUG)
  173. let loadParameter = fs.readFileSync(sampleDir + '/' + sampleFilename)
  174. if (sampleFilename.endsWith('.mxl')) {
  175. loadParameter = await OSMD.MXLHelper.MXLtoXMLstring(loadParameter)
  176. } else {
  177. loadParameter = loadParameter.toString()
  178. }
  179. // console.log('loadParameter: ' + loadParameter)
  180. // console.log('typeof loadParameter: ' + typeof loadParameter)
  181. await osmdInstance.load(loadParameter).then(function () {
  182. debug('xml loaded', DEBUG)
  183. try {
  184. osmdInstance.render()
  185. } catch (ex) {
  186. console.log('renderError: ' + ex)
  187. }
  188. debug('rendered', DEBUG)
  189. const dataUrls = []
  190. let canvasImage
  191. for (let pageNumber = 1; pageNumber < 999; pageNumber++) {
  192. canvasImage = document.getElementById('osmdCanvasVexFlowBackendCanvas' + pageNumber)
  193. if (!canvasImage) {
  194. break
  195. }
  196. if (!canvasImage.toDataURL) {
  197. console.log(`error: could not get canvas image for page ${pageNumber} for file: ${sampleFilename}`)
  198. break
  199. }
  200. dataUrls.push(canvasImage.toDataURL())
  201. }
  202. for (let urlIndex = 0; urlIndex < dataUrls.length; urlIndex++) {
  203. const pageNumberingString = `_${urlIndex + 1}`
  204. // pageNumberingString = dataUrls.length > 0 ? pageNumberingString : '' // don't put '_1' at the end if only one page. though that may cause more work
  205. var pageFilename = `${imageDir}/${sampleFilename}${pageNumberingString}.png`
  206. const dataUrl = dataUrls[urlIndex]
  207. if (!dataUrl || !dataUrl.split) {
  208. console.log(`error: could not get dataUrl (imageData) for page ${urlIndex + 1} of sample: ${sampleFilename}`)
  209. continue
  210. }
  211. const imageData = dataUrl.split(';base64,').pop()
  212. const imageBuffer = Buffer.from(imageData, 'base64')
  213. console.log('got image data, saving to: ' + pageFilename)
  214. fs.writeFileSync(pageFilename, imageBuffer, { encoding: 'base64' })
  215. }
  216. }) // end render then
  217. // },
  218. // function (e) {
  219. // console.log('error while rendering: ' + e)
  220. // }) // end load then
  221. // }) // end read file
  222. }
  223. console.log('[OSMD.generate_browserless] exit')
  224. }
  225. function debug (msg, debugEnabled) {
  226. if (debugEnabled) {
  227. console.log(msg)
  228. }
  229. }
  230. init()