summaryrefslogtreecommitdiffstats
path: root/toolkit/actors/ViewSourceChild.sys.mjs
blob: 4c573865b76d22250cf590a9fa360016687decec (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
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* 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/. */

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  ViewSourcePageChild: "resource://gre/actors/ViewSourcePageChild.sys.mjs",
});

export class ViewSourceChild extends JSWindowActorChild {
  receiveMessage(message) {
    let data = message.data;
    switch (message.name) {
      case "ViewSource:LoadSource":
        this.viewSource(data.URL, data.outerWindowID, data.lineNumber);
        break;
      case "ViewSource:LoadSourceWithSelection":
        this.viewSourceWithSelection(
          data.URL,
          data.drawSelection,
          data.baseURI
        );
        break;
      case "ViewSource:GetSelection":
        let selectionDetails;
        try {
          selectionDetails = this.getSelection(this.document.ownerGlobal);
        } catch (e) {}
        return selectionDetails;
    }

    return undefined;
  }

  /**
   * Called when the parent sends a message to view some source code.
   *
   * @param URL (required)
   *        The URL string of the source to be shown.
   * @param outerWindowID (optional)
   *        The outerWindowID of the content window that has hosted
   *        the document, in case we want to retrieve it from the network
   *        cache.
   * @param lineNumber (optional)
   *        The line number to focus as soon as the source has finished
   *        loading.
   */
  viewSource(URL, outerWindowID, lineNumber) {
    let otherDocShell;
    let forceEncodingDetection = false;

    if (outerWindowID) {
      let contentWindow = Services.wm.getOuterWindowWithId(outerWindowID);
      if (contentWindow) {
        otherDocShell = contentWindow.docShell;

        forceEncodingDetection = contentWindow.windowUtils.docCharsetIsForced;
      }
    }

    this.loadSource(URL, otherDocShell, lineNumber, forceEncodingDetection);
  }

  /**
   * Loads a view source selection showing the given view-source url and
   * highlight the selection.
   *
   * @param uri view-source uri to show
   * @param drawSelection true to highlight the selection
   * @param baseURI base URI of the original document
   */
  viewSourceWithSelection(uri, drawSelection, baseURI) {
    // This isn't ideal, but set a global in the view source page actor
    // that indicates that a selection should be drawn. It will be read
    // when by the page's pageshow listener. This should work as the
    // view source page is always loaded in the same process.
    lazy.ViewSourcePageChild.setNeedsDrawSelection(drawSelection);

    // all our content is held by the data:URI and URIs are internally stored as utf-8 (see nsIURI.idl)
    let loadFlags = Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
    let webNav = this.docShell.QueryInterface(Ci.nsIWebNavigation);
    let loadURIOptions = {
      triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
      loadFlags,
      baseURI: Services.io.newURI(baseURI),
    };
    webNav.fixupAndLoadURIString(uri, loadURIOptions);
  }

  /**
   * Common utility function used by both the current and deprecated APIs
   * for loading source.
   *
   * @param URL (required)
   *        The URL string of the source to be shown.
   * @param otherDocShell (optional)
   *        The docshell of the content window that is hosting the document.
   * @param lineNumber (optional)
   *        The line number to focus as soon as the source has finished
   *        loading.
   * @param forceEncodingDetection (optional)
   *        Force autodetection of the character encoding.
   */
  loadSource(URL, otherDocShell, lineNumber, forceEncodingDetection) {
    const viewSrcURL = "view-source:" + URL;

    if (forceEncodingDetection) {
      this.docShell.forceEncodingDetection();
    }

    if (lineNumber) {
      lazy.ViewSourcePageChild.setInitialLineNumber(lineNumber);
    }

    if (!otherDocShell) {
      this.loadSourceFromURL(viewSrcURL);
      return;
    }

    try {
      let pageLoader = this.docShell.QueryInterface(Ci.nsIWebPageDescriptor);
      pageLoader.loadPageAsViewSource(otherDocShell, viewSrcURL);
    } catch (e) {
      // We were not able to load the source from the network cache.
      this.loadSourceFromURL(viewSrcURL);
    }
  }

  /**
   * Load some URL in the browser.
   *
   * @param URL
   *        The URL string to load.
   */
  loadSourceFromURL(URL) {
    let loadFlags = Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
    let webNav = this.docShell.QueryInterface(Ci.nsIWebNavigation);
    let loadURIOptions = {
      triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
      loadFlags,
    };
    webNav.fixupAndLoadURIString(URL, loadURIOptions);
  }

  /**
   * A helper to get a path like FIXptr, but with an array instead of the
   * "tumbler" notation.
   * See FIXptr: http://lists.w3.org/Archives/Public/www-xml-linking-comments/2001AprJun/att-0074/01-NOTE-FIXptr-20010425.htm
   */
  getPath(ancestor, node) {
    var n = node;
    var p = n.parentNode;
    if (n == ancestor || !p) {
      return null;
    }
    var path = [];
    if (!path) {
      return null;
    }
    do {
      for (var i = 0; i < p.childNodes.length; i++) {
        if (p.childNodes.item(i) == n) {
          path.push(i);
          break;
        }
      }
      n = p;
      p = n.parentNode;
    } while (n != ancestor && p);
    return path;
  }

  getSelection(global) {
    const { content } = global;

    // These are markers used to delimit the selection during processing. They
    // are removed from the final rendering.
    // We use noncharacter Unicode codepoints to minimize the risk of clashing
    // with anything that might legitimately be present in the document.
    // U+FDD0..FDEF <noncharacters>
    const MARK_SELECTION_START = "\uFDD0";
    const MARK_SELECTION_END = "\uFDEF";

    var focusedWindow = Services.focus.focusedWindow || content;
    var selection = focusedWindow.getSelection();

    var range = selection.getRangeAt(0);
    var ancestorContainer = range.commonAncestorContainer;
    var doc = ancestorContainer.ownerDocument;

    var startContainer = range.startContainer;
    var endContainer = range.endContainer;
    var startOffset = range.startOffset;
    var endOffset = range.endOffset;

    // let the ancestor be an element
    var Node = doc.defaultView.Node;
    if (
      ancestorContainer.nodeType == Node.TEXT_NODE ||
      ancestorContainer.nodeType == Node.CDATA_SECTION_NODE
    ) {
      ancestorContainer = ancestorContainer.parentNode;
    }

    // for selectAll, let's use the entire document, including <html>...</html>
    // @see nsDocumentViewer::SelectAll() for how selectAll is implemented
    try {
      if (ancestorContainer == doc.body) {
        ancestorContainer = doc.documentElement;
      }
    } catch (e) {}

    // each path is a "child sequence" (a.k.a. "tumbler") that
    // descends from the ancestor down to the boundary point
    var startPath = this.getPath(ancestorContainer, startContainer);
    var endPath = this.getPath(ancestorContainer, endContainer);

    // clone the fragment of interest and reset everything to be relative to it
    // note: it is with the clone that we operate/munge from now on.  Also note
    // that we clone into a data document to prevent images in the fragment from
    // loading and the like.  The use of importNode here, as opposed to adoptNode,
    // is _very_ important.
    // XXXbz wish there were a less hacky way to create an untrusted document here
    var isHTML = doc.createElement("div").tagName == "DIV";
    var dataDoc = isHTML
      ? ancestorContainer.ownerDocument.implementation.createHTMLDocument("")
      : ancestorContainer.ownerDocument.implementation.createDocument(
          "",
          "",
          null
        );
    ancestorContainer = dataDoc.importNode(ancestorContainer, true);
    startContainer = ancestorContainer;
    endContainer = ancestorContainer;

    // Only bother with the selection if it can be remapped. Don't mess with
    // leaf elements (such as <isindex>) that secretly use anynomous content
    // for their display appearance.
    var canDrawSelection = ancestorContainer.hasChildNodes();
    var tmpNode;
    if (canDrawSelection) {
      var i;
      for (i = startPath ? startPath.length - 1 : -1; i >= 0; i--) {
        startContainer = startContainer.childNodes.item(startPath[i]);
      }
      for (i = endPath ? endPath.length - 1 : -1; i >= 0; i--) {
        endContainer = endContainer.childNodes.item(endPath[i]);
      }

      // add special markers to record the extent of the selection
      // note: |startOffset| and |endOffset| are interpreted either as
      // offsets in the text data or as child indices (see the Range spec)
      // (here, munging the end point first to keep the start point safe...)
      if (
        endContainer.nodeType == Node.TEXT_NODE ||
        endContainer.nodeType == Node.CDATA_SECTION_NODE
      ) {
        // do some extra tweaks to try to avoid the view-source output to look like
        // ...<tag>]... or ...]</tag>... (where ']' marks the end of the selection).
        // To get a neat output, the idea here is to remap the end point from:
        // 1. ...<tag>]...   to   ...]<tag>...
        // 2. ...]</tag>...  to   ...</tag>]...
        if (
          (endOffset > 0 && endOffset < endContainer.data.length) ||
          !endContainer.parentNode ||
          !endContainer.parentNode.parentNode
        ) {
          endContainer.insertData(endOffset, MARK_SELECTION_END);
        } else {
          tmpNode = dataDoc.createTextNode(MARK_SELECTION_END);
          endContainer = endContainer.parentNode;
          if (endOffset === 0) {
            endContainer.parentNode.insertBefore(tmpNode, endContainer);
          } else {
            endContainer.parentNode.insertBefore(
              tmpNode,
              endContainer.nextSibling
            );
          }
        }
      } else {
        tmpNode = dataDoc.createTextNode(MARK_SELECTION_END);
        endContainer.insertBefore(
          tmpNode,
          endContainer.childNodes.item(endOffset)
        );
      }

      if (
        startContainer.nodeType == Node.TEXT_NODE ||
        startContainer.nodeType == Node.CDATA_SECTION_NODE
      ) {
        // do some extra tweaks to try to avoid the view-source output to look like
        // ...<tag>[... or ...[</tag>... (where '[' marks the start of the selection).
        // To get a neat output, the idea here is to remap the start point from:
        // 1. ...<tag>[...   to   ...[<tag>...
        // 2. ...[</tag>...  to   ...</tag>[...
        if (
          (startOffset > 0 && startOffset < startContainer.data.length) ||
          !startContainer.parentNode ||
          !startContainer.parentNode.parentNode ||
          startContainer != startContainer.parentNode.lastChild
        ) {
          startContainer.insertData(startOffset, MARK_SELECTION_START);
        } else {
          tmpNode = dataDoc.createTextNode(MARK_SELECTION_START);
          startContainer = startContainer.parentNode;
          if (startOffset === 0) {
            startContainer.parentNode.insertBefore(tmpNode, startContainer);
          } else {
            startContainer.parentNode.insertBefore(
              tmpNode,
              startContainer.nextSibling
            );
          }
        }
      } else {
        tmpNode = dataDoc.createTextNode(MARK_SELECTION_START);
        startContainer.insertBefore(
          tmpNode,
          startContainer.childNodes.item(startOffset)
        );
      }
    }

    // now extract and display the syntax highlighted source
    tmpNode = dataDoc.createElementNS("http://www.w3.org/1999/xhtml", "div");
    tmpNode.appendChild(ancestorContainer);

    return {
      URL:
        (isHTML
          ? "view-source:data:text/html;charset=utf-8,"
          : "view-source:data:application/xml;charset=utf-8,") +
        encodeURIComponent(tmpNode.innerHTML),
      drawSelection: canDrawSelection,
      baseURI: doc.baseURI,
    };
  }

  get wrapLongLines() {
    return Services.prefs.getBoolPref("view_source.wrap_long_lines");
  }
}