home *** CD-ROM | disk | FTP | other *** search
/ PC World 2005 March / PCWorld_2005-03_cd.bin / komunikace / kmeleon / kmeleon09.exe / comm.jar / content / communicator / nsContextMenu.js < prev    next >
Text File  |  2004-02-19  |  44KB  |  990 lines

  1. /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
  2. /*
  3.  * The contents of this file are subject to the Netscape Public
  4.  * License Version 1.1 (the "License"); you may not use this file
  5.  * except in compliance with the License. You may obtain a copy of
  6.  * the License at http://www.mozilla.org/NPL/
  7.  *
  8.  * Software distributed under the License is distributed on an "AS
  9.  * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
  10.  * implied. See the License for the specific language governing
  11.  * rights and limitations under the License.
  12.  *
  13.  * The Original Code is Mozilla Communicator client code,
  14.  * released March 31, 1998.
  15.  *
  16.  * The Initial Developer of the Original Code is Netscape Communications
  17.  * Corporation.  Portions created by Netscape are
  18.  * Copyright (C) 1998 Netscape Communications Corporation. All
  19.  * Rights Reserved.
  20.  *
  21.  * Contributor(s):
  22.  *     William A. ("PowerGUI") Law <law@netscape.com>
  23.  *     Blake Ross <blakeross@telocity.com>
  24.  *     Gervase Markham <gerv@gerv.net>
  25.  */
  26.  
  27. /*------------------------------ nsContextMenu ---------------------------------
  28. |   This JavaScript "class" is used to implement the browser's content-area    |
  29. |   context menu.                                                              |
  30. |                                                                              |
  31. |   For usage, see references to this class in navigator.xul.                  |
  32. |                                                                              |
  33. |   Currently, this code is relatively useless for any other purpose.  In the  |
  34. |   longer term, this code will be restructured to make it more reusable.      |
  35. ------------------------------------------------------------------------------*/
  36. function nsContextMenu( xulMenu ) {
  37.     this.target         = null;
  38.     this.menu           = null;
  39.     this.popupURL       = null;
  40.     this.onTextInput    = false;
  41.     this.onImage        = false;
  42.     this.onLink         = false;
  43.     this.onMailtoLink   = false;
  44.     this.onSaveableLink = false;
  45.     this.onMetaDataItem = false;
  46.     this.onMathML       = false;
  47.     this.link           = false;
  48.     this.inFrame        = false;
  49.     this.hasBGImage     = false;
  50.     this.isTextSelected = false;
  51.     this.inDirList      = false;
  52.     this.shouldDisplay  = true;
  53.  
  54.     // Initialize new menu.
  55.     this.initMenu( xulMenu );
  56. }
  57.  
  58. // Prototype for nsContextMenu "class."
  59. nsContextMenu.prototype = {
  60.     // onDestroy is a no-op at this point.
  61.     onDestroy : function () {
  62.     },
  63.     // Initialize context menu.
  64.     initMenu : function ( popup ) {
  65.         const xulNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
  66.         if ( document.popupNode.namespaceURI == xulNS ) {
  67.           this.shouldDisplay = false;
  68.           return;
  69.         }
  70.         // Save menu.
  71.         this.menu = popup;
  72.  
  73.         // Get contextual info.
  74.         this.setTarget( document.popupNode );
  75.         
  76.         this.isTextSelected = this.isTextSelection();
  77.  
  78.         this.initPopupURL();
  79.  
  80.         // Initialize (disable/remove) menu items.
  81.         this.initItems();
  82.     },
  83.     initItems : function () {
  84.         this.initOpenItems();
  85.         this.initNavigationItems();
  86.         this.initViewItems();
  87.         this.initMiscItems();
  88.         this.initSaveItems();
  89.         this.initClipboardItems();
  90.         this.initMetadataItems();
  91.     },
  92.     initOpenItems : function () {
  93.         var showOpen = this.onSaveableLink || ( this.inDirList && this.onLink );
  94.  
  95.         this.showItem( "context-openlink", showOpen );
  96.         this.showItem( "context-openlinkintab", showOpen );
  97.  
  98.         this.showItem( "context-sep-open", showOpen );
  99.     },
  100.     initNavigationItems : function () {
  101.         // Back determined by canGoBack broadcaster.
  102.         this.setItemAttrFromNode( "context-back", "disabled", "canGoBack" );
  103.  
  104.         // Forward determined by canGoForward broadcaster.
  105.         this.setItemAttrFromNode( "context-forward", "disabled", "canGoForward" );
  106.  
  107.         var showNav = !( this.isTextSelected || this.onLink || this.onImage || this.onTextInput );
  108.         
  109.         this.showItem( "context-back", showNav );
  110.         this.showItem( "context-forward", showNav );
  111.  
  112.         this.showItem( "context-reload", showNav );
  113.         
  114.         this.showItem( "context-stop", showNav );
  115.         this.showItem( "context-sep-stop", showNav );
  116.  
  117.         // XXX: Stop is determined in navigator.js; the canStop broadcaster is broken
  118.         //this.setItemAttrFromNode( "context-stop", "disabled", "canStop" );
  119.     },
  120.     initSaveItems : function () {
  121.         this.showItem( "context-savepage", 
  122.                        !( this.inDirList || this.isTextSelected || this.onTextInput || this.onStandaloneImage ||
  123.                          (this.onLink && this.onImage)));
  124.  
  125.         // Save link depends on whether we're in a link.
  126.         this.showItem( "context-savelink", this.onSaveableLink );
  127.  
  128.         // Save image depends on whether there is one.
  129.         this.showItem( "context-saveimage", this.onImage || this.onStandaloneImage);
  130.         
  131.         this.showItem( "context-sendimage", this.onImage || this.onStandaloneImage);
  132.     },
  133.     initViewItems : function () {
  134.         // View source is always OK, unless in directory listing.
  135.         this.showItem( "context-viewpartialsource-selection", this.isTextSelected && !this.onTextInput );
  136.         this.showItem( "context-viewpartialsource-mathml", this.onMathML && !this.isTextSelected );
  137.  
  138.         var showView = !( this.inDirList || this.onImage || this.isTextSelected || this.onLink || this.onTextInput );
  139.  
  140.         this.showItem( "context-viewsource", showView );
  141.         this.showItem( "context-viewinfo", showView );
  142.  
  143.         this.showItem( "context-sep-properties", !( this.inDirList || this.isTextSelected || this.onTextInput ) );
  144.         // Set As Wallpaper depends on whether an image was clicked on, and only works on Windows.
  145.         var isWin = navigator.appVersion.indexOf("Windows") != -1;
  146.         this.showItem( "context-setWallpaper", isWin && (this.onImage || this.onStandaloneImage));
  147.  
  148.         this.showItem( "context-sep-image", this.onImage || this.onStandaloneImage);
  149.  
  150.         if( isWin && this.onImage )
  151.             // Disable the Set As Wallpaper menu item if we're still trying to load the image
  152.           this.setItemAttr( "context-setWallpaper", "disabled", (("complete" in this.target) && !this.target.complete) ? "true" : null );
  153.  
  154.         this.showItem( "context-fitimage", this.onStandaloneImage && _content.document.imageResizingEnabled );
  155.         if ( this.onStandaloneImage && _content.document.imageResizingEnabled ) {
  156.           this.setItemAttr( "context-fitimage", "disabled", _content.document.imageIsOverflowing ? null : "true");
  157.           this.setItemAttr( "context-fitimage", "checked", _content.document.imageIsResized ? "true" : null);
  158.         }
  159.  
  160.         // View Image depends on whether an image was clicked on.
  161.         this.showItem( "context-viewimage", this.onImage && !this.onStandaloneImage);
  162.  
  163.         // View background image depends on whether there is one.
  164.         this.showItem( "context-viewbgimage", showView && !this.onStandaloneImage);
  165.         this.showItem( "context-sep-viewbgimage", showView && !this.onStandaloneImage);
  166.         this.setItemAttr( "context-viewbgimage", "disabled", this.hasBGImage ? null : "true");
  167.     },
  168.     initMiscItems : function () {
  169.         // Use "Bookmark This Link" if on a link.
  170.         this.showItem( "context-bookmarkpage", !( this.isTextSelected || this.onTextInput || this.onStandaloneImage ) );
  171.         this.showItem( "context-bookmarklink", this.onLink && !this.onMailtoLink );
  172.         this.showItem( "context-searchselect", this.isTextSelected && !this.onTextInput );
  173.         this.showItem( "frame", this.inFrame );
  174.         this.showItem( "frame-sep", this.inFrame );
  175.         var blocking = true;
  176.         if (this.popupURL)
  177.           try {
  178.             const PM = Components.classes["@mozilla.org/PopupWindowManager;1"]
  179.                        .getService(Components.interfaces.nsIPopupWindowManager);
  180.             blocking = PM.testPermission(this.popupURL) ==
  181.                        Components.interfaces.nsIPopupWindowManager.DENY_POPUP;
  182.           } catch (e) {
  183.           }
  184.  
  185.         this.showItem( "popupwindow-reject", this.popupURL && !blocking);
  186.         this.showItem( "popupwindow-allow", this.popupURL && blocking);
  187.         this.showItem( "context-sep-popup", this.popupURL);
  188.     },
  189.     initClipboardItems : function () {
  190.  
  191.         // Copy depends on whether there is selected text.
  192.         // Enabling this context menu item is now done through the global
  193.         // command updating system
  194.         // this.setItemAttr( "context-copy", "disabled", !this.isTextSelected() );
  195.  
  196.         goUpdateGlobalEditMenuItems();
  197.  
  198.         this.showItem( "context-undo", this.onTextInput );
  199.         this.showItem( "context-redo", this.onTextInput );
  200.         this.showItem( "context-sep-undo", this.onTextInput );
  201.         this.showItem( "context-cut", this.onTextInput );
  202.         this.showItem( "context-copy", this.isTextSelected || this.onTextInput);
  203.         this.showItem( "context-paste", this.onTextInput );
  204.         this.showItem( "context-delete", this.onTextInput );
  205.         this.showItem( "context-sep-paste", this.onTextInput );
  206.         this.showItem( "context-selectall", true );
  207.         this.showItem( "context-sep-selectall", this.isTextSelected && !this.onTextInput );
  208.         // In a text area there will be nothing after select all, so we don't want a sep
  209.         // Otherwise, if there's text selected then there are extra menu items
  210.         // (search for selection and view selection source), so we do want a sep
  211.  
  212.         // XXX dr
  213.         // ------
  214.         // nsDocumentViewer.cpp has code to determine whether we're
  215.         // on a link or an image. we really ought to be using that...
  216.  
  217.         // Copy email link depends on whether we're on an email link.
  218.         this.showItem( "context-copyemail", this.onMailtoLink );
  219.  
  220.         // Copy link location depends on whether we're on a link.
  221.         this.showItem( "context-copylink", this.onLink );
  222.         this.showItem( "context-sep-copylink", this.onLink );
  223.  
  224.         // Copy image location depends on whether we're on an image.
  225.         this.showItem( "context-copyimage", this.onImage );
  226.         this.showItem( "context-sep-copyimage", this.onImage );
  227.     },
  228.     initMetadataItems : function () {
  229.         // Show if user clicked on something which has metadata.
  230.         this.showItem( "context-metadata", this.onMetaDataItem );
  231.     },
  232.     // Set various context menu attributes based on the state of the world.
  233.     setTarget : function ( node ) {
  234.         // Initialize contextual info.
  235.         this.onImage    = false;
  236.         this.onStandaloneImage = false;
  237.         this.onMetaDataItem = false;
  238.         this.onTextInput = false;
  239.         this.imageURL   = "";
  240.         this.onLink     = false;
  241.         this.onMathML   = false;
  242.         this.inFrame    = false;
  243.         this.hasBGImage = false;
  244.         this.bgImageURL = "";
  245.  
  246.         // Remember the node that was clicked.
  247.         this.target = node;
  248.  
  249.         // See if the user clicked on an image.
  250.         if ( this.target.nodeType == Node.ELEMENT_NODE ) {
  251.              if ( this.target.localName.toUpperCase() == "IMG" ) {
  252.                 this.onImage = true;
  253.                 this.imageURL = this.target.src;
  254.  
  255.                 var documentType = window._content.document.contentType;
  256.                 if ( documentType.substr(0,6) == "image/" )
  257.                     this.onStandaloneImage = true;
  258.  
  259.                 // Look for image map.
  260.                 var mapName = this.target.getAttribute( "usemap" );
  261.                 if ( mapName ) {
  262.                     // Find map.
  263.                     var map = this.target.ownerDocument.getElementById( mapName.substr(1) );
  264.                     if ( map ) {
  265.                         // Search child <area>s for a match.
  266.                         var areas = map.childNodes;
  267.                         //XXX Client side image maps are too hard for now!
  268.                         areas.length = 0;
  269.                         for ( var i = 0; i < areas.length && !this.onLink; i++ ) {
  270.                             var area = areas[i];
  271.                             if ( area.nodeType == Node.ELEMENT_NODE
  272.                                  &&
  273.                                  area.localName.toUpperCase() == "AREA" ) {
  274.                                 // Get type (rect/circle/polygon/default).
  275.                                 var type = area.getAttribute( "type" );
  276.                                 var coords = this.parseCoords( area );
  277.                                 switch ( type.toUpperCase() ) {
  278.                                     case "RECT":
  279.                                     case "RECTANGLE":
  280.                                         break;
  281.                                     case "CIRC":
  282.                                     case "CIRCLE":
  283.                                         break;
  284.                                     case "POLY":
  285.                                     case "POLYGON":
  286.                                         break;
  287.                                     case "DEFAULT":
  288.                                         // Default matches entire image.
  289.                                         this.onLink = true;
  290.                                         this.link = area;
  291.                                         this.onSaveableLink = this.isLinkSaveable( this.link );
  292.                                         break;
  293.                                 }
  294.                             }
  295.                         }
  296.                     }
  297.                 }
  298.              } else if ( this.target.localName.toUpperCase() == "OBJECT"
  299.                          &&
  300.                          // See if object tag is for an image.
  301.                          this.objectIsImage( this.target ) ) {
  302.                 // This is an image.
  303.                 this.onImage = true;
  304.                 // URL must be constructed.
  305.                 this.imageURL = this.objectImageURL( this.target );
  306.              } else if ( this.target.localName.toUpperCase() == "INPUT") {
  307.                type = this.target.getAttribute("type");
  308.                if(type && type.toUpperCase() == "IMAGE") {
  309.                  this.onImage = true;
  310.                  // Convert src attribute to absolute URL.
  311.                  this.imageURL = this.makeURLAbsolute( this.target.baseURI,
  312.                                                        this.target.src );
  313.                } else /* if (this.target.getAttribute( "type" ).toUpperCase() == "TEXT") */ {
  314.                  this.onTextInput = this.isTargetATextBox(this.target);
  315.                }
  316.             } else if ( this.target.localName.toUpperCase() == "TEXTAREA" ) {
  317.                  this.onTextInput = true;
  318.             } else if ( this.target.localName.toUpperCase() == "HTML" ) {
  319.                // pages with multiple <body>s are lame. we'll teach them a lesson.
  320.                var bodyElt = this.target.ownerDocument.getElementsByTagName("body")[0];
  321.                if ( bodyElt ) {
  322.                  var computedURL = this.getComputedURL( bodyElt, "background-image" );
  323.                  if ( computedURL ) {
  324.                    this.hasBGImage = true;
  325.                    this.bgImageURL = this.makeURLAbsolute( bodyElt.baseURI,
  326.                                                            computedURL );
  327.                  }
  328.                }
  329.             } else if ( "HTTPIndex" in _content &&
  330.                         _content.HTTPIndex instanceof Components.interfaces.nsIHTTPIndex ) {
  331.                 this.inDirList = true;
  332.                 // Bubble outward till we get to an element with URL attribute
  333.                 // (which should be the href).
  334.                 var root = this.target;
  335.                 while ( root && !this.link ) {
  336.                     if ( root.tagName == "tree" ) {
  337.                         // Hit root of tree; must have clicked in empty space;
  338.                         // thus, no link.
  339.                         break;
  340.                     }
  341.                     if ( root.getAttribute( "URL" ) ) {
  342.                         // Build pseudo link object so link-related functions work.
  343.                         this.onLink = true;
  344.                         this.link = { href : root.getAttribute("URL"),
  345.                                       getAttribute: function (attr) {
  346.                                           if (attr == "title") {
  347.                                               return root.firstChild.firstChild.getAttribute("label");
  348.                                           } else {
  349.                                               return "";
  350.                                           }
  351.                                       }
  352.                                     };
  353.                         // If element is a directory, then you can't save it.
  354.                         if ( root.getAttribute( "container" ) == "true" ) {
  355.                             this.onSaveableLink = false;
  356.                         } else {
  357.                             this.onSaveableLink = true;
  358.                         }
  359.                     } else {
  360.                         root = root.parentNode;
  361.                     }
  362.                 }
  363.             }
  364.         }
  365.  
  366.         // We have meta data on images.
  367.         this.onMetaDataItem = this.onImage;
  368.         
  369.         // See if the user clicked on MathML
  370.         const NS_MathML = "http://www.w3.org/1998/Math/MathML";
  371.         if ((this.target.nodeType == Node.TEXT_NODE &&
  372.              this.target.parentNode.namespaceURI == NS_MathML)
  373.              || (this.target.namespaceURI == NS_MathML))
  374.           this.onMathML = true;
  375.  
  376.         // See if the user clicked in a frame.
  377.         if ( this.target.ownerDocument != window._content.document ) {
  378.             this.inFrame = true;
  379.         }
  380.         
  381.         // Bubble out, looking for items of interest
  382.         var elem = this.target;
  383.         while ( elem ) {
  384.             if ( elem.nodeType == Node.ELEMENT_NODE ) {
  385.                 var localname = elem.localName.toUpperCase();
  386.                 
  387.                 // Link?
  388.                 if ( !this.onLink && 
  389.                     ( (localname === "A" && elem.href) ||
  390.                       localname === "AREA" ||
  391.                       localname === "LINK" ||
  392.                       elem.getAttributeNS( "http://www.w3.org/1999/xlink", "type") == "simple" ) ) {
  393.                     // Clicked on a link.
  394.                     this.onLink = true;
  395.                     this.onMetaDataItem = true;
  396.                     // Remember corresponding element.
  397.                     this.link = elem;
  398.                     this.onMailtoLink = this.isLinkType( "mailto:", this.link );
  399.                     // Remember if it is saveable.
  400.                     this.onSaveableLink = this.isLinkSaveable( this.link );
  401.                 }
  402.                 
  403.                 // Text input?
  404.                 if ( !this.onTextInput ) {
  405.                     // Clicked on a link.
  406.                     this.onTextInput = this.isTargetATextBox(elem);
  407.                 }
  408.                 
  409.                 // Metadata item?
  410.                 if ( !this.onMetaDataItem ) {
  411.                     // We currently display metadata on anything which fits
  412.                     // the below test.
  413.                     if ( ( localname === "BLOCKQUOTE" && 'cite' in elem && elem.cite)  ||
  414.                          ( localname === "Q" && 'cite' in elem && elem.cite)           ||
  415.                          ( localname === "TABLE" && 'summary' in elem && elem.summary) ||
  416.                          ( ( localname === "INS" || localname === "DEL" ) &&
  417.                            ( ( 'cite' in elem && elem.cite ) ||
  418.                              ( 'dateTime' in elem && elem.dateTime ) ) )               ||
  419.                          ( 'title' in elem && elem.title )                             ||
  420.                          ( 'lang' in elem && elem.lang ) ) {
  421.                         dump("On metadata item.\n");
  422.                         this.onMetaDataItem = true;
  423.                     }
  424.                 }
  425.  
  426.                 // Background image?  Don't bother if we've already found a 
  427.                 // background image further down the hierarchy.  Otherwise,
  428.                 // we look for the computed background-image style.
  429.                 if ( !this.hasBGImage ) {
  430.                     var bgImgUrl = this.getComputedURL( elem, "background-image" );
  431.                     if ( bgImgUrl ) {
  432.                         this.hasBGImage = true;
  433.                         this.bgImageURL = this.makeURLAbsolute( elem.baseURI,
  434.                                                                 bgImgUrl );
  435.                     }
  436.                 }
  437.             }
  438.             elem = elem.parentNode;    
  439.         }
  440.     },
  441.     initPopupURL: function() {
  442.       // quick check: if no opener, it can't be a popup
  443.       if (!window.content.opener)
  444.         return;
  445.       try {
  446.         var show = false;
  447.         // is it a popup window?
  448.         const CI = Components.interfaces;
  449.         var xulwin = window
  450.                     .QueryInterface(CI.nsIInterfaceRequestor)
  451.                     .getInterface(CI.nsIWebNavigation)
  452.                     .QueryInterface(CI.nsIDocShellTreeItem)
  453.                     .treeOwner
  454.                     .QueryInterface(CI.nsIInterfaceRequestor)
  455.                     .getInterface(CI.nsIXULWindow);
  456.         if (xulwin.contextFlags &
  457.             CI.nsIWindowCreator2.PARENT_IS_LOADING_OR_RUNNING_TIMEOUT) {
  458.           // do the pref settings allow site-by-site popup management?
  459.           const PB = Components.classes["@mozilla.org/preferences-service;1"]
  460.                      .getService(CI.nsIPrefBranch);
  461.           show = !PB.getBoolPref("dom.disable_open_during_load");
  462.         }
  463.         if (show) {
  464.           // initialize popupURL
  465.           const IOS = Components.classes["@mozilla.org/network/io-service;1"]
  466.                       .getService(CI.nsIIOService);
  467.           var spec = Components.lookupMethod(window.content.opener, "location")
  468.                      .call();
  469.           this.popupURL = IOS.newURI(spec, null, null);
  470.  
  471.           // but cancel if it's an unsuitable URL
  472.           const PM = Components.classes["@mozilla.org/PopupWindowManager;1"]
  473.                      .getService(CI.nsIPopupWindowManager);
  474.         }
  475.       } catch(e) {
  476.       }
  477.     },
  478.     // Returns the computed style attribute for the given element.
  479.     getComputedStyle: function( elem, prop ) {
  480.          return elem.ownerDocument.defaultView.getComputedStyle( elem, '' ).getPropertyValue( prop );
  481.     },
  482.     // Returns a "url"-type computed style attribute value, with the url() stripped.
  483.     getComputedURL: function( elem, prop ) {
  484.          var url = elem.ownerDocument.defaultView.getComputedStyle( elem, '' ).getPropertyCSSValue( prop );
  485.          return ( url.primitiveType == CSSPrimitiveValue.CSS_URI ) ? url.getStringValue() : null;
  486.     },
  487.     // Returns true iff clicked on link is saveable.
  488.     isLinkSaveable : function ( link ) {
  489.         // We don't do the Right Thing for news/snews yet, so turn them off
  490.         // until we do.
  491.         return !(this.isLinkType( "mailto:" , link )     ||
  492.                  this.isLinkType( "javascript:" , link ) ||
  493.                  this.isLinkType( "news:", link )        || 
  494.                  this.isLinkType( "snews:", link ) ); 
  495.     },
  496.     // Returns true iff clicked on link is of type given.
  497.     isLinkType : function ( linktype, link ) {        
  498.         try {
  499.             // Test for missing protocol property.
  500.             if ( !link.protocol ) {
  501.                 // We must resort to testing the URL string :-(.
  502.                 var protocol;
  503.                 if ( link.href ) {
  504.                     protocol = link.href.substr( 0, linktype.length );
  505.                 } else {
  506.                     protocol = link.getAttributeNS("http://www.w3.org/1999/xlink","href");
  507.                     if ( protocol ) {
  508.                         protocol = protocol.substr( 0, linktype.length );
  509.                     }
  510.                 }
  511.                 return protocol.toLowerCase() === linktype;        
  512.             } else {
  513.                 // Presume all but javascript: urls are saveable.
  514.                 return link.protocol.toLowerCase() === linktype;
  515.             }
  516.         } catch (e) {
  517.             // something was wrong with the link,
  518.             // so we won't be able to save it anyway
  519.             return false;
  520.         }
  521.     },
  522.     // Block popup windows
  523.     rejectPopupWindows: function(andClose) {
  524.       const PM = Components.classes["@mozilla.org/PopupWindowManager;1"]
  525.                  .getService(Components.interfaces.nsIPopupWindowManager);
  526.       PM.add(this.popupURL, false);
  527.       if (andClose) {
  528.         const OS = Components.classes["@mozilla.org/observer-service;1"]
  529.                    .getService(Components.interfaces.nsIObserverService);
  530.         OS.notifyObservers(window, "popup-perm-close", this.popupURL.spec);
  531.       }
  532.     },
  533.     // Unblock popup windows
  534.     allowPopupWindows: function() {
  535.       const PM = Components.classes["@mozilla.org/PopupWindowManager;1"]
  536.                  .getService(Components.interfaces.nsIPopupWindowManager);
  537.       PM.add(this.popupURL, true);
  538.     },
  539.     // Open linked-to URL in a new window.
  540.     openLink : function () {
  541.         // Determine linked-to URL.
  542.         openNewWindowWith( this.linkURL(), true );
  543.     },
  544.     // Open linked-to URL in a new tab.
  545.     openLinkInTab : function () {
  546.         // Determine linked-to URL.
  547.         openNewTabWith( this.linkURL(), true, false );
  548.     },
  549.     // Open frame in a new tab.
  550.     openFrameInTab : function () {
  551.         // Determine linked-to URL.
  552.         openNewTabWith( this.target.ownerDocument.location.href );
  553.     },
  554.     // Reload clicked-in frame.
  555.     reloadFrame : function () {
  556.         this.target.ownerDocument.location.reload();
  557.     },
  558.     // Open clicked-in frame in its own window.
  559.     openFrame : function () {
  560.         openNewWindowWith( this.target.ownerDocument.location.href );
  561.     },
  562.     // Open clicked-in frame in the same window
  563.     showOnlyThisFrame : function () {
  564.         window.loadURI(this.target.ownerDocument.location.href);
  565.     },
  566.     // View Partial Source
  567.     viewPartialSource : function ( context ) {
  568.         var focusedWindow = document.commandDispatcher.focusedWindow;
  569.         if (focusedWindow == window)
  570.           focusedWindow = _content;
  571.         var docCharset = null;
  572.         if (focusedWindow)
  573.           docCharset = "charset=" + focusedWindow.document.characterSet;
  574.  
  575.         // "View Selection Source" and others such as "View MathML Source"
  576.         // are mutually exclusive, with the precedence given to the selection
  577.         // when there is one
  578.         var reference = null;
  579.         if (context == "selection")
  580.           reference = focusedWindow.__proto__.getSelection.call(focusedWindow);
  581.         else if (context == "mathml")
  582.           reference = this.target;
  583.         else
  584.           throw "not reached";
  585.  
  586.         var docUrl = null; // unused (and play nice for fragments generated via XSLT too)
  587.         window.openDialog("chrome://navigator/content/viewPartialSource.xul",
  588.                           "_blank", "scrollbars,resizable,chrome,dialog=no",
  589.                           docUrl, docCharset, reference, context);
  590.     },
  591.     // Open new "view source" window with the frame's URL.
  592.     viewFrameSource : function () {
  593.         BrowserViewSourceOfDocument(this.target.ownerDocument);
  594.     },
  595.     viewInfo : function () {
  596.         BrowserPageInfo();
  597.     },
  598.     viewFrameInfo : function () {
  599.         BrowserPageInfo(this.target.ownerDocument);
  600.     },
  601.     toggleImageSize : function () {
  602.         _content.document.toggleImageSize();
  603.     },
  604.     // Change current window to the URL of the image.
  605.     viewImage : function () {
  606.         openTopWin( this.imageURL );
  607.     },
  608.     // Change current window to the URL of the background image.
  609.     viewBGImage : function () {
  610.         openTopWin( this.bgImageURL );
  611.     },
  612.     setWallpaper: function() {
  613.       // Confirm since it's annoying if you hit this accidentally.
  614.       var promptService       = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
  615.       var gNavigatorBundle    = document.getElementById("bundle_navigator");
  616.       var promptTitle         = gNavigatorBundle.getString("wallpaperConfirmTitle");
  617.       var promptMsg           = gNavigatorBundle.getString("wallpaperConfirmMsg");
  618.       var promptConfirmButton = gNavigatorBundle.getString("wallpaperConfirmButton");
  619.  
  620.       var buttonPressed = promptService.confirmEx(window, promptTitle, promptMsg,
  621.                                                    (promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0) +
  622.                                                    (promptService.BUTTON_TITLE_CANCEL    * promptService.BUTTON_POS_1),
  623.                                                    promptConfirmButton, null, null, null, {value:0});
  624.  
  625.       if (buttonPressed != 0)
  626.         return;
  627.  
  628.       var winhooks = Components.classes[ "@mozilla.org/winhooks;1" ].
  629.                        getService(Components.interfaces.nsIWindowsHooks);
  630.       
  631.       winhooks.setImageAsWallpaper(this.target, false);
  632.     },    
  633.     // Save URL of clicked-on frame.
  634.     saveFrame : function () {
  635.         saveDocument( this.target.ownerDocument );
  636.     },
  637.     // Save URL of clicked-on link.
  638.     saveLink : function () {
  639.         saveURL( this.linkURL(), this.linkText(), null, true );
  640.     },
  641.     // Save URL of clicked-on image.
  642.     saveImage : function () {
  643.         saveURL( this.imageURL, null, "SaveImageTitle", false );
  644.     },
  645.     // Generate email address and put it on clipboard.
  646.     copyEmail : function () {
  647.         // Copy the comma-separated list of email addresses only.
  648.         // There are other ways of embedding email addresses in a mailto:
  649.         // link, but such complex parsing is beyond us.
  650.         var url = this.linkURL();
  651.         var qmark = url.indexOf( "?" );
  652.         var addresses;
  653.         
  654.         if ( qmark > 7 ) {                   // 7 == length of "mailto:"
  655.             addresses = url.substring( 7, qmark );
  656.         } else {
  657.             addresses = url.substr( 7 );
  658.         }
  659.  
  660.         // Let's try to unescape it using a character set
  661.         // in case the address is not ASCII.
  662.         try {
  663.           var characterSet = Components.lookupMethod(this.target.ownerDocument, "characterSet")
  664.                                        .call(this.target.ownerDocument);
  665.           const textToSubURI = Components.classes["@mozilla.org/intl/texttosuburi;1"]
  666.                                          .getService(Components.interfaces.nsITextToSubURI);
  667.           addresses = textToSubURI.unEscapeNonAsciiURI(characterSet, addresses);
  668.         }
  669.         catch(ex) {
  670.           // Do nothing.
  671.         }
  672.  
  673.         var clipboard = this.getService( "@mozilla.org/widget/clipboardhelper;1",
  674.                                          Components.interfaces.nsIClipboardHelper );
  675.         clipboard.copyString(addresses);
  676.     },    
  677.     addBookmark : function() {
  678.       var docshell = document.getElementById( "content" ).webNavigation;
  679.       BookmarksUtils.addBookmark( docshell.currentURI.spec,
  680.                                   docshell.document.title,
  681.                                   docshell.document.charset,
  682.                                   false );
  683.     },
  684.     addBookmarkForFrame : function() {
  685.       var doc = this.target.ownerDocument;
  686.       var uri = doc.location.href;
  687.       var title = doc.title;
  688.       if ( !title )
  689.         title = uri;
  690.       BookmarksUtils.addBookmark( uri,
  691.                                   title,
  692.                                   doc.charset,
  693.                                   false );
  694.     },
  695.     // Open Metadata window for node
  696.     showMetadata : function () {
  697.         window.openDialog(  "chrome://navigator/content/metadata.xul",
  698.                             "_blank",
  699.                             "scrollbars,resizable,chrome,dialog=no",
  700.                             this.target);
  701.     },
  702.  
  703.     ///////////////
  704.     // Utilities //
  705.     ///////////////
  706.  
  707.     // Create instance of component given contractId and iid (as string).
  708.     createInstance : function ( contractId, iidName ) {
  709.         var iid = Components.interfaces[ iidName ];
  710.         return Components.classes[ contractId ].createInstance( iid );
  711.     },
  712.     // Get service given contractId and iid (as string).
  713.     getService : function ( contractId, iidName ) {
  714.         var iid = Components.interfaces[ iidName ];
  715.         return Components.classes[ contractId ].getService( iid );
  716.     },
  717.     // Show/hide one item (specified via name or the item element itself).
  718.     showItem : function ( itemOrId, show ) {
  719.         var item = itemOrId.constructor == String ? document.getElementById(itemOrId) : itemOrId;
  720.         if (item) 
  721.           item.hidden = !show;
  722.     },
  723.     // Set given attribute of specified context-menu item.  If the
  724.     // value is null, then it removes the attribute (which works
  725.     // nicely for the disabled attribute).
  726.     setItemAttr : function ( id, attr, val ) {
  727.         var elem = document.getElementById( id );
  728.         if ( elem ) {
  729.             if ( val == null ) {
  730.                 // null indicates attr should be removed.
  731.                 elem.removeAttribute( attr );
  732.             } else {
  733.                 // Set attr=val.
  734.                 elem.setAttribute( attr, val );
  735.             }
  736.         }
  737.     },
  738.     // Set context menu attribute according to like attribute of another node
  739.     // (such as a broadcaster).
  740.     setItemAttrFromNode : function ( item_id, attr, other_id ) {
  741.         var elem = document.getElementById( other_id );
  742.         if ( elem && elem.getAttribute( attr ) == "true" ) {
  743.             this.setItemAttr( item_id, attr, "true" );
  744.         } else {
  745.             this.setItemAttr( item_id, attr, null );
  746.         }
  747.     },
  748.     // Temporary workaround for DOM api not yet implemented by XUL nodes.
  749.     cloneNode : function ( item ) {
  750.         // Create another element like the one we're cloning.
  751.         var node = document.createElement( item.tagName );
  752.  
  753.         // Copy attributes from argument item to the new one.
  754.         var attrs = item.attributes;
  755.         for ( var i = 0; i < attrs.length; i++ ) {
  756.             var attr = attrs.item( i );
  757.             node.setAttribute( attr.nodeName, attr.nodeValue );
  758.         }
  759.  
  760.         // Voila!
  761.         return node;
  762.     },
  763.     // Generate fully-qualified URL for clicked-on link.
  764.     linkURL : function () {
  765.         if (this.link.href) {
  766.           return this.link.href;
  767.         }
  768.         var href = this.link.getAttributeNS("http://www.w3.org/1999/xlink","href");
  769.         if (!href || !href.match(/\S/)) {
  770.           throw "Empty href"; // Without this we try to save as the current doc, for example, HTML case also throws if empty
  771.         }
  772.         href = this.makeURLAbsolute(this.link.baseURI,href);
  773.         return href;
  774.     },
  775.     // Get text of link.
  776.     linkText : function () {
  777.         var text = gatherTextUnder( this.link );
  778.         if (!text || !text.match(/\S/)) {
  779.           text = this.link.getAttribute("title");
  780.           if (!text || !text.match(/\S/)) {
  781.             text = this.link.getAttribute("alt");
  782.             if (!text || !text.match(/\S/)) {
  783.               if (this.link.href) {                
  784.                 text = this.link.href;
  785.               } else {
  786.                 text = getAttributeNS("http://www.w3.org/1999/xlink", "href");
  787.                 if (text && text.match(/\S/)) {
  788.                   text = this.makeURLAbsolute(this.link.baseURI, text);
  789.                 }
  790.               }
  791.             }
  792.           }
  793.         }
  794.  
  795.         return text;
  796.     },
  797.  
  798.     //Get selected object and convert it to a string to get
  799.     //selected text.   Only use the first 15 chars.
  800.     isTextSelection : function() {
  801.         var result = false;
  802.         var selection = this.searchSelected(16);
  803.  
  804.         var bundle = srGetStrBundle("chrome://communicator/locale/contentAreaCommands.properties");
  805.  
  806.         var searchSelectText;
  807.         if (selection != "") {
  808.             searchSelectText = selection.toString();
  809.             if (searchSelectText.length > 15)
  810.                 searchSelectText = searchSelectText.substr(0,15) + "...";
  811.             result = true;
  812.  
  813.           // format "Search for <selection>" string to show in menu
  814.           searchSelectText = bundle.formatStringFromName("searchText",
  815.                                                          [searchSelectText], 1);
  816.           this.setItemAttr("context-searchselect", "label", searchSelectText);
  817.         } 
  818.         return result;
  819.     },
  820.     
  821.     searchSelected : function( charlen ) {
  822.         var focusedWindow = document.commandDispatcher.focusedWindow;
  823.         var searchStr = focusedWindow.__proto__.getSelection.call(focusedWindow);
  824.         searchStr = searchStr.toString();
  825.         // searching for more than 150 chars makes no sense
  826.         if (!charlen)
  827.             charlen = 150;
  828.         if (charlen < searchStr.length) {
  829.             // only use the first charlen important chars. see bug 221361
  830.             var pattern = new RegExp("^(?:\\s*.){0," + charlen + "}");
  831.             pattern.test(searchStr);
  832.             searchStr = RegExp.lastMatch;
  833.         }
  834.         searchStr = searchStr.replace(/\s*(.*?)\s*$/, "$1");
  835.         searchStr = searchStr.replace(/\s+/g, " ");
  836.         return searchStr;
  837.     },
  838.     
  839.     // Determine if target <object> is an image.
  840.     objectIsImage : function ( objElem ) {
  841.         var result = false;
  842.         // Get type and data attributes.
  843.         var type = objElem.getAttribute( "type" );
  844.         var data = objElem.getAttribute( "data" );
  845.         // Presume any mime type of the form "image/..." is an image.
  846.         // There must be a data= attribute with an URL, also.
  847.         if ( type.substring( 0, 6 ) == "image/" && data && data != "" ) {
  848.             result = true;
  849.         }
  850.         return result;
  851.     },
  852.     // Extract image URL from <object> tag.
  853.     objectImageURL : function ( objElem ) {
  854.         // Extract url from data= attribute.
  855.         var data = objElem.getAttribute( "data" );
  856.         // Make it absolute.
  857.         return this.makeURLAbsolute( objElem.baseURI, data );
  858.     },
  859.     // Convert relative URL to absolute, using document's <base>.
  860.     makeURLAbsolute : function ( base, url ) {
  861.         // Construct nsIURL.
  862.         var ioService = Components.classes["@mozilla.org/network/io-service;1"]
  863.                       .getService(Components.interfaces.nsIIOService);
  864.         var baseURI  = ioService.newURI(base, null, null);
  865.         
  866.         return ioService.newURI(baseURI.resolve(url), null, null).spec;
  867.     },
  868.     // Parse coords= attribute and return array.
  869.     parseCoords : function ( area ) {
  870.         return [];
  871.     },
  872.     toString : function () {
  873.         return "contextMenu.target     = " + this.target + "\n" +
  874.                "contextMenu.onImage    = " + this.onImage + "\n" +
  875.                "contextMenu.onLink     = " + this.onLink + "\n" +
  876.                "contextMenu.link       = " + this.link + "\n" +
  877.                "contextMenu.inFrame    = " + this.inFrame + "\n" +
  878.                "contextMenu.hasBGImage = " + this.hasBGImage + "\n";
  879.     },
  880.     isTargetATextBox : function ( node )
  881.     {
  882.       if (node.nodeType != Node.ELEMENT_NODE)
  883.         return false;
  884.  
  885.       if (node.localName.toUpperCase() == "INPUT") {
  886.         var attrib = "";
  887.         var type = node.getAttribute("type");
  888.  
  889.         if (type)
  890.           attrib = type.toUpperCase();
  891.  
  892.         return( (attrib != "IMAGE") &&
  893.                 (attrib != "CHECKBOX") &&
  894.                 (attrib != "RADIO") &&
  895.                 (attrib != "SUBMIT") &&
  896.                 (attrib != "RESET") &&
  897.                 (attrib != "HIDDEN") &&
  898.                 (attrib != "RESET") &&
  899.                 (attrib != "BUTTON") );
  900.       } else  {
  901.         return(node.localName.toUpperCase() == "TEXTAREA");
  902.       }
  903.     },
  904.     
  905.     // Determines whether or not the separator with the specified ID should be 
  906.     // shown or not by determining if there are any non-hidden items between it
  907.     // and the previous separator. 
  908.     shouldShowSeparator : function ( aSeparatorID )
  909.     {
  910.       var separator = document.getElementById(aSeparatorID);
  911.       if (separator) {
  912.         var sibling = separator.previousSibling;
  913.         while (sibling && sibling.localName != "menuseparator") {
  914.           if (sibling.getAttribute("hidden") != "true")
  915.             return true;
  916.           sibling = sibling.previousSibling;
  917.         }
  918.       }
  919.       return false;  
  920.     }
  921. };
  922.  
  923. /*************************************************************************
  924.  *
  925.  *   nsDefaultEngine : nsIObserver
  926.  *
  927.  *************************************************************************/
  928. function nsDefaultEngine()
  929. {
  930.     try
  931.     {
  932.         var pb = Components.classes["@mozilla.org/preferences-service;1"].
  933.                    getService(Components.interfaces.nsIPrefBranch);
  934.         var pbi = pb.QueryInterface(
  935.                     Components.interfaces.nsIPrefBranchInternal);
  936.         pbi.addObserver(this.domain, this, false);
  937.  
  938.         // reuse code by explicitly invoking initial |observe| call
  939.         // to initialize the |icon| and |name| member variables
  940.         this.observe(pb, "", this.domain);
  941.     }
  942.     catch (ex)
  943.     {
  944.     }
  945. }
  946.  
  947. nsDefaultEngine.prototype = 
  948. {
  949.     name: "",
  950.     icon: "",
  951.     domain: "browser.search.defaultengine",
  952.  
  953.     // nsIObserver implementation
  954.     observe: function(aPrefBranch, aTopic, aPrefName)
  955.     {
  956.         try
  957.         {
  958.             var rdf = Components.
  959.                         classes["@mozilla.org/rdf/rdf-service;1"].
  960.                         getService(Components.interfaces.nsIRDFService);
  961.             var ds = rdf.GetDataSource("rdf:internetsearch");
  962.             var defaultEngine = aPrefBranch.getCharPref(aPrefName);
  963.             var res = rdf.GetResource(defaultEngine);
  964.  
  965.             // get engine ``pretty'' name
  966.             const kNC_Name = rdf.GetResource(
  967.                                "http://home.netscape.com/NC-rdf#Name");
  968.             var engineName = ds.GetTarget(res, kNC_Name, true);
  969.             if (engineName)
  970.             {
  971.                 this.name = engineName.QueryInterface(
  972.                               Components.interfaces.nsIRDFLiteral).Value;
  973.             }
  974.  
  975.             // get URL to engine vendor icon
  976.             const kNC_Icon = rdf.GetResource(
  977.                                "http://home.netscape.com/NC-rdf#Icon");
  978.             var iconURL = ds.GetTarget(res, kNC_Icon, true);
  979.             if (iconURL)
  980.             {
  981.                 this.icon = iconURL.QueryInterface(
  982.                   Components.interfaces.nsIRDFLiteral).Value;
  983.             }
  984.         }
  985.         catch (ex)
  986.         {
  987.         }
  988.     }
  989. }
  990.