home *** CD-ROM | disk | FTP | other *** search
/ ftp.swcp.com / ftp.swcp.com.zip / ftp.swcp.com / mac / mozilla-macos9-1.3.1.sea.bin / Mozilla1.3.1 / Chrome / comm.jar / content / navigator / viewPartialSource.js < prev    next >
Text File  |  2003-06-08  |  18KB  |  491 lines

  1. /* ***** BEGIN LICENSE BLOCK *****
  2.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3.  *
  4.  * The contents of this file are subject to the Mozilla Public License Version
  5.  * 1.1 (the "License"); you may not use this file except in compliance with
  6.  * the License. You may obtain a copy of the License at
  7.  * http://www.mozilla.org/MPL/
  8.  *
  9.  * Software distributed under the License is distributed on an "AS IS" basis,
  10.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11.  * for the specific language governing rights and limitations under the
  12.  * License.
  13.  *
  14.  * The Original Code is mozilla.org view-source front-end.
  15.  *
  16.  * The Initial Developer of the Original Code is mozilla.org.
  17.  * Portions created by the Initial Developer are Copyright (C) 2002
  18.  * the Initial Developer. All Rights Reserved.
  19.  *
  20.  * Contributor(s):
  21.  *   Roger B. Sidje <rbs@maths.uq.edu.au> (Original Author)
  22.  *   Steve Swanson <steve.swanson@mackichan.com>
  23.  *   Doron Rosenberg <doronr@naboonline.com>
  24.  *
  25.  * Alternatively, the contents of this file may be used under the terms of
  26.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  27.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  28.  * in which case the provisions of the GPL or the LGPL are applicable instead
  29.  * of those above. If you wish to allow use of your version of this file only
  30.  * under the terms of either the GPL or the LGPL, and not to allow others to
  31.  * use your version of this file under the terms of the MPL, indicate your
  32.  * decision by deleting the provisions above and replace them with the notice
  33.  * and other provisions required by the GPL or the LGPL. If you do not delete
  34.  * the provisions above, a recipient may use your version of this file under
  35.  * the terms of any one of the MPL, the GPL or the LGPL.
  36.  *
  37.  * ***** END LICENSE BLOCK ***** */
  38.  
  39. var gDebug = 0;
  40. var gLineCount = 0;
  41. var gStartTargetLine = 0;
  42. var gEndTargetLine = 0;
  43. var gTargetNode = null;
  44.  
  45. var gEntityConverter = null;
  46. var gWrapLongLines = false;
  47. const gViewSourceCSS = 'resource:///res/viewsource.css';
  48. const NS_XHTML = 'http://www.w3.org/1999/xhtml';
  49.  
  50. // These are markers used to delimit the selection during processing. They
  51. // are removed from the final rendering, but we pick space-like characters for
  52. // safety (and futhermore, these are known to be mapped to a 0-length string
  53. // in transliterate.properties). It is okay to set start=end, we use findNext()
  54. // U+200B ZERO WIDTH SPACE
  55. const MARK_SELECTION_START = '\u200B\u200B\u200B\u200B\u200B';
  56. const MARK_SELECTION_END = '\u200B\u200B\u200B\u200B\u200B';
  57.  
  58. function onLoadViewPartialSource()
  59. {
  60.   // check the view_source.wrap_long_lines pref and set the menuitem's checked attribute accordingly
  61.   if (gPrefs) {
  62.     try {
  63.       var wraplonglinesPrefValue = gPrefs.getBoolPref('view_source.wrap_long_lines');
  64.       if (wraplonglinesPrefValue) {
  65.         document.getElementById('menu_wrapLongLines').setAttribute('checked', 'true');
  66.         gWrapLongLines = true;
  67.       }
  68.     } catch (e) { }
  69.     try {
  70.       document.getElementById("menu_highlightSyntax").setAttribute("checked", gPrefs.getBoolPref("view_source.syntax_highlight"));
  71.     } catch (e) {
  72.     }
  73.   } else {
  74.     document.getElementById("menu_highlightSyntax").setAttribute("hidden", "true");
  75.   }
  76.  
  77.   // disable menu items that don't work since the selection is munged and
  78.   // the editor doesn't work for MathML
  79.   document.getElementById('cmd_savePage').setAttribute('disabled', 'true');
  80.   document.getElementById('cmd_editPage').setAttribute('disabled', 'true');
  81.  
  82.   if (window.arguments[3] == 'selection')
  83.     viewPartialSourceForSelection(window.arguments[2]);
  84.   else
  85.     viewPartialSourceForFragment(window.arguments[2], window.arguments[3]);
  86.  
  87.   window._content.focus();
  88. }
  89.  
  90. ////////////////////////////////////////////////////////////////////////////////
  91. // view-source of a selection with the special effect of remapping the selection
  92. // to the underlying view-source output
  93. function viewPartialSourceForSelection(selection)
  94. {
  95.   var range = selection.getRangeAt(0);
  96.   var ancestorContainer = range.commonAncestorContainer;
  97.   var doc = ancestorContainer.ownerDocument;
  98.  
  99.   var startContainer = range.startContainer;
  100.   var endContainer = range.endContainer;
  101.   var startOffset = range.startOffset;
  102.   var endOffset = range.endOffset;
  103.  
  104.   // let the ancestor be an element
  105.   if (ancestorContainer.nodeType == Node.TEXT_NODE ||
  106.       ancestorContainer.nodeType == Node.CDATA_SECTION_NODE)
  107.     ancestorContainer = ancestorContainer.parentNode;
  108.  
  109.   // each path is a "child sequence" (a.k.a. "tumbler") that
  110.   // descends from the ancestor down to the boundary point
  111.   var startPath = getPath(ancestorContainer, startContainer);
  112.   var endPath = getPath(ancestorContainer, endContainer);
  113.  
  114.   // clone the fragment of interest and reset everything to be relative to it
  115.   ancestorContainer = ancestorContainer.cloneNode(true);
  116.   startContainer = ancestorContainer;
  117.   endContainer = ancestorContainer;
  118.   var i;
  119.   for (i = startPath ? startPath.length-1 : -1; i >= 0; i--) {
  120.     startContainer = startContainer.childNodes.item(startPath[i]);
  121.   }
  122.   for (i = endPath ? endPath.length-1 : -1; i >= 0; i--) {
  123.     endContainer = endContainer.childNodes.item(endPath[i]);
  124.   }
  125.  
  126.   // add special markers to record the extent of the selection
  127.   // note: |startOffset| and |endOffset| are interpreted either as
  128.   // offsets in the text data or as child indices (see the Range spec)
  129.   // (here, munging the end point first to keep the start point safe...)
  130.   var tmpNode;
  131.   if (endContainer.nodeType == Node.TEXT_NODE ||
  132.       endContainer.nodeType == Node.CDATA_SECTION_NODE) {
  133.     // do some extra tweaks to try to avoid the view-source output to look like
  134.     // ...<tag>]... or ...]</tag>... (where ']' marks the end of the selection).
  135.     // To get a neat output, the idea here is to remap the end point from:
  136.     // 1. ...<tag>]...   to   ...]<tag>...
  137.     // 2. ...]</tag>...  to   ...</tag>]...
  138.     if ((endOffset > 0 && endOffset < endContainer.data.length-1) ||
  139.         !endContainer.parentNode || !endContainer.parentNode.parentNode)
  140.       endContainer.insertData(endOffset, MARK_SELECTION_END);
  141.     else {
  142.       tmpNode = doc.createTextNode(MARK_SELECTION_END);
  143.       endContainer = endContainer.parentNode;
  144.       if (endOffset == 0)
  145.         endContainer.parentNode.insertBefore(tmpNode, endContainer);
  146.       else
  147.         endContainer.parentNode.insertBefore(tmpNode, endContainer.nextSibling);
  148.     }
  149.   }
  150.   else {
  151.     tmpNode = doc.createTextNode(MARK_SELECTION_END);
  152.     endContainer.insertBefore(tmpNode, endContainer.childNodes.item(endOffset));
  153.   }
  154.  
  155.   if (startContainer.nodeType == Node.TEXT_NODE ||
  156.       startContainer.nodeType == Node.CDATA_SECTION_NODE) {
  157.     // do some extra tweaks to try to avoid the view-source output to look like
  158.     // ...<tag>[... or ...[</tag>... (where '[' marks the start of the selection).
  159.     // To get a neat output, the idea here is to remap the start point from:
  160.     // 1. ...<tag>[...   to   ...[<tag>...
  161.     // 2. ...[</tag>...  to   ...</tag>[...
  162.     if ((startOffset > 0 && startOffset < startContainer.data.length-1) ||
  163.         !startContainer.parentNode || !startContainer.parentNode.parentNode)
  164.       startContainer.insertData(startOffset, MARK_SELECTION_START);
  165.     else {
  166.       tmpNode = doc.createTextNode(MARK_SELECTION_START);
  167.       startContainer = startContainer.parentNode;
  168.       if (startOffset == 0)
  169.         startContainer.parentNode.insertBefore(tmpNode, startContainer);
  170.       else
  171.         startContainer.parentNode.insertBefore(tmpNode, startContainer.nextSibling);
  172.     }
  173.   }
  174.   else {
  175.     tmpNode = doc.createTextNode(MARK_SELECTION_START);
  176.     startContainer.insertBefore(tmpNode, startContainer.childNodes.item(startOffset));
  177.   }
  178.  
  179.   // now extract and display the syntax highlighted source
  180.   tmpNode = doc.createElementNS(NS_XHTML, 'div');
  181.   tmpNode.appendChild(ancestorContainer);
  182.  
  183.   // the load is aynchronous and so we will wait until the view-source DOM is done
  184.   // before drawing the selection.
  185.   window.document.getElementById("appcontent").addEventListener("load", drawSelection, true);
  186.  
  187.   // all our content is held by the data:URI and URIs are internally stored as utf-8 (see nsIURI.idl)
  188.   var loadFlags = Components.interfaces.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE;
  189.   getBrowser().webNavigation
  190.               .loadURI("view-source:data:text/html;charset=utf-8," + escape(tmpNode.innerHTML),
  191.                        loadFlags, null, null, null);
  192. }
  193.  
  194. ////////////////////////////////////////////////////////////////////////////////
  195. // helper to get a path like FIXptr, but with an array instead of the "tumbler" notation
  196. // see FIXptr: http://lists.w3.org/Archives/Public/www-xml-linking-comments/2001AprJun/att-0074/01-NOTE-FIXptr-20010425.htm
  197. function getPath(ancestor, node)
  198. {
  199.   var n = node;
  200.   var p = n.parentNode;
  201.   if (n == ancestor || !p)
  202.     return null;
  203.   var path = new Array();
  204.   if (!path)
  205.     return null;
  206.   do {
  207.     for (var i = 0; i < p.childNodes.length; i++) {
  208.       if (p.childNodes.item(i) == n) {
  209.         path.push(i);
  210.         break;
  211.       }
  212.     }
  213.     n = p;
  214.     p = n.parentNode;
  215.   } while (n != ancestor && p);
  216.   return path;
  217. }
  218.  
  219. ////////////////////////////////////////////////////////////////////////////////
  220. // using special markers left in the serialized source, this helper makes the
  221. // underlying markup of the selected fragement to automatically appear as selected
  222. // on the inflated view-source DOM
  223. function drawSelection()
  224. {
  225.   // find the special selection markers that we added earlier, and
  226.   // draw the selection between the two...
  227.   var findService = null;
  228.   try {
  229.     // get the find service which stores the global find state
  230.     findService = Components.classes["@mozilla.org/find/find_service;1"]
  231.                             .getService(Components.interfaces.nsIFindService);
  232.   } catch(e) { }
  233.   if (!findService)
  234.     return;
  235.  
  236.   // cache the current global find state
  237.   var matchCase     = findService.matchCase;
  238.   var entireWord    = findService.entireWord;
  239.   var wrapFind      = findService.wrapFind;
  240.   var findBackwards = findService.findBackwards;
  241.   var searchString  = findService.searchString;
  242.   var replaceString = findService.replaceString;
  243.  
  244.   // setup our find instance
  245.   var findInst = getBrowser().webBrowserFind;
  246.   findInst.matchCase = true;
  247.   findInst.entireWord = false;
  248.   findInst.wrapFind = false;
  249.   findInst.findBackwards = false;
  250.  
  251.   // ...lookup the start mark
  252.   findInst.searchString = MARK_SELECTION_START;
  253.   var startLength = MARK_SELECTION_START.length;
  254.   findInst.findNext();
  255.  
  256.   var contentWindow = getBrowser().contentDocument.defaultView;
  257.   var selection = contentWindow.getSelection();
  258.   var range = selection.getRangeAt(0);
  259.  
  260.   var startContainer = range.startContainer;
  261.   var startOffset = range.startOffset;
  262.  
  263.   // ...lookup the end mark
  264.   findInst.searchString = MARK_SELECTION_END;
  265.   var endLength = MARK_SELECTION_END.length;
  266.   findInst.findNext();
  267.  
  268.   var endContainer = selection.anchorNode;
  269.   var endOffset = selection.anchorOffset;
  270.  
  271.   // reset the selection that find has left
  272.   selection.removeAllRanges();
  273.  
  274.   // delete the special markers now...
  275.   endContainer.deleteData(endOffset, endLength);
  276.   startContainer.deleteData(startOffset, startLength);
  277.   if (startContainer == endContainer)
  278.     endOffset -= startLength; // has shrunk if on same text node...
  279.   range.setEnd(endContainer, endOffset);
  280.  
  281.   // show the selection and scroll it into view
  282.   selection.addRange(range);
  283.   // the default behavior of the selection is to scroll at the end of
  284.   // the selection, whereas in this situation, it is more user-friendly
  285.   // to scroll at the beginning. So we override the default behavior here
  286.   try {
  287.     getBrowser().docShell
  288.                 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  289.                 .getInterface(Components.interfaces.nsISelectionDisplay)
  290.                 .QueryInterface(Components.interfaces.nsISelectionController)
  291.                 .scrollSelectionIntoView(Components.interfaces.nsISelectionController.SELECTION_NORMAL,
  292.                                          Components.interfaces.nsISelectionController.SELECTION_ANCHOR_REGION,
  293.                                          true);
  294.   }
  295.   catch(e) { }
  296.  
  297.   // restore the current find state
  298.   findService.matchCase     = matchCase;
  299.   findService.entireWord    = entireWord;
  300.   findService.wrapFind      = wrapFind;
  301.   findService.findBackwards = findBackwards;
  302.   findService.searchString  = searchString;
  303.   findService.replaceString = replaceString;
  304.  
  305.   findInst.matchCase     = matchCase;
  306.   findInst.entireWord    = entireWord;
  307.   findInst.wrapFind      = wrapFind;
  308.   findInst.findBackwards = findBackwards;
  309.   findInst.searchString  = searchString;
  310. }
  311.  
  312. ////////////////////////////////////////////////////////////////////////////////
  313. // special handler for markups such as MathML where reformatting the output is
  314. // helpful
  315. function viewPartialSourceForFragment(node, context)
  316. {
  317.   gTargetNode = node;
  318.   if (gTargetNode && gTargetNode.nodeType == Node.TEXT_NODE)
  319.     gTargetNode = gTargetNode.parentNode;
  320.  
  321.   // walk up the tree to the top-level element (e.g., <math>, <svg>)
  322.   var topTag;
  323.   if (context == 'mathml')
  324.     topTag = 'math';
  325.   else
  326.     throw 'not reached';
  327.   var topNode = gTargetNode;
  328.   while (topNode && topNode.localName != topTag)
  329.     topNode = topNode.parentNode;
  330.   if (!topNode)
  331.     return;
  332.  
  333.   // serialize (note: the main window overrides the title set here)
  334.   var wrapClass = gWrapLongLines ? ' class="wrap"' : '';
  335.   var source =
  336.     '<html>'
  337.   + '<head><title>Mozilla</title>'
  338.   + '<link rel="stylesheet" type="text/css" href="' + gViewSourceCSS + '">'
  339.   + '<style type="text/css">'
  340.   + '#target { border: dashed 1px; background-color: lightyellow; }'
  341.   + '</style>'
  342.   + '</head>'
  343.   + '<body id="viewsource"' + wrapClass
  344.   +        ' onload="document.getElementById(\'target\').scrollIntoView(true)">'
  345.   + '<pre>'
  346.   + getOuterMarkup(topNode, 0)
  347.   + '</pre></body></html>'
  348.   ; // end
  349.  
  350.   // display
  351.   var doc = getBrowser().contentDocument;
  352.   doc.open("text/html", "replace");
  353.   doc.write(source);
  354.   doc.close();
  355. }
  356.  
  357. ////////////////////////////////////////////////////////////////////////////////
  358. function getInnerMarkup(node, indent) {
  359.   var str = '';
  360.   for (var i = 0; i < node.childNodes.length; i++) {
  361.     str += getOuterMarkup(node.childNodes.item(i), indent);
  362.   }
  363.   return str;
  364. }
  365.  
  366. ////////////////////////////////////////////////////////////////////////////////
  367. function getOuterMarkup(node, indent) {
  368.   var newline = '';
  369.   var padding = '';
  370.   var str = '';
  371.   if (node == gTargetNode) {
  372.     gStartTargetLine = gLineCount;
  373.     str += '</pre><pre id="target">';
  374.   }
  375.  
  376.   switch (node.nodeType) {
  377.   case Node.ELEMENT_NODE: // Element
  378.     // to avoid the wide gap problem, '\n' is not emitted on the first
  379.     // line and the lines before & after the <pre id="target">...</pre>
  380.     if (gLineCount > 0 &&
  381.         gLineCount != gStartTargetLine &&
  382.         gLineCount != gEndTargetLine) {
  383.       newline = '\n';
  384.     }
  385.     gLineCount++;
  386.     if (gDebug) {
  387.       newline += gLineCount;
  388.     }
  389.     for (var k = 0; k < indent; k++) {
  390.       padding += ' ';
  391.     }
  392.     str += newline + padding
  393.         +  '<<span class="start-tag">' + node.nodeName + '</span>';
  394.     for (var i = 0; i < node.attributes.length; i++) {
  395.       var attr = node.attributes.item(i);
  396.       if (!gDebug && attr.nodeName.match(/^[-_]moz/)) {
  397.         continue;
  398.       }
  399.       str += ' <span class="attribute-name">'
  400.           +  attr.nodeName
  401.           +  '</span>=<span class="attribute-value">"'
  402.           +  unicodeTOentity(attr.nodeValue)
  403.           +  '"</span>';
  404.     }
  405.     if (!node.hasChildNodes()) {
  406.       str += '/>';
  407.     }
  408.     else {
  409.       str += '>';
  410.       var oldLine = gLineCount;
  411.       str += getInnerMarkup(node, indent + 2);
  412.       if (oldLine == gLineCount) {
  413.         newline = '';
  414.         padding = '';
  415.       }
  416.       else {
  417.         newline = (gLineCount == gEndTargetLine) ? '' : '\n';
  418.         gLineCount++;
  419.         if (gDebug) {
  420.           newline += gLineCount;
  421.         }
  422.       }
  423.       str += newline + padding
  424.           +  '</<span class="end-tag">' + node.nodeName + '</span>>';
  425.     }
  426.     break;
  427.   case Node.TEXT_NODE: // Text
  428.     var tmp = node.nodeValue;
  429.     tmp = tmp.replace(/(\n|\r|\t)+/g, " ");
  430.     tmp = tmp.replace(/^ +/, "");
  431.     tmp = tmp.replace(/ +$/, "");
  432.     if (tmp.length != 0) {
  433.       str += '<span class="text">' + unicodeTOentity(tmp) + '</span>';
  434.     }
  435.     break;
  436.   default:
  437.     break;
  438.   }
  439.  
  440.   if (node == gTargetNode) {
  441.     gEndTargetLine = gLineCount;
  442.     str += '</pre><pre>';
  443.   }
  444.   return str;
  445. }
  446.  
  447. ////////////////////////////////////////////////////////////////////////////////
  448. function unicodeTOentity(text)
  449. {
  450.   const charTable = {
  451.     '&': '&<span class="entity">amp;</span>',
  452.     '<': '&<span class="entity">lt;</span>',
  453.     '>': '&<span class="entity">gt;</span>',
  454.     '"': '&<span class="entity">quot;</span>'
  455.   };
  456.  
  457.   function charTableLookup(letter) {
  458.     return charTable[letter];
  459.   }
  460.  
  461.   function convertEntity(letter) {
  462.     try {
  463.       var unichar = gEntityConverter.ConvertToEntity(letter, entityVersion);
  464.       var entity = unichar.substring(1); // extract '&'
  465.       return '&<span class="entity">' + entity + '</span>';
  466.     } catch (ex) {
  467.       return letter;
  468.     }
  469.   }
  470.  
  471.   if (!gEntityConverter) {
  472.     try {
  473.       gEntityConverter =
  474.         Components.classes["@mozilla.org/intl/entityconverter;1"]
  475.                   .createInstance(Components.interfaces.nsIEntityConverter);
  476.     } catch(e) { }
  477.   }
  478.  
  479.   const entityVersion = Components.interfaces.nsIEntityConverter.entityW3C;
  480.  
  481.   var str = text;
  482.  
  483.   // replace chars in our charTable
  484.   str = str.replace(/[<>&"]/g, charTableLookup);
  485.  
  486.   // replace chars > 0x7f via nsIEntityConverter
  487.   str = str.replace(/[^\0-\u007f]/g, convertEntity);
  488.  
  489.   return str;
  490. }
  491.