home *** CD-ROM | disk | FTP | other *** search
/ PC World 2003 May / PCWorld_2003-05_cd.bin / Komunik / phoenix / chrome / comm.jar / content / navigator / viewPartialSource.js < prev    next >
Text File  |  2002-11-06  |  18KB  |  487 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.   }
  70.  
  71.   // disable menu items that don't work since the selection is munged and
  72.   // the editor doesn't work for MathML
  73.   document.getElementById('cmd_savePage').setAttribute('disabled', 'true');
  74.   document.getElementById('cmd_editPage').setAttribute('disabled', 'true');
  75.  
  76.   if (window.arguments[3] == 'selection')
  77.     viewPartialSourceForSelection(window.arguments[2]);
  78.   else
  79.     viewPartialSourceForFragment(window.arguments[2], window.arguments[3]);
  80.  
  81.   window._content.focus();
  82. }
  83.  
  84. ////////////////////////////////////////////////////////////////////////////////
  85. // view-source of a selection with the special effect of remapping the selection
  86. // to the underlying view-source output
  87. function viewPartialSourceForSelection(selection)
  88. {
  89.   var range = selection.getRangeAt(0);
  90.   var ancestorContainer = range.commonAncestorContainer;
  91.   var doc = ancestorContainer.ownerDocument;
  92.  
  93.   var startContainer = range.startContainer;
  94.   var endContainer = range.endContainer;
  95.   var startOffset = range.startOffset;
  96.   var endOffset = range.endOffset;
  97.  
  98.   // let the ancestor be an element
  99.   if (ancestorContainer.nodeType == Node.TEXT_NODE ||
  100.       ancestorContainer.nodeType == Node.CDATA_SECTION_NODE)
  101.     ancestorContainer = ancestorContainer.parentNode;
  102.  
  103.   // each path is a "child sequence" (a.k.a. "tumbler") that
  104.   // descends from the ancestor down to the boundary point
  105.   var startPath = getPath(ancestorContainer, startContainer);
  106.   var endPath = getPath(ancestorContainer, endContainer);
  107.  
  108.   // clone the fragment of interest and reset everything to be relative to it
  109.   ancestorContainer = ancestorContainer.cloneNode(true);
  110.   startContainer = ancestorContainer;
  111.   endContainer = ancestorContainer;
  112.   var i;
  113.   for (i = startPath ? startPath.length-1 : -1; i >= 0; i--) {
  114.     startContainer = startContainer.childNodes.item(startPath[i]);
  115.   }
  116.   for (i = endPath ? endPath.length-1 : -1; i >= 0; i--) {
  117.     endContainer = endContainer.childNodes.item(endPath[i]);
  118.   }
  119.  
  120.   // add special markers to record the extent of the selection
  121.   // note: |startOffset| and |endOffset| are interpreted either as
  122.   // offsets in the text data or as child indices (see the Range spec)
  123.   // (here, munging the end point first to keep the start point safe...)
  124.   var tmpNode;
  125.   if (endContainer.nodeType == Node.TEXT_NODE ||
  126.       endContainer.nodeType == Node.CDATA_SECTION_NODE) {
  127.     // do some extra tweaks to try to avoid the view-source output to look like
  128.     // ...<tag>]... or ...]</tag>... (where ']' marks the end of the selection).
  129.     // To get a neat output, the idea here is to remap the end point from:
  130.     // 1. ...<tag>]...   to   ...]<tag>...
  131.     // 2. ...]</tag>...  to   ...</tag>]...
  132.     if ((endOffset > 0 && endOffset < endContainer.data.length-1) ||
  133.         !endContainer.parentNode || !endContainer.parentNode.parentNode)
  134.       endContainer.insertData(endOffset, MARK_SELECTION_END);
  135.     else {
  136.       tmpNode = doc.createTextNode(MARK_SELECTION_END);
  137.       endContainer = endContainer.parentNode;
  138.       if (endOffset == 0)
  139.         endContainer.parentNode.insertBefore(tmpNode, endContainer);
  140.       else
  141.         endContainer.parentNode.insertBefore(tmpNode, endContainer.nextSibling);
  142.     }
  143.   }
  144.   else {
  145.     tmpNode = doc.createTextNode(MARK_SELECTION_END);
  146.     endContainer.insertBefore(tmpNode, endContainer.childNodes.item(endOffset));
  147.   }
  148.  
  149.   if (startContainer.nodeType == Node.TEXT_NODE ||
  150.       startContainer.nodeType == Node.CDATA_SECTION_NODE) {
  151.     // do some extra tweaks to try to avoid the view-source output to look like
  152.     // ...<tag>[... or ...[</tag>... (where '[' marks the start of the selection).
  153.     // To get a neat output, the idea here is to remap the start point from:
  154.     // 1. ...<tag>[...   to   ...[<tag>...
  155.     // 2. ...[</tag>...  to   ...</tag>[...
  156.     if ((startOffset > 0 && startOffset < startContainer.data.length-1) ||
  157.         !startContainer.parentNode || !startContainer.parentNode.parentNode)
  158.       startContainer.insertData(startOffset, MARK_SELECTION_START);
  159.     else {
  160.       tmpNode = doc.createTextNode(MARK_SELECTION_START);
  161.       startContainer = startContainer.parentNode;
  162.       if (startOffset == 0)
  163.         startContainer.parentNode.insertBefore(tmpNode, startContainer);
  164.       else
  165.         startContainer.parentNode.insertBefore(tmpNode, startContainer.nextSibling);
  166.     }
  167.   }
  168.   else {
  169.     tmpNode = doc.createTextNode(MARK_SELECTION_START);
  170.     startContainer.insertBefore(tmpNode, startContainer.childNodes.item(startOffset));
  171.   }
  172.  
  173.   // now extract and display the syntax highlighted source
  174.   tmpNode = doc.createElementNS(NS_XHTML, 'div');
  175.   tmpNode.appendChild(ancestorContainer);
  176.  
  177.   // the load is aynchronous and so we will wait until the view-source DOM is done
  178.   // before drawing the selection.
  179.   window.document.getElementById("appcontent").addEventListener("load", drawSelection, true);
  180.  
  181.   // all our content is held by the data:URI and URIs are internally stored as utf-8 (see nsIURI.idl)
  182.   var loadFlags = Components.interfaces.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE;
  183.   getBrowser().webNavigation
  184.               .loadURI("view-source:data:text/html;charset=utf-8," + escape(tmpNode.innerHTML),
  185.                        loadFlags, null, null, null);
  186. }
  187.  
  188. ////////////////////////////////////////////////////////////////////////////////
  189. // helper to get a path like FIXptr, but with an array instead of the "tumbler" notation
  190. // see FIXptr: http://lists.w3.org/Archives/Public/www-xml-linking-comments/2001AprJun/att-0074/01-NOTE-FIXptr-20010425.htm
  191. function getPath(ancestor, node)
  192. {
  193.   var n = node;
  194.   var p = n.parentNode;
  195.   if (n == ancestor || !p)
  196.     return null;
  197.   var path = new Array();
  198.   if (!path)
  199.     return null;
  200.   do {
  201.     for (var i = 0; i < p.childNodes.length; i++) {
  202.       if (p.childNodes.item(i) == n) {
  203.         path.push(i);
  204.         break;
  205.       }
  206.     }
  207.     n = p;
  208.     p = n.parentNode;
  209.   } while (n != ancestor && p);
  210.   return path;
  211. }
  212.  
  213. ////////////////////////////////////////////////////////////////////////////////
  214. // using special markers left in the serialized source, this helper makes the
  215. // underlying markup of the selected fragement to automatically appear as selected
  216. // on the inflated view-source DOM
  217. function drawSelection()
  218. {
  219.   // find the special selection markers that we added earlier, and
  220.   // draw the selection between the two...
  221.   var findService = null;
  222.   try {
  223.     // get the find service which stores the global find state
  224.     findService = Components.classes["@mozilla.org/find/find_service;1"]
  225.                             .getService(Components.interfaces.nsIFindService);
  226.   } catch(e) { }
  227.   if (!findService)
  228.     return;
  229.  
  230.   // cache the current global find state
  231.   var matchCase     = findService.matchCase;
  232.   var entireWord    = findService.entireWord;
  233.   var wrapFind      = findService.wrapFind;
  234.   var findBackwards = findService.findBackwards;
  235.   var searchString  = findService.searchString;
  236.   var replaceString = findService.replaceString;
  237.  
  238.   // setup our find instance
  239.   var findInst = getBrowser().webBrowserFind;
  240.   findInst.matchCase = true;
  241.   findInst.entireWord = false;
  242.   findInst.wrapFind = false;
  243.   findInst.findBackwards = false;
  244.  
  245.   // ...lookup the start mark
  246.   findInst.searchString = MARK_SELECTION_START;
  247.   var startLength = MARK_SELECTION_START.length;
  248.   findInst.findNext();
  249.  
  250.   var contentWindow = getBrowser().contentDocument.defaultView;
  251.   var selection = contentWindow.getSelection();
  252.   var range = selection.getRangeAt(0);
  253.  
  254.   var startContainer = range.startContainer;
  255.   var startOffset = range.startOffset;
  256.  
  257.   // ...lookup the end mark
  258.   findInst.searchString = MARK_SELECTION_END;
  259.   var endLength = MARK_SELECTION_END.length;
  260.   findInst.findNext();
  261.  
  262.   var endContainer = selection.anchorNode;
  263.   var endOffset = selection.anchorOffset;
  264.  
  265.   // reset the selection that find has left
  266.   selection.removeAllRanges();
  267.  
  268.   // delete the special markers now...
  269.   endContainer.deleteData(endOffset, endLength);
  270.   startContainer.deleteData(startOffset, startLength);
  271.   if (startContainer == endContainer)
  272.     endOffset -= startLength; // has shrunk if on same text node...
  273.   range.setEnd(endContainer, endOffset);
  274.  
  275.   // show the selection and scroll it into view
  276.   selection.addRange(range);
  277.   // the default behavior of the selection is to scroll at the end of
  278.   // the selection, whereas in this situation, it is more user-friendly
  279.   // to scroll at the beginning. So we override the default behavior here
  280.   try {
  281.     getBrowser().docShell
  282.                 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  283.                 .getInterface(Components.interfaces.nsISelectionDisplay)
  284.                 .QueryInterface(Components.interfaces.nsISelectionController)
  285.                 .scrollSelectionIntoView(Components.interfaces.nsISelectionController.SELECTION_NORMAL,
  286.                                          Components.interfaces.nsISelectionController.SELECTION_ANCHOR_REGION,
  287.                                          true);
  288.   }
  289.   catch(e) { }
  290.  
  291.   // restore the current find state
  292.   findService.matchCase     = matchCase;
  293.   findService.entireWord    = entireWord;
  294.   findService.wrapFind      = wrapFind;
  295.   findService.findBackwards = findBackwards;
  296.   findService.searchString  = searchString;
  297.   findService.replaceString = replaceString;
  298.  
  299.   findInst.matchCase     = matchCase;
  300.   findInst.entireWord    = entireWord;
  301.   findInst.wrapFind      = wrapFind;
  302.   findInst.findBackwards = findBackwards;
  303.   findInst.searchString  = searchString;
  304. }
  305.  
  306. ////////////////////////////////////////////////////////////////////////////////
  307. // special handler for markups such as MathML where reformatting the output is
  308. // helpful
  309. function viewPartialSourceForFragment(node, context)
  310. {
  311.   gTargetNode = node;
  312.   if (gTargetNode && gTargetNode.nodeType == Node.TEXT_NODE)
  313.     gTargetNode = gTargetNode.parentNode;
  314.  
  315.   // walk up the tree to the top-level element (e.g., <math>, <svg>)
  316.   var topTag;
  317.   if (context == 'mathml')
  318.     topTag = 'math';
  319.   else
  320.     throw 'not reached';
  321.   var topNode = gTargetNode;
  322.   while (topNode && topNode.localName != topTag)
  323.     topNode = topNode.parentNode;
  324.   if (!topNode)
  325.     return;
  326.  
  327.   // serialize (note: the main window overrides the title set here)
  328.   var wrapClass = gWrapLongLines ? ' class="wrap"' : '';
  329.   var source =
  330.     '<html>'
  331.   + '<head><title>Mozilla</title>'
  332.   + '<link rel="stylesheet" type="text/css" href="' + gViewSourceCSS + '">'
  333.   + '<style type="text/css">'
  334.   + '#target { border: dashed 1px; background-color: lightyellow; }'
  335.   + '</style>'
  336.   + '</head>'
  337.   + '<body id="viewsource"' + wrapClass
  338.   +        ' onload="document.getElementById(\'target\').scrollIntoView(true)">'
  339.   + '<pre>'
  340.   + getOuterMarkup(topNode, 0)
  341.   + '</pre></body></html>'
  342.   ; // end
  343.  
  344.   // display
  345.   var doc = getBrowser().contentDocument;
  346.   doc.open("text/html", "replace");
  347.   doc.write(source);
  348.   doc.close();
  349. }
  350.  
  351. ////////////////////////////////////////////////////////////////////////////////
  352. function getInnerMarkup(node, indent) {
  353.   var str = '';
  354.   for (var i = 0; i < node.childNodes.length; i++) {
  355.     str += getOuterMarkup(node.childNodes.item(i), indent);
  356.   }
  357.   return str;
  358. }
  359.  
  360. ////////////////////////////////////////////////////////////////////////////////
  361. function getOuterMarkup(node, indent) {
  362.   var newline = '';
  363.   var padding = '';
  364.   var str = '';
  365.   if (node == gTargetNode) {
  366.     gStartTargetLine = gLineCount;
  367.     str += '</pre><pre id="target">';
  368.   }
  369.  
  370.   switch (node.nodeType) {
  371.   case Node.ELEMENT_NODE: // Element
  372.     // to avoid the wide gap problem, '\n' is not emitted on the first
  373.     // line and the lines before & after the <pre id="target">...</pre>
  374.     if (gLineCount > 0 &&
  375.         gLineCount != gStartTargetLine &&
  376.         gLineCount != gEndTargetLine) {
  377.       newline = '\n';
  378.     }
  379.     gLineCount++;
  380.     if (gDebug) {
  381.       newline += gLineCount;
  382.     }
  383.     for (var k = 0; k < indent; k++) {
  384.       padding += ' ';
  385.     }
  386.     str += newline + padding
  387.         +  '<<span class="start-tag">' + node.nodeName + '</span>';
  388.     for (var i = 0; i < node.attributes.length; i++) {
  389.       var attr = node.attributes.item(i);
  390.       if (!gDebug && attr.nodeName.match(/^[-_]moz/)) {
  391.         continue;
  392.       }
  393.       str += ' <span class="attribute-name">'
  394.           +  attr.nodeName
  395.           +  '</span>=<span class="attribute-value">"'
  396.           +  unicodeTOentity(attr.nodeValue)
  397.           +  '"</span>';
  398.     }
  399.     if (!node.hasChildNodes()) {
  400.       str += '/>';
  401.     }
  402.     else {
  403.       str += '>';
  404.       var oldLine = gLineCount;
  405.       str += getInnerMarkup(node, indent + 2);
  406.       if (oldLine == gLineCount) {
  407.         newline = '';
  408.         padding = '';
  409.       }
  410.       else {
  411.         newline = (gLineCount == gEndTargetLine) ? '' : '\n';
  412.         gLineCount++;
  413.         if (gDebug) {
  414.           newline += gLineCount;
  415.         }
  416.       }
  417.       str += newline + padding
  418.           +  '</<span class="end-tag">' + node.nodeName + '</span>>';
  419.     }
  420.     break;
  421.   case Node.TEXT_NODE: // Text
  422.     var tmp = node.nodeValue;
  423.     tmp = tmp.replace(/(\n|\r|\t)+/g, " ");
  424.     tmp = tmp.replace(/^ +/, "");
  425.     tmp = tmp.replace(/ +$/, "");
  426.     if (tmp.length != 0) {
  427.       str += '<span class="text">' + unicodeTOentity(tmp) + '</span>';
  428.     }
  429.     break;
  430.   default:
  431.     break;
  432.   }
  433.  
  434.   if (node == gTargetNode) {
  435.     gEndTargetLine = gLineCount;
  436.     str += '</pre><pre>';
  437.   }
  438.   return str;
  439. }
  440.  
  441. ////////////////////////////////////////////////////////////////////////////////
  442. function unicodeTOentity(text)
  443. {
  444.   const charTable = {
  445.     '&': '&<span class="entity">amp;</span>',
  446.     '<': '&<span class="entity">lt;</span>',
  447.     '>': '&<span class="entity">gt;</span>',
  448.     '"': '&<span class="entity">quot;</span>'
  449.   };
  450.  
  451.   function charTableLookup(letter) {
  452.     return charTable[letter];
  453.   }
  454.  
  455.   function convertEntity(letter) {
  456.     try {
  457.       var unichar = gEntityConverter.ConvertToEntity(letter, entityVersion);
  458.       var entity = unichar.substring(1); // extract '&'
  459.       return '&<span class="entity">' + entity + '</span>';
  460.     } catch (ex) {
  461.       return letter;
  462.     }
  463.   }
  464.  
  465.   if (!gEntityConverter) {
  466.     try {
  467.       gEntityConverter =
  468.         Components.classes["@mozilla.org/intl/entityconverter;1"]
  469.                   .createInstance(Components.interfaces.nsIEntityConverter);
  470.     } catch(e) { }
  471.   }
  472.  
  473.   const entityVersion =
  474.     Components.interfaces.nsIEntityConverter.html40 |
  475.     Components.interfaces.nsIEntityConverter.mathml20;
  476.  
  477.   var str = text;
  478.  
  479.   // replace chars in our charTable
  480.   str = str.replace(/[<>&"]/g, charTableLookup);
  481.  
  482.   // replace chars > 0x7f via nsIEntityConverter
  483.   str = str.replace(/[^\0-\u007f]/g, convertEntity);
  484.  
  485.   return str;
  486. }
  487.