browser-screenshot-surface-smoke.mjs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import { app, BrowserWindow, nativeImage, screen, webContents } from "electron";
  2. import { writeFile } from "node:fs/promises";
  3. const VIEWPORT = { width: 1280, height: 720 };
  4. const INITIAL_SURFACE = { width: 800, height: 450 };
  5. const SENTINEL_SIZE = 96;
  6. const RESULT_PATH = process.env.ZCODE_SCREENSHOT_SMOKE_RESULT_PATH;
  7. const SCALE_FACTOR = process.env.ZCODE_SCREENSHOT_SMOKE_SCALE_FACTOR;
  8. const SUCCESS_RESULT =
  9. '{"width":1280,"height":720,"periodicRepeat":false,"corners":"distinct"}';
  10. let scaleFactorError;
  11. if (SCALE_FACTOR) {
  12. const parsedScaleFactor = Number(SCALE_FACTOR);
  13. if (!Number.isFinite(parsedScaleFactor) || parsedScaleFactor <= 0) {
  14. scaleFactorError = new Error(
  15. `ZCODE_SCREENSHOT_SMOKE_SCALE_FACTOR must be a positive number, received ${SCALE_FACTOR}`,
  16. );
  17. } else {
  18. app.commandLine.appendSwitch("force-device-scale-factor", SCALE_FACTOR);
  19. }
  20. }
  21. function periodicMatchRatio(bitmap, width, height, stride, dx, dy) {
  22. let compared = 0;
  23. let equal = 0;
  24. for (let y = 0; y + dy < height; y += stride) {
  25. for (let x = 0; x + dx < width; x += stride) {
  26. const a = (y * width + x) * 4;
  27. const b = ((y + dy) * width + x + dx) * 4;
  28. compared += 1;
  29. if (
  30. bitmap[a] === bitmap[b] &&
  31. bitmap[a + 1] === bitmap[b + 1] &&
  32. bitmap[a + 2] === bitmap[b + 2]
  33. ) {
  34. equal += 1;
  35. }
  36. }
  37. }
  38. return compared === 0 ? 0 : equal / compared;
  39. }
  40. function guestHtml() {
  41. return `<!doctype html>
  42. <html>
  43. <head>
  44. <style>
  45. html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; }
  46. body {
  47. position: relative;
  48. background:
  49. linear-gradient(90deg, rgb(11 37 89 / 92%), rgb(217 71 31 / 92%)),
  50. linear-gradient(180deg, rgb(31 127 211), rgb(239 193 41));
  51. }
  52. .sentinel { position: fixed; width: ${SENTINEL_SIZE}px; height: ${SENTINEL_SIZE}px; }
  53. .top-left { top: 0; left: 0; background: rgb(255 0 0); }
  54. .top-right { top: 0; right: 0; background: rgb(0 255 0); }
  55. .bottom-left { bottom: 0; left: 0; background: rgb(0 0 255); }
  56. .bottom-right { right: 0; bottom: 0; background: rgb(255 255 0); }
  57. </style>
  58. </head>
  59. <body>
  60. <div class="sentinel top-left"></div>
  61. <div class="sentinel top-right"></div>
  62. <div class="sentinel bottom-left"></div>
  63. <div class="sentinel bottom-right"></div>
  64. </body>
  65. </html>`;
  66. }
  67. function htmlDataUrl(html) {
  68. return `data:text/html;base64,${Buffer.from(html).toString("base64")}`;
  69. }
  70. function hostHtml(guestUrl) {
  71. return `<!doctype html>
  72. <html>
  73. <head>
  74. <style>
  75. html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; background: rgb(20 20 20); }
  76. #capture-layer {
  77. position: absolute;
  78. top: 0;
  79. left: 0;
  80. z-index: 0;
  81. width: ${INITIAL_SURFACE.width}px;
  82. height: ${INITIAL_SURFACE.height}px;
  83. overflow: hidden;
  84. pointer-events: none;
  85. }
  86. #guest { display: block; width: ${INITIAL_SURFACE.width}px; height: ${INITIAL_SURFACE.height}px; }
  87. #active-cover { position: absolute; inset: 0; z-index: 1; background: rgb(48 48 48); }
  88. </style>
  89. </head>
  90. <body>
  91. <div id="capture-layer" aria-hidden="true" inert>
  92. <webview id="guest" src="${guestUrl}"></webview>
  93. </div>
  94. <div id="active-cover" aria-hidden="true" inert></div>
  95. <script>
  96. const guest = document.querySelector("#guest");
  97. let guestDomReadyId = 0;
  98. guest.addEventListener("dom-ready", () => { guestDomReadyId = guest.getWebContentsId(); }, { once: true });
  99. const nextFrame = () => new Promise(requestAnimationFrame);
  100. window.waitForGuestDomReady = () => new Promise((resolve) => {
  101. if (guestDomReadyId) {
  102. resolve(guestDomReadyId);
  103. return;
  104. }
  105. guest.addEventListener("dom-ready", () => resolve(guest.getWebContentsId()), { once: true });
  106. });
  107. window.waitForHistoricalSurface = () => nextFrame();
  108. window.readStableSurface = async () => {
  109. await nextFrame();
  110. const first = guest.getBoundingClientRect();
  111. await nextFrame();
  112. const second = guest.getBoundingClientRect();
  113. return {
  114. first: { width: Math.round(first.width), height: Math.round(first.height) },
  115. second: { width: Math.round(second.width), height: Math.round(second.height) },
  116. };
  117. };
  118. </script>
  119. </body>
  120. </html>`;
  121. }
  122. function rgbaAt(bitmap, width, x, y) {
  123. const index = (y * width + x) * 4;
  124. // nativeImage.toBitmap() 在 Windows 采用 Chromium 的 BGRA 顺序,这里统一为 RGBA。
  125. return [bitmap[index + 2], bitmap[index + 1], bitmap[index], bitmap[index + 3]];
  126. }
  127. function assertColor(name, actual, expected) {
  128. const tolerance = 2;
  129. if (actual.some((channel, index) => Math.abs(channel - expected[index]) > tolerance)) {
  130. throw new Error(`${name} sentinel RGBA mismatch: expected ${expected}, received ${actual}`);
  131. }
  132. }
  133. function validateScreenshot(png) {
  134. const image = nativeImage.createFromBuffer(png);
  135. const { width, height } = image.getSize();
  136. if (width !== VIEWPORT.width || height !== VIEWPORT.height) {
  137. throw new Error(
  138. `screenshot dimensions mismatch: expected ${VIEWPORT.width}x${VIEWPORT.height}, received ${width}x${height}`,
  139. );
  140. }
  141. const bitmap = image.toBitmap();
  142. const inset = Math.floor(SENTINEL_SIZE / 2);
  143. assertColor("top-left", rgbaAt(bitmap, width, inset, inset), [255, 0, 0, 255]);
  144. assertColor("top-right", rgbaAt(bitmap, width, width - inset - 1, inset), [0, 255, 0, 255]);
  145. assertColor("bottom-left", rgbaAt(bitmap, width, inset, height - inset - 1), [0, 0, 255, 255]);
  146. assertColor(
  147. "bottom-right",
  148. rgbaAt(bitmap, width, width - inset - 1, height - inset - 1),
  149. [255, 255, 0, 255],
  150. );
  151. const horizontalRatio = periodicMatchRatio(bitmap, width, height, 17, 800, 0);
  152. const verticalRatio = periodicMatchRatio(bitmap, width, height, 17, 0, 450);
  153. if (horizontalRatio >= 0.95 || verticalRatio >= 0.95) {
  154. throw new Error(
  155. `stale tiled surface detected: horizontal=${horizontalRatio.toFixed(4)}, vertical=${verticalRatio.toFixed(4)}`,
  156. );
  157. }
  158. }
  159. async function writeSuccess() {
  160. if (RESULT_PATH) await writeFile(RESULT_PATH, `${SUCCESS_RESULT}\n`, "utf8");
  161. console.log(SUCCESS_RESULT);
  162. }
  163. async function writeDiagnostic(error) {
  164. await new Promise((resolve) => process.stderr.write(`${error.stack ?? error}\n`, resolve));
  165. }
  166. async function run() {
  167. let window;
  168. let guest;
  169. let debuggerAttached = false;
  170. let exitCode = 0;
  171. try {
  172. if (scaleFactorError) throw scaleFactorError;
  173. await app.whenReady();
  174. const workArea = screen.getPrimaryDisplay().workArea;
  175. window = new BrowserWindow({
  176. width: VIEWPORT.width,
  177. height: VIEWPORT.height,
  178. useContentSize: true,
  179. x: Math.max(workArea.x, workArea.x + workArea.width - VIEWPORT.width),
  180. y: Math.max(workArea.y, workArea.y + workArea.height - VIEWPORT.height),
  181. show: true,
  182. focusable: false,
  183. skipTaskbar: true,
  184. webPreferences: { webviewTag: true },
  185. });
  186. window.showInactive();
  187. const guestUrl = htmlDataUrl(guestHtml());
  188. await window.loadURL(htmlDataUrl(hostHtml(guestUrl)));
  189. const guestId = await window.webContents.executeJavaScript("window.waitForGuestDomReady()", true);
  190. guest = webContents.fromId(guestId);
  191. if (!guest) throw new Error(`guest webContents ${guestId} was not found`);
  192. // 保持 800×450 Fit surface,只用 CDP 把 guest 的逻辑 viewport 改为 1280×720。
  193. await window.webContents.executeJavaScript("window.waitForHistoricalSurface()", true);
  194. const surface = await window.webContents.executeJavaScript("window.readStableSurface()", true);
  195. for (const rect of [surface.first, surface.second]) {
  196. if (rect.width !== INITIAL_SURFACE.width || rect.height !== INITIAL_SURFACE.height) {
  197. throw new Error(
  198. `capture layer did not stabilize at ${INITIAL_SURFACE.width}x${INITIAL_SURFACE.height}: ${JSON.stringify(surface)}`,
  199. );
  200. }
  201. }
  202. guest.debugger.attach("1.3");
  203. debuggerAttached = true;
  204. await guest.debugger.sendCommand("Emulation.setDeviceMetricsOverride", {
  205. width: VIEWPORT.width,
  206. height: VIEWPORT.height,
  207. deviceScaleFactor: 1,
  208. mobile: false,
  209. dontSetVisibleSize: true,
  210. });
  211. // Bug 原因:Windows 的 CDP Page.captureScreenshot 会把较小 Fit surface 平铺到逻辑
  212. // viewport;main 直接读取 guest 已合成 surface 不会重复,再归一化到 CSS 尺寸。
  213. const source = await guest.capturePage();
  214. const size = source.getSize();
  215. const resized =
  216. size.width === VIEWPORT.width && size.height === VIEWPORT.height
  217. ? source
  218. : source.resize({ width: VIEWPORT.width, height: VIEWPORT.height, quality: "best" });
  219. validateScreenshot(resized.toPNG());
  220. await writeSuccess();
  221. } catch (error) {
  222. exitCode = 1;
  223. await writeDiagnostic(error);
  224. } finally {
  225. if (debuggerAttached && guest?.debugger.isAttached()) {
  226. try {
  227. guest.debugger.detach();
  228. } catch (error) {
  229. exitCode = 1;
  230. await writeDiagnostic(error);
  231. }
  232. }
  233. if (window && !window.isDestroyed()) window.destroy();
  234. // window/detach 已完成后显式退出,确保错误退出码不会被 Electron 生命周期回调覆盖。
  235. app.exit(exitCode);
  236. }
  237. }
  238. void run();