summaryrefslogtreecommitdiffstats
path: root/browser/components/shell/HeadlessShell.sys.mjs
blob: c87a7a6d56d16c5dba854def7cbf5f9bbd8b6336 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

import { E10SUtils } from "resource://gre/modules/E10SUtils.sys.mjs";
import { HiddenFrame } from "resource://gre/modules/HiddenFrame.sys.mjs";

// Refrences to the progress listeners to keep them from being gc'ed
// before they are called.
const progressListeners = new Set();

export class ScreenshotParent extends JSWindowActorParent {
  getDimensions(params) {
    return this.sendQuery("GetDimensions", params);
  }
}

ChromeUtils.registerWindowActor("Screenshot", {
  parent: {
    esModuleURI: "resource:///modules/HeadlessShell.sys.mjs",
  },
  child: {
    esModuleURI: "resource:///modules/ScreenshotChild.sys.mjs",
  },
});

function loadContentWindow(browser, url) {
  let uri;
  try {
    uri = Services.io.newURI(url);
  } catch (e) {
    let msg = `Invalid URL passed to loadContentWindow(): ${url}`;
    console.error(msg);
    return Promise.reject(new Error(msg));
  }

  const principal = Services.scriptSecurityManager.getSystemPrincipal();
  return new Promise((resolve, reject) => {
    let oa = E10SUtils.predictOriginAttributes({
      browser,
    });
    let loadURIOptions = {
      triggeringPrincipal: principal,
      remoteType: E10SUtils.getRemoteTypeForURI(
        url,
        true,
        false,
        E10SUtils.DEFAULT_REMOTE_TYPE,
        null,
        oa
      ),
    };
    browser.loadURI(uri, loadURIOptions);
    let { webProgress } = browser;

    let progressListener = {
      onLocationChange(progress, request, location, flags) {
        // Ignore inner-frame events
        if (!progress.isTopLevel) {
          return;
        }
        // Ignore events that don't change the document
        if (flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT) {
          return;
        }
        // Ignore the initial about:blank, unless about:blank is requested
        if (location.spec == "about:blank" && uri.spec != "about:blank") {
          return;
        }

        progressListeners.delete(progressListener);
        webProgress.removeProgressListener(progressListener);
        resolve();
      },
      QueryInterface: ChromeUtils.generateQI([
        "nsIWebProgressListener",
        "nsISupportsWeakReference",
      ]),
    };
    progressListeners.add(progressListener);
    webProgress.addProgressListener(
      progressListener,
      Ci.nsIWebProgress.NOTIFY_LOCATION
    );
  });
}

async function takeScreenshot(
  fullWidth,
  fullHeight,
  contentWidth,
  contentHeight,
  path,
  url
) {
  let frame;
  try {
    frame = new HiddenFrame();
    let windowlessBrowser = await frame.get();

    let doc = windowlessBrowser.document;
    let browser = doc.createXULElement("browser");
    browser.setAttribute("remote", "true");
    browser.setAttribute("type", "content");
    browser.setAttribute(
      "style",
      `width: ${contentWidth}px; min-width: ${contentWidth}px; height: ${contentHeight}px; min-height: ${contentHeight}px;`
    );
    browser.setAttribute("maychangeremoteness", "true");
    doc.documentElement.appendChild(browser);

    await loadContentWindow(browser, url);

    let actor =
      browser.browsingContext.currentWindowGlobal.getActor("Screenshot");
    let dimensions = await actor.getDimensions();

    let canvas = doc.createElementNS(
      "http://www.w3.org/1999/xhtml",
      "html:canvas"
    );
    let context = canvas.getContext("2d");
    let width = dimensions.innerWidth;
    let height = dimensions.innerHeight;
    if (fullWidth) {
      width += dimensions.scrollMaxX - dimensions.scrollMinX;
    }
    if (fullHeight) {
      height += dimensions.scrollMaxY - dimensions.scrollMinY;
    }
    canvas.width = width;
    canvas.height = height;
    let rect = new DOMRect(0, 0, width, height);

    let snapshot =
      await browser.browsingContext.currentWindowGlobal.drawSnapshot(
        rect,
        1,
        "rgb(255, 255, 255)"
      );
    context.drawImage(snapshot, 0, 0);

    snapshot.close();

    let blob = await new Promise(resolve => canvas.toBlob(resolve));

    let reader = await new Promise(resolve => {
      let fr = new FileReader();
      fr.onloadend = () => resolve(fr);
      fr.readAsArrayBuffer(blob);
    });

    await IOUtils.write(path, new Uint8Array(reader.result));
    dump("Screenshot saved to: " + path + "\n");
  } catch (e) {
    dump("Failure taking screenshot: " + e + "\n");
  } finally {
    if (frame) {
      frame.destroy();
    }
  }
}

export let HeadlessShell = {
  async handleCmdLineArgs(cmdLine, URLlist) {
    try {
      // Don't quit even though we don't create a window
      Services.startup.enterLastWindowClosingSurvivalArea();

      // Default options
      let fullWidth = true;
      let fullHeight = true;
      // Most common screen resolution of Firefox users
      let contentWidth = 1366;
      let contentHeight = 768;

      // Parse `window-size`
      try {
        var dimensionsStr = cmdLine.handleFlagWithParam("window-size", true);
      } catch (e) {
        dump("expected format: --window-size width[,height]\n");
        return;
      }
      if (dimensionsStr) {
        let success;
        let dimensions = dimensionsStr.split(",", 2);
        if (dimensions.length == 1) {
          success = dimensions[0] > 0;
          if (success) {
            fullWidth = false;
            fullHeight = true;
            contentWidth = dimensions[0];
          }
        } else {
          success = dimensions[0] > 0 && dimensions[1] > 0;
          if (success) {
            fullWidth = false;
            fullHeight = false;
            contentWidth = dimensions[0];
            contentHeight = dimensions[1];
          }
        }

        if (!success) {
          dump("expected format: --window-size width[,height]\n");
          return;
        }
      }

      let urlOrFileToSave = null;
      try {
        urlOrFileToSave = cmdLine.handleFlagWithParam("screenshot", true);
      } catch (e) {
        // We know that the flag exists so we only get here if there was no parameter.
        cmdLine.handleFlag("screenshot", true); // Remove `screenshot`
      }

      // Assume that the remaining arguments that do not start
      // with a hyphen are URLs
      for (let i = 0; i < cmdLine.length; ++i) {
        const argument = cmdLine.getArgument(i);
        if (argument.startsWith("-")) {
          dump(`Warning: unrecognized command line flag ${argument}\n`);
          // To emulate the pre-nsICommandLine behavior, we ignore
          // the argument after an unrecognized flag.
          ++i;
        } else {
          URLlist.push(argument);
        }
      }

      let path = null;
      if (urlOrFileToSave && !URLlist.length) {
        // URL was specified next to "-screenshot"
        // Example: -screenshot https://www.example.com -attach-console
        URLlist.push(urlOrFileToSave);
      } else {
        path = urlOrFileToSave;
      }

      if (!path) {
        path = PathUtils.join(cmdLine.workingDirectory.path, "screenshot.png");
      }

      if (URLlist.length == 1) {
        await takeScreenshot(
          fullWidth,
          fullHeight,
          contentWidth,
          contentHeight,
          path,
          URLlist[0]
        );
      } else {
        dump("expected exactly one URL when using `screenshot`\n");
      }
    } finally {
      Services.startup.exitLastWindowClosingSurvivalArea();
      Services.startup.quit(Ci.nsIAppStartup.eForceQuit);
    }
  },
};