summaryrefslogtreecommitdiffstats
path: root/devtools/client/shared/screenshot.js
blob: ca746f66e767ccffed58574521a50a47ef73da3f (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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/* 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/. */

"use strict";

const { LocalizationHelper } = require("resource://devtools/shared/l10n.js");

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  Downloads: "resource://gre/modules/Downloads.sys.mjs",
  FileUtils: "resource://gre/modules/FileUtils.sys.mjs",
  PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
});

const STRINGS_URI = "devtools/shared/locales/screenshot.properties";
const L10N = new LocalizationHelper(STRINGS_URI);

/**
 * Take a screenshot of a browser element matching the passed target and save it to a file
 * or the clipboard.
 *
 * @param {TargetFront} targetFront: The targetFront of the frame we want to take a screenshot of.
 * @param {Window} window: The DevTools Client window.
 * @param {Object} args
 * @param {Boolean} args.fullpage: Should the screenshot be the height of the whole page
 * @param {String} args.filename: Expected filename for the screenshot
 * @param {Boolean} args.clipboard: Whether or not the screenshot should be saved to the clipboard.
 * @param {Number} args.dpr: Scale of the screenshot. Defaults to the window `devicePixelRatio`.
 *                           ⚠️ Note that the scale might be decreased if the resulting
 *                           image would be too big to draw safely. Warning will be emitted
 *                           to the console if that's the case.
 * @param {Number} args.delay: Number of seconds to wait before taking the screenshot
 * @param {Boolean} args.help: Set to true to receive a message with the screenshot command
 *                             documentation.
 * @param {Boolean} args.disableFlash: Set to true to disable the flash animation when the
 *                  screenshot is taken.
 * @param {Boolean} args.ignoreDprForFileScale: Set to true to if the resulting screenshot
 *                  file size shouldn't be impacted by the dpr. Note that the dpr will still
 *                  be taken into account when taking the screenshot, only the size of the
 *                  file will be different.
 * @returns {Array<Object{text, level}>} An array of object representing the different
 *          messages emitted throught the process, that should be displayed to the user.
 */
async function captureAndSaveScreenshot(targetFront, window, args = {}) {
  if (args.help) {
    // Wrap message in an array so that the return value is consistant.
    return [{ text: getFormattedHelpData() }];
  }

  const captureResponse = await captureScreenshot(targetFront, args);

  if (captureResponse.error) {
    return captureResponse.messages || [];
  }

  const saveMessages = await saveScreenshot(window, args, captureResponse);
  return (captureResponse.messages || []).concat(saveMessages);
}

/**
 * Take a screenshot of a browser element matching the passed target
 * @param {TargetFront} targetFront: The targetFront of the frame we want to take a screenshot of.
 * @param {Object} args: See args param in captureAndSaveScreenshot
 */
async function captureScreenshot(targetFront, args) {
  // @backward-compat { version 87 } The screenshot-content actor was introduced in 87,
  // so we can always use it once 87 reaches release.
  const supportsContentScreenshot = targetFront.hasActor("screenshotContent");
  if (!supportsContentScreenshot) {
    const screenshotFront = await targetFront.getFront("screenshot");
    return screenshotFront.capture(args);
  }

  if (args.delay > 0) {
    await new Promise(res => setTimeout(res, args.delay * 1000));
  }

  const screenshotContentFront = await targetFront.getFront(
    "screenshot-content"
  );

  // Call the content-process on the server to retrieve informations that will be needed
  // by the parent process.
  const { rect, windowDpr, windowZoom, messages, error } =
    await screenshotContentFront.prepareCapture(args);

  if (error) {
    return { error, messages };
  }

  if (rect) {
    args.rect = rect;
  }

  args.dpr ||= windowDpr;

  args.snapshotScale = args.dpr * windowZoom;
  if (args.ignoreDprForFileScale) {
    args.fileScale = windowZoom;
  }

  args.browsingContextID = targetFront.browsingContextID;

  // We can now call the parent process which will take the screenshot via
  // the drawSnapshot API
  const rootFront = targetFront.client.mainRoot;
  const parentProcessScreenshotFront = await rootFront.getFront("screenshot");
  const captureResponse = await parentProcessScreenshotFront.capture(args);

  return {
    ...captureResponse,
    messages: (messages || []).concat(captureResponse.messages || []),
  };
}

const screenshotDescription = L10N.getStr("screenshotDesc");
const screenshotGroupOptions = L10N.getStr("screenshotGroupOptions");
const screenshotCommandParams = [
  {
    name: "clipboard",
    type: "boolean",
    description: L10N.getStr("screenshotClipboardDesc"),
    manual: L10N.getStr("screenshotClipboardManual"),
  },
  {
    name: "delay",
    type: "number",
    description: L10N.getStr("screenshotDelayDesc"),
    manual: L10N.getStr("screenshotDelayManual"),
  },
  {
    name: "dpr",
    type: "number",
    description: L10N.getStr("screenshotDPRDesc"),
    manual: L10N.getStr("screenshotDPRManual"),
  },
  {
    name: "fullpage",
    type: "boolean",
    description: L10N.getStr("screenshotFullPageDesc"),
    manual: L10N.getStr("screenshotFullPageManual"),
  },
  {
    name: "selector",
    type: "string",
    description: L10N.getStr("inspectNodeDesc"),
    manual: L10N.getStr("inspectNodeManual"),
  },
  {
    name: "file",
    type: "boolean",
    description: L10N.getStr("screenshotFileDesc"),
    manual: L10N.getStr("screenshotFileManual"),
  },
  {
    name: "filename",
    type: "string",
    description: L10N.getStr("screenshotFilenameDesc"),
    manual: L10N.getStr("screenshotFilenameManual"),
  },
];

/**
 * Creates a string from an object for use when screenshot is passed the `--help` argument
 *
 * @param object param
 *        The param object to be formatted.
 * @return string
 *         The formatted information from the param object as a string
 */
function formatHelpField(param) {
  const padding = " ".repeat(5);
  return Object.entries(param)
    .map(([key, value]) => {
      if (key === "name") {
        const name = `${padding}--${value}`;
        return name;
      }
      return `${padding.repeat(2)}${key}: ${value}`;
    })
    .join("\n");
}

/**
 * Creates a string response from the screenshot options for use when
 * screenshot is passed the `--help` argument
 *
 * @return string
 *         The formatted information from the param object as a string
 */
function getFormattedHelpData() {
  const formattedParams = screenshotCommandParams
    .map(formatHelpField)
    .join("\n\n");

  return `${screenshotDescription}\n${screenshotGroupOptions}\n\n${formattedParams}`;
}

/**
 * Main entry point in this file; Takes the original arguments that `:screenshot` was
 * called with and the image value from the server, and uses the client window to add
 * and audio effect.
 *
 * @param object window
 *        The DevTools Client window.
 *
 * @param object args
 *        The original args with which the screenshot
 *        was called.
 * @param object value
 *        an object with a image value and file name
 *
 * @return string[]
 *         Response messages from processing the screenshot
 */
function saveScreenshot(window, args = {}, value) {
  // @backward-compat { version 87 } This is still needed by the console when connecting
  // to an older server. Once 87 is in release, we can remove this whole block since we
  // already handle args.help in captureScreenshotAndSave.
  if (args.help) {
    // Wrap message in an array so that the return value is consistant.
    return [{ text: getFormattedHelpData() }];
  }

  // Guard against missing image data.
  if (!value.data) {
    return [];
  }

  simulateCameraShutter(window);
  return save(window, args, value);
}

/**
 * This function is called to simulate camera effects
 *
 * @param object document
 *        The DevTools Client document.
 */
function simulateCameraShutter(window) {
  if (Services.prefs.getBoolPref("devtools.screenshot.audio.enabled")) {
    const audioCamera = new window.Audio(
      "resource://devtools/client/themes/audio/shutter.wav"
    );
    audioCamera.play();
  }
}

/**
 * Save the captured screenshot to one of several destinations.
 *
 * @param object window
 *        The DevTools Client window.
 *
 * @param object args
 *        The original args with which the screenshot was called.
 *
 * @param object image
 *        The image object that was sent from the server.
 *
 *
 * @return string[]
 *         Response messages from processing the screenshot.
 */
async function save(window, args, image) {
  const fileNeeded = args.filename || !args.clipboard || args.file;
  const results = [];

  if (args.clipboard) {
    const result = saveToClipboard(image.data);
    results.push(result);
  }

  if (fileNeeded) {
    const result = await saveToFile(window, image);
    results.push(result);
  }
  return results;
}

/**
 * Save the image data to the clipboard. This returns a promise, so it can
 * be treated exactly like file processing.
 *
 * @param string base64URI
 *        The image data encoded in a base64 URI that was sent from the server.
 *
 * @return string
 *         Response message from processing the screenshot.
 */
function saveToClipboard(base64URI) {
  try {
    const imageTools = Cc["@mozilla.org/image/tools;1"].getService(
      Ci.imgITools
    );

    const base64Data = base64URI.replace("data:image/png;base64,", "");

    const image = atob(base64Data);
    const img = imageTools.decodeImageFromBuffer(
      image,
      image.length,
      "image/png"
    );

    const transferable = Cc[
      "@mozilla.org/widget/transferable;1"
    ].createInstance(Ci.nsITransferable);
    transferable.init(null);
    transferable.addDataFlavor("image/png");
    transferable.setTransferData("image/png", img);

    Services.clipboard.setData(
      transferable,
      null,
      Services.clipboard.kGlobalClipboard
    );
    return { text: L10N.getStr("screenshotCopied") };
  } catch (ex) {
    console.error(ex);
    return { level: "error", text: L10N.getStr("screenshotErrorCopying") };
  }
}

let _outputDirectory = null;

/**
 * Returns the default directory for screenshots.
 * If a specific directory for screenshots is not defined,
 * it falls back to the system downloads directory.
 *
 * @return {Promise<String>} Resolves the path as a string
 */
async function getOutputDirectory() {
  if (_outputDirectory) {
    return _outputDirectory;
  }

  try {
    // This will throw if there is not a screenshot directory set for the platform
    _outputDirectory = Services.dirsvc.get("Scrnshts", Ci.nsIFile).path;
  } catch (e) {
    _outputDirectory = await lazy.Downloads.getPreferredDownloadsDirectory();
  }

  return _outputDirectory;
}

/**
 * Save the screenshot data to disk, returning a promise which is resolved on
 * completion.
 *
 * @param object window
 *        The DevTools Client window.
 *
 * @param object image
 *        The image object that was sent from the server.
 *
 * @return string
 *         Response message from processing the screenshot.
 */
async function saveToFile(window, image) {
  let filename = image.filename;

  // Guard against missing image data.
  if (!image.data) {
    return "";
  }

  // Check there is a .png extension to filename
  if (!filename.match(/.png$/i)) {
    filename += ".png";
  }

  const dir = await getOutputDirectory();
  const dirExists = await IOUtils.exists(dir);
  if (dirExists) {
    // If filename is absolute, it will override the downloads directory and
    // still be applied as expected.
    filename = PathUtils.isAbsolute(filename)
      ? filename
      : PathUtils.joinRelative(dir, filename);
  }

  const targetFile = new lazy.FileUtils.File(filename);

  // Create download and track its progress.
  try {
    const download = await lazy.Downloads.createDownload({
      source: {
        url: image.data,
        // Here we want to know if the window in which the screenshot is taken is private.
        // We have a ChromeWindow when this is called from Browser Console (:screenshot) and
        // RDM (screenshot button).
        isPrivate: window.isChromeWindow
          ? lazy.PrivateBrowsingUtils.isWindowPrivate(window)
          : lazy.PrivateBrowsingUtils.isBrowserPrivate(
              window.browsingContext.embedderElement
            ),
      },
      target: targetFile,
    });
    const list = await lazy.Downloads.getList(lazy.Downloads.ALL);
    // add the download to the download list in the Downloads list in the Browser UI
    list.add(download);
    // Await successful completion of the save via the download manager
    await download.start();
    return { text: L10N.getFormatStr("screenshotSavedToFile", filename) };
  } catch (ex) {
    console.error(ex);
    return {
      level: "error",
      text: L10N.getFormatStr("screenshotErrorSavingToFile", filename),
    };
  }
}

module.exports = {
  captureAndSaveScreenshot,
  captureScreenshot,
  saveScreenshot,
};