File: viewPartialSource.js

package info (click to toggle)
iceweasel 2.0.0.19-0etch1
  • links: PTS
  • area: main
  • in suites: etch
  • size: 298,784 kB
  • ctags: 317,912
  • sloc: cpp: 1,796,902; ansic: 987,677; xml: 109,036; makefile: 47,777; asm: 35,201; perl: 26,983; sh: 20,879; cs: 6,232; java: 5,513; python: 3,249; pascal: 459; lex: 306; php: 244; csh: 132; objc: 97; yacc: 79; ada: 49; awk: 14; sql: 4; sed: 4
file content (516 lines) | stat: -rw-r--r-- 18,718 bytes parent folder | download | duplicates (4)
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
# -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is mozilla.org view-source front-end.
#
# The Initial Developer of the Original Code is
# mozilla.org.
# Portions created by the Initial Developer are Copyright (C) 2002
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#   Roger B. Sidje <rbs@maths.uq.edu.au> (Original Author)
#   Steve Swanson <steve.swanson@mackichan.com>
#   Doron Rosenberg <doronr@naboonline.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****

var gDebug = 0;
var gLineCount = 0;
var gStartTargetLine = 0;
var gEndTargetLine = 0;
var gTargetNode = null;

var gEntityConverter = null;
var gWrapLongLines = false;
const gViewSourceCSS = 'resource://gre/res/viewsource.css';
const NS_XHTML = 'http://www.w3.org/1999/xhtml';

// These are markers used to delimit the selection during processing. They
// are removed from the final rendering, but we pick space-like characters for
// safety (and futhermore, these are known to be mapped to a 0-length string
// in transliterate.properties). It is okay to set start=end, we use findNext()
// U+200B ZERO WIDTH SPACE
const MARK_SELECTION_START = '\u200B\u200B\u200B\u200B\u200B';
const MARK_SELECTION_END = '\u200B\u200B\u200B\u200B\u200B';

function onLoadViewPartialSource()
{
  // check the view_source.wrap_long_lines pref and set the menuitem's checked attribute accordingly
  if (gPrefs) {
    try {
      var wraplonglinesPrefValue = gPrefs.getBoolPref('view_source.wrap_long_lines');
      if (wraplonglinesPrefValue) {
        document.getElementById('menu_wrapLongLines').setAttribute('checked', 'true');
        gWrapLongLines = true;
      }
    } catch (e) { }
    try {
      document.getElementById("menu_highlightSyntax").setAttribute("checked", gPrefs.getBoolPref("view_source.syntax_highlight"));
    } catch (e) {
    }
  } else {
    document.getElementById("menu_highlightSyntax").setAttribute("hidden", "true");
  }
  
  gFindBar.initFindBar();

  if (window.arguments[3] == 'selection')
    viewPartialSourceForSelection(window.arguments[2]);
  else
    viewPartialSourceForFragment(window.arguments[2], window.arguments[3]);

  window._content.focus();
}

function onUnloadViewPartialSource()
{
  gFindBar.uninitFindBar();
}

////////////////////////////////////////////////////////////////////////////////
// view-source of a selection with the special effect of remapping the selection
// to the underlying view-source output
function viewPartialSourceForSelection(selection)
{
  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
  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 DocumentViewerImpl::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 = getPath(ancestorContainer, startContainer);
  var endPath = 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
  ancestorContainer = ancestorContainer.cloneNode(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();
  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...)
    var tmpNode;
    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 = doc.createTextNode(MARK_SELECTION_END);
        endContainer = endContainer.parentNode;
        if (endOffset == 0)
          endContainer.parentNode.insertBefore(tmpNode, endContainer);
        else
          endContainer.parentNode.insertBefore(tmpNode, endContainer.nextSibling);
      }
    }
    else {
      tmpNode = doc.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 = doc.createTextNode(MARK_SELECTION_START);
        startContainer = startContainer.parentNode;
        if (startOffset == 0)
          startContainer.parentNode.insertBefore(tmpNode, startContainer);
        else
          startContainer.parentNode.insertBefore(tmpNode, startContainer.nextSibling);
      }
    }
    else {
      tmpNode = doc.createTextNode(MARK_SELECTION_START);
      startContainer.insertBefore(tmpNode, startContainer.childNodes.item(startOffset));
    }
  }

  // now extract and display the syntax highlighted source
  tmpNode = doc.createElementNS(NS_XHTML, 'div');
  tmpNode.appendChild(ancestorContainer);

  // the load is aynchronous and so we will wait until the view-source DOM is done
  // before drawing the selection.
  if (canDrawSelection) {
    window.document.getElementById("appcontent").addEventListener("load", drawSelection, true);
  }

  // all our content is held by the data:URI and URIs are internally stored as utf-8 (see nsIURI.idl)
  var loadFlags = Components.interfaces.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE;
  getBrowser().webNavigation
              .loadURI("view-source:data:text/html;charset=utf-8," + encodeURIComponent(tmpNode.innerHTML),
                       loadFlags, null, null, null);
}

////////////////////////////////////////////////////////////////////////////////
// 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
function getPath(ancestor, node)
{
  var n = node;
  var p = n.parentNode;
  if (n == ancestor || !p)
    return null;
  var path = new Array();
  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;
}

////////////////////////////////////////////////////////////////////////////////
// using special markers left in the serialized source, this helper makes the
// underlying markup of the selected fragment to automatically appear as selected
// on the inflated view-source DOM
function drawSelection()
{
  getBrowser().contentDocument.title =
    getViewSourceBundle().getString("viewSelectionSourceTitle");

  // find the special selection markers that we added earlier, and
  // draw the selection between the two...
  var findService = null;
  try {
    // get the find service which stores the global find state
    findService = Components.classes["@mozilla.org/find/find_service;1"]
                            .getService(Components.interfaces.nsIFindService);
  } catch(e) { }
  if (!findService)
    return;

  // cache the current global find state
  var matchCase     = findService.matchCase;
  var entireWord    = findService.entireWord;
  var wrapFind      = findService.wrapFind;
  var findBackwards = findService.findBackwards;
  var searchString  = findService.searchString;
  var replaceString = findService.replaceString;

  // setup our find instance
  var findInst = getBrowser().webBrowserFind;
  findInst.matchCase = true;
  findInst.entireWord = false;
  findInst.wrapFind = true;
  findInst.findBackwards = false;

  // ...lookup the start mark
  findInst.searchString = MARK_SELECTION_START;
  var startLength = MARK_SELECTION_START.length;
  findInst.findNext();

  var contentWindow = getBrowser().contentDocument.defaultView;
  var selection = contentWindow.getSelection();
  var range = selection.getRangeAt(0);

  var startContainer = range.startContainer;
  var startOffset = range.startOffset;

  // ...lookup the end mark
  findInst.searchString = MARK_SELECTION_END;
  var endLength = MARK_SELECTION_END.length;
  findInst.findNext();

  var endContainer = selection.anchorNode;
  var endOffset = selection.anchorOffset;

  // reset the selection that find has left
  selection.removeAllRanges();

  // delete the special markers now...
  endContainer.deleteData(endOffset, endLength);
  startContainer.deleteData(startOffset, startLength);
  if (startContainer == endContainer)
    endOffset -= startLength; // has shrunk if on same text node...
  range.setEnd(endContainer, endOffset);

  // show the selection and scroll it into view
  selection.addRange(range);
  // the default behavior of the selection is to scroll at the end of
  // the selection, whereas in this situation, it is more user-friendly
  // to scroll at the beginning. So we override the default behavior here
  try {
    getBrowser().docShell
                .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                .getInterface(Components.interfaces.nsISelectionDisplay)
                .QueryInterface(Components.interfaces.nsISelectionController)
                .scrollSelectionIntoView(Components.interfaces.nsISelectionController.SELECTION_NORMAL,
                                         Components.interfaces.nsISelectionController.SELECTION_ANCHOR_REGION,
                                         true);
  }
  catch(e) { }

  // restore the current find state
  findService.matchCase     = matchCase;
  findService.entireWord    = entireWord;
  findService.wrapFind      = wrapFind;
  findService.findBackwards = findBackwards;
  findService.searchString  = searchString;
  findService.replaceString = replaceString;

  findInst.matchCase     = matchCase;
  findInst.entireWord    = entireWord;
  findInst.wrapFind      = wrapFind;
  findInst.findBackwards = findBackwards;
  findInst.searchString  = searchString;
}

////////////////////////////////////////////////////////////////////////////////
// special handler for markups such as MathML where reformatting the output is
// helpful
function viewPartialSourceForFragment(node, context)
{
  gTargetNode = node;
  if (gTargetNode && gTargetNode.nodeType == Node.TEXT_NODE)
    gTargetNode = gTargetNode.parentNode;

  // walk up the tree to the top-level element (e.g., <math>, <svg>)
  var topTag;
  if (context == 'mathml')
    topTag = 'math';
  else
    throw 'not reached';
  var topNode = gTargetNode;
  while (topNode && topNode.localName != topTag)
    topNode = topNode.parentNode;
  if (!topNode)
    return;

  // serialize
  var title = getViewSourceBundle().getString("viewMathMLSourceTitle");
  var wrapClass = gWrapLongLines ? ' class="wrap"' : '';
  var source =
    '<html>'
  + '<head><title>' + title + '</title>'
  + '<link rel="stylesheet" type="text/css" href="' + gViewSourceCSS + '">'
  + '<style type="text/css">'
  + '#target { border: dashed 1px; background-color: lightyellow; }'
  + '</style>'
  + '</head>'
  + '<body id="viewsource"' + wrapClass
  +        ' onload="document.title=\''+title+'\';document.getElementById(\'target\').scrollIntoView(true)">'
  + '<pre>'
  + getOuterMarkup(topNode, 0)
  + '</pre></body></html>'
  ; // end

  // display
  var doc = getBrowser().contentDocument;
  doc.open("text/html", "replace");
  doc.write(source);
  doc.close();
}

////////////////////////////////////////////////////////////////////////////////
function getInnerMarkup(node, indent) {
  var str = '';
  for (var i = 0; i < node.childNodes.length; i++) {
    str += getOuterMarkup(node.childNodes.item(i), indent);
  }
  return str;
}

////////////////////////////////////////////////////////////////////////////////
function getOuterMarkup(node, indent) {
  var newline = '';
  var padding = '';
  var str = '';
  if (node == gTargetNode) {
    gStartTargetLine = gLineCount;
    str += '</pre><pre id="target">';
  }

  switch (node.nodeType) {
  case Node.ELEMENT_NODE: // Element
    // to avoid the wide gap problem, '\n' is not emitted on the first
    // line and the lines before & after the <pre id="target">...</pre>
    if (gLineCount > 0 &&
        gLineCount != gStartTargetLine &&
        gLineCount != gEndTargetLine) {
      newline = '\n';
    }
    gLineCount++;
    if (gDebug) {
      newline += gLineCount;
    }
    for (var k = 0; k < indent; k++) {
      padding += ' ';
    }
    str += newline + padding
        +  '&lt;<span class="start-tag">' + node.nodeName + '</span>';
    for (var i = 0; i < node.attributes.length; i++) {
      var attr = node.attributes.item(i);
      if (!gDebug && attr.nodeName.match(/^[-_]moz/)) {
        continue;
      }
      str += ' <span class="attribute-name">'
          +  attr.nodeName
          +  '</span>=<span class="attribute-value">"'
          +  unicodeTOentity(attr.nodeValue)
          +  '"</span>';
    }
    if (!node.hasChildNodes()) {
      str += '/&gt;';
    }
    else {
      str += '&gt;';
      var oldLine = gLineCount;
      str += getInnerMarkup(node, indent + 2);
      if (oldLine == gLineCount) {
        newline = '';
        padding = '';
      }
      else {
        newline = (gLineCount == gEndTargetLine) ? '' : '\n';
        gLineCount++;
        if (gDebug) {
          newline += gLineCount;
        }
      }
      str += newline + padding
          +  '&lt;/<span class="end-tag">' + node.nodeName + '</span>&gt;';
    }
    break;
  case Node.TEXT_NODE: // Text
    var tmp = node.nodeValue;
    tmp = tmp.replace(/(\n|\r|\t)+/g, " ");
    tmp = tmp.replace(/^ +/, "");
    tmp = tmp.replace(/ +$/, "");
    if (tmp.length != 0) {
      str += '<span class="text">' + unicodeTOentity(tmp) + '</span>';
    }
    break;
  default:
    break;
  }

  if (node == gTargetNode) {
    gEndTargetLine = gLineCount;
    str += '</pre><pre>';
  }
  return str;
}

////////////////////////////////////////////////////////////////////////////////
function unicodeTOentity(text)
{
  const charTable = {
    '&': '&amp;<span class="entity">amp;</span>',
    '<': '&amp;<span class="entity">lt;</span>',
    '>': '&amp;<span class="entity">gt;</span>',
    '"': '&amp;<span class="entity">quot;</span>'
  };

  function charTableLookup(letter) {
    return charTable[letter];
  }

  function convertEntity(letter) {
    try {
      var unichar = gEntityConverter.ConvertToEntity(letter, entityVersion);
      var entity = unichar.substring(1); // extract '&'
      return '&amp;<span class="entity">' + entity + '</span>';
    } catch (ex) {
      return letter;
    }
  }

  if (!gEntityConverter) {
    try {
      gEntityConverter =
        Components.classes["@mozilla.org/intl/entityconverter;1"]
                  .createInstance(Components.interfaces.nsIEntityConverter);
    } catch(e) { }
  }

  const entityVersion = Components.interfaces.nsIEntityConverter.entityW3C;

  var str = text;

  // replace chars in our charTable
  str = str.replace(/[<>&"]/g, charTableLookup);

  // replace chars > 0x7f via nsIEntityConverter
  str = str.replace(/[^\0-\u007f]/g, convertEntity);

  return str;
}