generateImages_browserless.js 10 KB

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