texcmp.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. /* eslint-env node, es6 */
  2. /* eslint-disable no-console */
  3. "use strict";
  4. const childProcess = require("child_process");
  5. const fs = require("fs");
  6. const path = require("path");
  7. const Q = require("q"); // To debug, pass Q_DEBUG=1 in the environment
  8. const pngparse = require("pngparse");
  9. const fft = require("ndarray-fft");
  10. const ndarray = require("ndarray");
  11. const data = require("../../test/screenshotter/ss_data");
  12. // Adapt node functions to Q promises
  13. const readFile = Q.denodeify(fs.readFile);
  14. const writeFile = Q.denodeify(fs.writeFile);
  15. const mkdir = Q.denodeify(fs.mkdir);
  16. let todo;
  17. if (process.argv.length > 2) {
  18. todo = process.argv.slice(2);
  19. } else {
  20. todo = Object.keys(data).filter(function(key) {
  21. return !data[key].nolatex;
  22. });
  23. }
  24. // Dimensions used when we do the FFT-based alignment computation
  25. const alignWidth = 2048; // should be at least twice the width resp. height
  26. const alignHeight = 2048; // of the screenshots, and a power of two.
  27. // Compute required resolution to match test.html. 16px default font,
  28. // scaled to 4em in test.html, and to 1.21em in katex.css. Corresponding
  29. // LaTeX font size is 10pt. There are 72.27pt per inch.
  30. const pxPerEm = 16 * 4 * 1.21;
  31. const pxPerPt = pxPerEm / 10;
  32. const dpi = pxPerPt * 72.27;
  33. const tmpDir = "/tmp/texcmp";
  34. const ssDir = path.normalize(
  35. path.join(__dirname, "..", "..", "test", "screenshotter"));
  36. const imagesDir = path.join(ssDir, "images");
  37. const teximgDir = path.join(ssDir, "tex");
  38. const diffDir = path.join(ssDir, "diff");
  39. let template;
  40. Q.all([
  41. readFile(path.join(ssDir, "test.tex"), "utf-8"),
  42. ensureDir(tmpDir),
  43. ensureDir(teximgDir),
  44. ensureDir(diffDir),
  45. ]).spread(function(data) {
  46. template = data;
  47. // dirs have been created, template has been read, now rasterize.
  48. return Q.all(todo.map(processTestCase));
  49. }).done();
  50. // Process a single test case: rasterize, then create diff
  51. function processTestCase(key) {
  52. const itm = data[key];
  53. let tex = "$" + itm.tex + "$";
  54. if (itm.display) {
  55. tex = "\\[" + itm.tex + "\\]";
  56. }
  57. if (itm.pre) {
  58. tex = itm.pre.replace("<br>", "\\\\") + tex;
  59. }
  60. if (itm.post) {
  61. tex = tex + itm.post.replace("<br>", "\\\\");
  62. }
  63. if (itm.macros) {
  64. tex = Object.keys(itm.macros).map(name => {
  65. const expansion = itm.macros[name];
  66. let numArgs = 0;
  67. if (expansion.indexOf("#") !== -1) {
  68. const stripped = expansion.replace(/##/g, "");
  69. while (stripped.indexOf("#" + (numArgs + 1)) !== -1) {
  70. ++numArgs;
  71. }
  72. }
  73. let args = "";
  74. for (let i = 1; i <= numArgs; ++i) {
  75. args += "#" + i;
  76. }
  77. return "\\def" + name + args + "{" + expansion + "}\n";
  78. }).join("") + tex;
  79. }
  80. tex = template.replace(/\$.*\$/, tex.replace(/\$/g, "$$$$"));
  81. const texFile = path.join(tmpDir, key + ".tex");
  82. const pdfFile = path.join(tmpDir, key + ".pdf");
  83. const pngFile = path.join(teximgDir, key + "-pdflatex.png");
  84. const browserFile = path.join(imagesDir, key + "-firefox.png");
  85. const diffFile = path.join(diffDir, key + ".png");
  86. // Step 1: write key.tex file
  87. const fftLatex = writeFile(texFile, tex).then(function() {
  88. // Step 2: call "pdflatex key" to create key.pdf
  89. return execFile("pdflatex", [
  90. "-interaction", "nonstopmode", key,
  91. ], {cwd: tmpDir});
  92. }).then(function() {
  93. console.log("Typeset " + key);
  94. // Step 3: call "convert ... key.pdf key.png" to create key.png
  95. return execFile("convert", [
  96. "-density", dpi, "-units", "PixelsPerInch", "-flatten",
  97. "-depth", "8", pdfFile, pngFile,
  98. ]);
  99. }).then(function() {
  100. console.log("Rasterized " + key);
  101. // Step 4: apply FFT to that
  102. return readPNG(pngFile).then(fftImage);
  103. });
  104. // Step 5: apply FFT to reference image as well
  105. const fftBrowser = readPNG(browserFile).then(fftImage);
  106. return Q.all([fftBrowser, fftLatex]).spread(function(browser, latex) {
  107. // Now we have the FFT result from both
  108. // Step 6: find alignment which maximizes overlap.
  109. // This uses a FFT-based correlation computation.
  110. let x;
  111. let y;
  112. const real = createMatrix();
  113. const imag = createMatrix();
  114. // Step 6a: (real + i*imag) = latex * conjugate(browser)
  115. for (y = 0; y < alignHeight; ++y) {
  116. for (x = 0; x < alignWidth; ++x) {
  117. const br = browser.real.get(y, x);
  118. const bi = browser.imag.get(y, x);
  119. const lr = latex.real.get(y, x);
  120. const li = latex.imag.get(y, x);
  121. real.set(y, x, br * lr + bi * li);
  122. imag.set(y, x, br * li - bi * lr);
  123. }
  124. }
  125. // Step 6b: (real + i*imag) = inverseFFT(real + i*imag)
  126. fft(-1, real, imag);
  127. // Step 6c: find position where the (squared) absolute value is maximal
  128. let offsetX = 0;
  129. let offsetY = 0;
  130. let maxSquaredNorm = -1; // any result is greater than initial value
  131. for (y = 0; y < alignHeight; ++y) {
  132. for (x = 0; x < alignWidth; ++x) {
  133. const or = real.get(y, x);
  134. const oi = imag.get(y, x);
  135. const squaredNorm = or * or + oi * oi;
  136. if (maxSquaredNorm < squaredNorm) {
  137. maxSquaredNorm = squaredNorm;
  138. offsetX = x;
  139. offsetY = y;
  140. }
  141. }
  142. }
  143. // Step 6d: Treat negative offsets in a non-cyclic way
  144. if (offsetY > (alignHeight / 2)) {
  145. offsetY -= alignHeight;
  146. }
  147. if (offsetX > (alignWidth / 2)) {
  148. offsetX -= alignWidth;
  149. }
  150. console.log("Positioned " + key + ": " + offsetX + ", " + offsetY);
  151. // Step 7: use these offsets to compute difference illustration
  152. const bx = Math.max(offsetX, 0); // browser left padding
  153. const by = Math.max(offsetY, 0); // browser top padding
  154. const lx = Math.max(-offsetX, 0); // latex left padding
  155. const ly = Math.max(-offsetY, 0); // latex top padding
  156. const uw = Math.max(browser.width + bx, latex.width + lx); // union w.
  157. const uh = Math.max(browser.height + by, latex.height + ly); // u. h.
  158. return execFile("convert", [
  159. // First image: latex rendering, converted to grayscale and padded
  160. "(", pngFile, "-colorspace", "Gray",
  161. "-extent", uw + "x" + uh + "-" + lx + "-" + ly,
  162. ")",
  163. // Second image: browser screenshot, to grayscale and padded
  164. "(", browserFile, "-colorspace", "Gray",
  165. "-extent", uw + "x" + uh + "-" + bx + "-" + by,
  166. ")",
  167. // Third image: the per-pixel minimum of the first two images
  168. "(", "-clone", "0-1", "-compose", "darken", "-composite", ")",
  169. // First image is red, second green, third blue channel of result
  170. "-channel", "RGB", "-combine",
  171. "-trim", // remove everything with the same color as the corners
  172. diffFile, // output file name
  173. ]);
  174. }).then(function() {
  175. console.log("Compared " + key);
  176. });
  177. }
  178. // Create a directory, but ignore error if the directory already exists.
  179. function ensureDir(dir) {
  180. return mkdir(dir).fail(function(err) {
  181. if (err.code !== "EEXIST") {
  182. throw err;
  183. }
  184. });
  185. }
  186. // Execute a given command, and return a promise to its output.
  187. // Don't denodeify here, since fail branch needs access to stderr.
  188. function execFile(cmd, args, opts) {
  189. const deferred = Q.defer();
  190. childProcess.execFile(cmd, args, opts, function(err, stdout, stderr) {
  191. if (err) {
  192. console.error("Error executing " + cmd + " " + args.join(" "));
  193. console.error(stdout + stderr);
  194. err.stdout = stdout;
  195. err.stderr = stderr;
  196. deferred.reject(err);
  197. } else {
  198. deferred.resolve(stdout);
  199. }
  200. });
  201. return deferred.promise;
  202. }
  203. // Read given file and parse it as a PNG file.
  204. function readPNG(file) {
  205. const deferred = Q.defer();
  206. const onerror = deferred.reject.bind(deferred);
  207. const stream = fs.createReadStream(file);
  208. stream.on("error", onerror);
  209. pngparse.parseStream(stream, function(err, image) {
  210. if (err) {
  211. console.log("Failed to load " + file);
  212. onerror(err);
  213. return;
  214. }
  215. deferred.resolve(image);
  216. });
  217. return deferred.promise;
  218. }
  219. // Take a parsed image data structure and apply FFT transformation to it
  220. function fftImage(image) {
  221. const real = createMatrix();
  222. const imag = createMatrix();
  223. let idx = 0;
  224. const nchan = image.channels;
  225. const alphachan = 1 - (nchan % 2);
  226. const colorchan = nchan - alphachan;
  227. for (let y = 0; y < image.height; ++y) {
  228. for (let x = 0; x < image.width; ++x) {
  229. let v = 0;
  230. for (let c = 0; c < colorchan; ++c) {
  231. v += 255 - image.data[idx++];
  232. }
  233. for (let c = 0; c < alphachan; ++c) {
  234. v += image.data[idx++];
  235. }
  236. real.set(y, x, v);
  237. }
  238. }
  239. fft(1, real, imag);
  240. return {
  241. real: real,
  242. imag: imag,
  243. width: image.width,
  244. height: image.height,
  245. };
  246. }
  247. // Create a new matrix of preconfigured dimensions, initialized to zero
  248. function createMatrix() {
  249. const array = new Float64Array(alignWidth * alignHeight);
  250. /* eslint-disable-next-line new-cap */
  251. return new ndarray(array, [alignWidth, alignHeight]);
  252. }