home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / firefox / components / nsHelperAppDlg.js < prev    next >
Encoding:
JavaScript  |  2007-04-03  |  37.5 KB  |  978 lines

  1. /*
  2. //@line 42 "/build/buildd/firefox-2.0.0.3+1/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  3. */
  4.  
  5. /* This file implements the nsIHelperAppLauncherDialog interface.
  6.  *
  7.  * The implementation consists of a JavaScript "class" named nsUnknownContentTypeDialog,
  8.  * comprised of:
  9.  *   - a JS constructor function
  10.  *   - a prototype providing all the interface methods and implementation stuff
  11.  *
  12.  * In addition, this file implements an nsIModule object that registers the
  13.  * nsUnknownContentTypeDialog component.
  14.  */
  15.  
  16.  
  17. /* ctor
  18.  */
  19. function nsUnknownContentTypeDialog() {
  20.     // Initialize data properties.
  21.     this.mLauncher = null;
  22.     this.mContext  = null;
  23.     this.mSourcePath = null;
  24.     this.chosenApp = null;
  25.     this.givenDefaultApp = false;
  26.     this.updateSelf = true;
  27.     this.mTitle    = "";
  28. }
  29.  
  30. nsUnknownContentTypeDialog.prototype = {
  31.     nsIMIMEInfo  : Components.interfaces.nsIMIMEInfo,
  32.  
  33.     // This "class" supports nsIHelperAppLauncherDialog, and nsISupports.
  34.     QueryInterface: function (iid) {
  35.         if (!iid.equals(Components.interfaces.nsIHelperAppLauncherDialog) &&
  36.             !iid.equals(Components.interfaces.nsISupports)) {
  37.             throw Components.results.NS_ERROR_NO_INTERFACE;
  38.         }
  39.         return this;
  40.     },
  41.  
  42.     // ---------- nsIHelperAppLauncherDialog methods ----------
  43.  
  44.     // show: Open XUL dialog using window watcher.  Since the dialog is not
  45.     //       modal, it needs to be a top level window and the way to open
  46.     //       one of those is via that route).
  47.     show: function(aLauncher, aContext, aReason)  {
  48.       this.mLauncher = aLauncher;
  49.       this.mContext  = aContext;
  50.       // Display the dialog using the Window Watcher interface.
  51.       
  52.       var ir = aContext.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
  53.       var dwi = ir.getInterface(Components.interfaces.nsIDOMWindowInternal);
  54.       var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  55.                 .getService(Components.interfaces.nsIWindowWatcher);
  56.       this.mDialog = ww.openWindow(dwi,
  57.                                    "chrome://mozapps/content/downloads/unknownContentType.xul",
  58.                                    null,
  59.                                    "chrome,centerscreen,titlebar,dialog=yes,dependent",
  60.                                    null);
  61.       // Hook this object to the dialog.
  62.       this.mDialog.dialog = this;
  63.       
  64.       // Hook up utility functions. 
  65.       this.getSpecialFolderKey = this.mDialog.getSpecialFolderKey;
  66.       
  67.       // Watch for error notifications.
  68.       this.progressListener.helperAppDlg = this;
  69.       this.mLauncher.setWebProgressListener(this.progressListener);
  70.     },
  71.  
  72.     // promptForSaveToFile:  Display file picker dialog and return selected file.
  73.     //                       This is called by the External Helper App Service
  74.     //                       after the ucth dialog calls |saveToDisk| with a null
  75.     //                       target filename (no target, therefore user must pick).
  76.     //
  77.     //                       Alternatively, if the user has selected to have all
  78.     //                       files download to a specific location, return that
  79.     //                       location and don't ask via the dialog. 
  80.     //
  81.     // Note - this function is called without a dialog, so it cannot access any part
  82.     // of the dialog XUL as other functions on this object do. 
  83.     promptForSaveToFile: function(aLauncher, aContext, aDefaultFile, aSuggestedFileExtension) {
  84.       var result = "";
  85.       
  86.       this.mLauncher = aLauncher;
  87.  
  88.       // If the user is always downloading to the same location, the default download
  89.       // folder is stored in preferences. If a value is found stored, use that 
  90.       // automatically and don't ask via a dialog. 
  91.       var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  92.       var autodownload = prefs.getBoolPref("browser.download.useDownloadDir");
  93.       if (autodownload) {
  94.         function getSpecialFolderKey(aFolderType) 
  95.         {
  96.           if (aFolderType == "Desktop")
  97.             return "Desk";
  98.         
  99.           if (aFolderType != "Downloads")
  100.             throw "ASSERTION FAILED: folder type should be 'Desktop' or 'Downloads'";
  101.         
  102. //@line 147 "/build/buildd/firefox-2.0.0.3+1/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  103.           return "Home";
  104. //@line 150 "/build/buildd/firefox-2.0.0.3+1/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  105.         }
  106.         
  107.         function getDownloadsFolder(aFolder)
  108.         {
  109.           var fileLocator = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties);
  110.  
  111.           var dir = fileLocator.get(getSpecialFolderKey(aFolder), Components.interfaces.nsILocalFile);
  112.           
  113.           var bundle = Components.classes["@mozilla.org/intl/stringbundle;1"].getService(Components.interfaces.nsIStringBundleService);
  114.           bundle = bundle.createBundle("chrome://mozapps/locale/downloads/unknownContentType.properties");
  115.  
  116.           var description = bundle.GetStringFromName("myDownloads");
  117.           if (aFolder != "Desktop")
  118.             dir.append(description);
  119.             
  120.           return dir;
  121.         }
  122.  
  123.         var defaultFolder = null;
  124.         switch (prefs.getIntPref("browser.download.folderList")) {
  125.         case 0:
  126.           defaultFolder = getDownloadsFolder("Desktop");
  127.           break;
  128.         case 1:
  129.           defaultFolder = getDownloadsFolder("Downloads");
  130.           break;
  131.         case 2:
  132.           defaultFolder = prefs.getComplexValue("browser.download.dir", Components.interfaces.nsILocalFile);
  133.           break;
  134.         }
  135.         
  136.         result = this.validateLeafName(defaultFolder, aDefaultFile, aSuggestedFileExtension);
  137.       }
  138.       
  139.       if (!result) {
  140.         // Use file picker to show dialog.
  141.         var nsIFilePicker = Components.interfaces.nsIFilePicker;
  142.         var picker = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  143.  
  144.         var bundle = Components.classes["@mozilla.org/intl/stringbundle;1"].getService(Components.interfaces.nsIStringBundleService);
  145.         bundle = bundle.createBundle("chrome://mozapps/locale/downloads/unknownContentType.properties");
  146.  
  147.         var windowTitle = bundle.GetStringFromName("saveDialogTitle");
  148.         var parent = aContext.QueryInterface(Components.interfaces.nsIInterfaceRequestor).getInterface(Components.interfaces.nsIDOMWindowInternal);
  149.         picker.init(parent, windowTitle, nsIFilePicker.modeSave);
  150.         picker.defaultString = aDefaultFile;
  151.  
  152.         if (aSuggestedFileExtension) {
  153.           // aSuggestedFileExtension includes the period, so strip it
  154.           picker.defaultExtension = aSuggestedFileExtension.substring(1);
  155.         } 
  156.         else {
  157.           try {
  158.             picker.defaultExtension = this.mLauncher.MIMEInfo.primaryExtension;
  159.           } 
  160.           catch (ex) { }
  161.         }
  162.  
  163.         var wildCardExtension = "*";
  164.         if (aSuggestedFileExtension) {
  165.           wildCardExtension += aSuggestedFileExtension;
  166.           picker.appendFilter(this.mLauncher.MIMEInfo.description, wildCardExtension);
  167.         }
  168.  
  169.         picker.appendFilters( nsIFilePicker.filterAll );
  170.  
  171.         // Pull in the user's preferences and get the default download directory.
  172.         var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  173.         try {
  174.           var startDir = prefs.getComplexValue("browser.download.dir", Components.interfaces.nsILocalFile);
  175.           if (startDir.exists()) {
  176.             picker.displayDirectory = startDir;
  177.           }
  178.         } 
  179.         catch(exception) { }
  180.  
  181.         var dlgResult = picker.show();
  182.  
  183.         if (dlgResult == nsIFilePicker.returnCancel) {
  184.           // null result means user cancelled.
  185.           return null;
  186.         }
  187.  
  188.  
  189.         // Be sure to save the directory the user chose through the Save As... 
  190.         // dialog  as the new browser.download.dir
  191.         result = picker.file;
  192.  
  193.         if (result) {
  194.           try {
  195.             // Remove the file so that it's not there when we ensure non-existence later;
  196.             // this is safe because for the file to exist, the user would have had to
  197.             // confirm that he wanted the file overwritten.
  198.             if (result.exists())
  199.               result.remove(false);
  200.           }
  201.           catch (e) { }
  202.           var newDir = result.parent;
  203.           prefs.setComplexValue("browser.download.dir", Components.interfaces.nsILocalFile, newDir);
  204.           result = this.validateLeafName(newDir, result.leafName, null);
  205.         }
  206.       }
  207.       return result;
  208.     },
  209.  
  210.     /**
  211.      * Ensures that a local folder/file combination does not already exist in
  212.      * the file system (or finds such a combination with a reasonably similar
  213.      * leaf name), creates the corresponding file, and returns it.
  214.      *
  215.      * @param   aLocalFile
  216.      *          the folder where the file resides
  217.      * @param   aLeafName
  218.      *          the string name of the file (may be empty if no name is known,
  219.      *          in which case a name will be chosen)
  220.      * @param   aFileExt
  221.      *          the extension of the file, if one is known; this will be ignored
  222.      *          if aLeafName is non-empty
  223.      * @returns nsILocalFile
  224.      *          the created file
  225.      */
  226.     validateLeafName: function (aLocalFile, aLeafName, aFileExt)
  227.     {
  228.       if (!aLocalFile || !aLocalFile.exists())
  229.         return null;
  230.  
  231.       if (aLeafName == "")
  232.         aLeafName = "unnamed" + (aFileExt ? "." + aFileExt : "");
  233.       aLocalFile.append(aLeafName);
  234.  
  235.       this.makeFileUnique(aLocalFile);
  236.  
  237.       if (aLocalFile.isExecutable() && !this.mLauncher.targetFile.isExecutable()) {
  238.         var f = aLocalFile.clone();
  239.         aLocalFile.leafName = aLocalFile.leafName + "." + this.mLauncher.MIMEInfo.primaryExtension; 
  240.  
  241.         f.remove(false);
  242.         this.makeFileUnique(aLocalFile);
  243.       }
  244.       return aLocalFile;
  245.     },
  246.  
  247.     /**
  248.      * Generates and returns a uniquely-named file from aLocalFile.  If
  249.      * aLocalFile does not exist, it will be the file returned; otherwise, a
  250.      * file whose name is similar to that of aLocalFile will be returned.
  251.      */
  252.     makeFileUnique: function (aLocalFile)
  253.     {
  254.       try {
  255.         // Note - this code is identical to that in 
  256.         //   toolkit/content/contentAreaUtils.js.
  257.         // If you are updating this code, update that code too! We can't share code
  258.         // here since this is called in a js component. 
  259.         var collisionCount = 0;
  260.         while (aLocalFile.exists()) {
  261.           collisionCount++;
  262.           if (collisionCount == 1) {
  263.             // Append "(2)" before the last dot in (or at the end of) the filename
  264.             // special case .ext.gz etc files so we don't wind up with .tar(2).gz
  265.             if (aLocalFile.leafName.match(/\.[^\.]{1,3}\.(gz|bz2|Z)$/i)) {
  266.               aLocalFile.leafName = aLocalFile.leafName.replace(/\.[^\.]{1,3}\.(gz|bz2|Z)$/i, "(2)$&");
  267.             }
  268.             else {
  269.               aLocalFile.leafName = aLocalFile.leafName.replace(/(\.[^\.]*)?$/, "(2)$&");
  270.             }
  271.           }
  272.           else {
  273.             // replace the last (n) in the filename with (n+1)
  274.             aLocalFile.leafName = aLocalFile.leafName.replace(/^(.*\()\d+\)/, "$1" + (collisionCount+1) + ")");
  275.           }
  276.         }
  277.         aLocalFile.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0600);
  278.       }
  279.       catch (e) {
  280.         dump("*** exception in validateLeafName: " + e + "\n");
  281.         if (aLocalFile.leafName == "" || aLocalFile.isDirectory()) {
  282.           aLocalFile.append("unnamed");
  283.           if (aLocalFile.exists())
  284.             aLocalFile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0600);
  285.         }
  286.       }
  287.     },
  288.     
  289.     // ---------- implementation methods ----------
  290.  
  291.     // Web progress listener so we can detect errors while mLauncher is
  292.     // streaming the data to a temporary file.
  293.     progressListener: {
  294.         // Implementation properties.
  295.         helperAppDlg: null,
  296.  
  297.         // nsIWebProgressListener methods.
  298.         // Look for error notifications and display alert to user.
  299.         onStatusChange: function( aWebProgress, aRequest, aStatus, aMessage ) {
  300.             if ( aStatus != Components.results.NS_OK ) {
  301.                 // Get prompt service.
  302.                 var prompter = Components.classes[ "@mozilla.org/embedcomp/prompt-service;1" ]
  303.                                    .getService( Components.interfaces.nsIPromptService );
  304.                 // Display error alert (using text supplied by back-end).
  305.                 prompter.alert( this.dialog, this.helperAppDlg.mTitle, aMessage );
  306.  
  307.                 // Close the dialog.
  308.                 this.helperAppDlg.onCancel();
  309.                 if ( this.helperAppDlg.mDialog ) {
  310.                     this.helperAppDlg.mDialog.close();
  311.                 }
  312.             }
  313.         },
  314.  
  315.         // Ignore onProgressChange, onStateChange, onLocationChange, and onSecurityChange notifications.
  316.         onProgressChange: function( aWebProgress,
  317.                                     aRequest,
  318.                                     aCurSelfProgress,
  319.                                     aMaxSelfProgress,
  320.                                     aCurTotalProgress,
  321.                                     aMaxTotalProgress ) {
  322.         },
  323.  
  324.         onProgressChange64: function( aWebProgress,
  325.                                       aRequest,
  326.                                       aCurSelfProgress,
  327.                                       aMaxSelfProgress,
  328.                                       aCurTotalProgress,
  329.                                       aMaxTotalProgress ) {
  330.         },
  331.  
  332.  
  333.  
  334.         onStateChange: function( aWebProgress, aRequest, aStateFlags, aStatus ) {
  335.         },
  336.  
  337.         onLocationChange: function( aWebProgress, aRequest, aLocation ) {
  338.         },
  339.  
  340.         onSecurityChange: function( aWebProgress, aRequest, state ) {
  341.         }
  342.     },
  343.  
  344.     // initDialog:  Fill various dialog fields with initial content.
  345.     initDialog : function() {
  346.       // Put file name in window title.
  347.       var suggestedFileName = this.mLauncher.suggestedFileName;
  348.  
  349.       // Some URIs do not implement nsIURL, so we can't just QI.
  350.       var url   = this.mLauncher.source;
  351.       var fname = "";
  352.       this.mSourcePath = url.prePath;
  353.       try {
  354.           url = url.QueryInterface( Components.interfaces.nsIURL );
  355.           // A url, use file name from it.
  356.           fname = url.fileName;
  357.           this.mSourcePath += url.directory;
  358.       } catch (ex) {
  359.           // A generic uri, use path.
  360.           fname = url.path;
  361.           this.mSourcePath += url.path;
  362.       }
  363.  
  364.       if (suggestedFileName)
  365.         fname = suggestedFileName;
  366.       
  367.       var displayName = fname.replace(/ +/g, " ");
  368.  
  369.       this.mTitle = this.dialogElement("strings").getFormattedString("title", [displayName]);
  370.       this.mDialog.document.title = this.mTitle;
  371.  
  372.       // Put content type, filename and location into intro.
  373.       this.initIntro(url, fname, displayName);
  374.  
  375.       var iconString = "moz-icon://" + fname + "?size=16&contentType=" + this.mLauncher.MIMEInfo.MIMEType;
  376.       this.dialogElement("contentTypeImage").setAttribute("src", iconString);
  377.  
  378.       // if always-save and is-executable and no-handler
  379.       // then set up simple ui
  380.       var mimeType = this.mLauncher.MIMEInfo.MIMEType;
  381.       var shouldntRememberChoice = (mimeType == "application/octet-stream" || 
  382.                                     mimeType == "application/x-msdownload" ||
  383.                                     this.mLauncher.targetFile.isExecutable());
  384.       if (shouldntRememberChoice && !this.openWithDefaultOK()) {
  385.         // hide featured choice 
  386.         this.mDialog.document.getElementById("normalBox").collapsed = true;
  387.         // show basic choice 
  388.         this.mDialog.document.getElementById("basicBox").collapsed = false;
  389.         // change button labels
  390.         this.mDialog.document.documentElement.getButton("accept").label = this.dialogElement("strings").getString("unknownAccept.label");
  391.         this.mDialog.document.documentElement.getButton("cancel").label = this.dialogElement("strings").getString("unknownCancel.label");
  392.         // hide other handler
  393.         this.mDialog.document.getElementById("openHandler").collapsed = true;
  394.         // set save as the selected option
  395.         this.dialogElement("mode").selectedItem = this.dialogElement("save");
  396.       }
  397.       else {
  398.         this.initAppAndSaveToDiskValues();
  399.  
  400.         // Initialize "always ask me" box. This should always be disabled
  401.         // and set to true for the ambiguous type application/octet-stream.
  402.         // We don't also check for application/x-msdownload here since we
  403.         // want users to be able to autodownload .exe files. 
  404.         var rememberChoice = this.dialogElement("rememberChoice");
  405.  
  406. //@line 471 "/build/buildd/firefox-2.0.0.3+1/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  407.         if (shouldntRememberChoice) {
  408.           rememberChoice.checked = false;
  409.           rememberChoice.disabled = true;
  410.         }
  411.         else {
  412.           rememberChoice.checked = !this.mLauncher.MIMEInfo.alwaysAskBeforeHandling;
  413.         }
  414.         this.toggleRememberChoice(rememberChoice);
  415.  
  416.         // XXXben - menulist won't init properly, hack. 
  417.         var openHandler = this.dialogElement("openHandler");
  418.         openHandler.parentNode.removeChild(openHandler);
  419.         var openHandlerBox = this.dialogElement("openHandlerBox");
  420.         openHandlerBox.appendChild(openHandler);
  421.       }
  422.  
  423.       this.mDialog.setTimeout("dialog.postShowCallback()", 0);
  424.       
  425.       this.mDialog.document.documentElement.getButton("accept").disabled = true;
  426.       const nsITimer = Components.interfaces.nsITimer;
  427.       this._timer = Components.classes["@mozilla.org/timer;1"]
  428.                               .createInstance(nsITimer);
  429.       this._timer.initWithCallback(this, 250, nsITimer.TYPE_ONE_SHOT);
  430.     },
  431.     
  432.     _timer: null,
  433.     notify: function (aTimer) {
  434.       try { // The user may have already canceled the dialog.
  435.         if (!this._blurred)
  436.           this.mDialog.document.documentElement.getButton('accept').disabled = false;
  437.       } catch (ex) {}
  438.       this._delayExpired = true;
  439.       this._timer = null; // the timer won't release us, so we have to release it
  440.     },
  441.     
  442.     postShowCallback: function () {
  443.       this.mDialog.sizeToContent();
  444.  
  445.       // Set initial focus
  446.       this.dialogElement("mode").focus();
  447.     },
  448.  
  449.     // initIntro:
  450.     initIntro: function(url, filename, displayname) {
  451.         this.dialogElement( "location" ).value = displayname;
  452.         this.dialogElement( "location" ).setAttribute("realname", filename);
  453.         this.dialogElement( "location" ).setAttribute("tooltiptext", displayname);
  454.  
  455.         // if mSourcePath is a local file, then let's use the pretty path name instead of an ugly
  456.         // url...
  457.         var pathString = this.mSourcePath;
  458.         try 
  459.         {
  460.           var fileURL = url.QueryInterface(Components.interfaces.nsIFileURL);
  461.           if (fileURL)
  462.           {
  463.             var fileObject = fileURL.file;
  464.             if (fileObject)
  465.             {
  466.               var parentObject = fileObject.parent;
  467.               if (parentObject)
  468.               {
  469.                 pathString = parentObject.path;
  470.               }
  471.             }
  472.           }
  473.         } catch(ex) {}
  474.  
  475.         if (pathString == this.mSourcePath)
  476.         {
  477.           // wasn't a fileURL
  478.           var tmpurl = url.clone(); // don't want to change the real url
  479.           try {
  480.             tmpurl.userPass = "";
  481.           } catch (ex) {}
  482.           pathString = tmpurl.prePath;
  483.         }
  484.  
  485.         // Set the location text, which is separate from the intro text so it can be cropped
  486.         var location = this.dialogElement( "source" );
  487.         location.value = pathString;
  488.         location.setAttribute("tooltiptext", this.mSourcePath);
  489.         
  490.         // Show the type of file. 
  491.         var type = this.dialogElement("type");
  492.         var mimeInfo = this.mLauncher.MIMEInfo;
  493.         
  494.         // 1. Try to use the pretty description of the type, if one is available.
  495.         var typeString = mimeInfo.description;
  496.         
  497.         if (typeString == "") {
  498.           // 2. If there is none, use the extension to identify the file, e.g. "ZIP file"
  499.           var primaryExtension = "";
  500.           try {
  501.             primaryExtension = mimeInfo.primaryExtension;
  502.           }
  503.           catch (ex) {
  504.           }
  505.           if (primaryExtension != "")
  506.             typeString = primaryExtension.toUpperCase() + " file";
  507.           // 3. If we can't even do that, just give up and show the MIME type. 
  508.           else
  509.             typeString = mimeInfo.MIMEType;
  510.         }
  511.         
  512.         type.value = typeString;
  513.     },
  514.     
  515.     _blurred: false,
  516.     _delayExpired: false, 
  517.     onBlur: function(aEvent) {
  518.       if (aEvent.target != this.mDialog.document)
  519.         return;
  520.       this._blurred = true;
  521.       this.mDialog.document.documentElement.getButton("accept").disabled = true;
  522.     },
  523.     
  524.     onFocus: function(aEvent) {
  525.       if (aEvent.target != this.mDialog.document)
  526.         return;
  527.       this._blurred = false;
  528.       if (this._delayExpired) {
  529.         var script = "document.documentElement.getButton('accept').disabled = false";
  530.         this.mDialog.setTimeout(script, 250);
  531.       }
  532.     },
  533.  
  534.     // Returns true if opening the default application makes sense.
  535.     openWithDefaultOK: function() {
  536.         var result;
  537.  
  538.         // The checking is different on Windows...
  539. //@line 617 "/build/buildd/firefox-2.0.0.3+1/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  540.             // On other platforms, default is Ok if there is a default app.
  541.             // Note that nsIMIMEInfo providers need to ensure that this holds true
  542.             // on each platform.
  543.         return this.mLauncher.MIMEInfo.hasDefaultHandler;
  544. //@line 622 "/build/buildd/firefox-2.0.0.3+1/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  545.     },
  546.     
  547.     // Set "default" application description field.
  548.     initDefaultApp: function() {
  549.       // Use description, if we can get one.
  550.       var desc = this.mLauncher.MIMEInfo.defaultDescription;
  551.       if (desc) {
  552.         var defaultApp = this.dialogElement("strings").getFormattedString("defaultApp", [desc]);
  553.         this.dialogElement("defaultHandler").label = defaultApp;
  554.       }
  555.       else {
  556.         this.dialogElement("modeDeck").setAttribute("selectedIndex", "1");
  557.         // Hide the default handler item too, in case the user picks a 
  558.         // custom handler at a later date which triggers the menulist to show.
  559.         this.dialogElement("defaultHandler").hidden = true;
  560.       }
  561.     },
  562.  
  563.     // getPath:
  564.     getPath: function (aFile) {
  565. //@line 645 "/build/buildd/firefox-2.0.0.3+1/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  566.       return aFile.path;
  567. //@line 647 "/build/buildd/firefox-2.0.0.3+1/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  568.     },
  569.  
  570.     // initAppAndSaveToDiskValues:
  571.     initAppAndSaveToDiskValues: function() {
  572.       var modeGroup = this.dialogElement("mode");
  573.  
  574.       // We don't let users open .exe files or random binary data directly 
  575.       // from the browser at the moment because of security concerns. 
  576.       var openWithDefaultOK = this.openWithDefaultOK();
  577.       var mimeType = this.mLauncher.MIMEInfo.MIMEType;
  578.       if (this.mLauncher.targetFile.isExecutable() || (
  579.           (mimeType == "application/octet-stream" ||
  580.            mimeType == "application/x-msdownload") && 
  581.            !openWithDefaultOK)) {
  582.         this.dialogElement("open").disabled = true;
  583.         var openHandler = this.dialogElement("openHandler");
  584.         openHandler.disabled = true;
  585.         openHandler.selectedItem = null;
  586.         modeGroup.selectedItem = this.dialogElement("save");
  587.         return;
  588.       }
  589.     
  590.       // Fill in helper app info, if there is any.
  591.       this.chosenApp = this.mLauncher.MIMEInfo.preferredApplicationHandler;
  592.       // Initialize "default application" field.
  593.       this.initDefaultApp();
  594.  
  595.       var otherHandler = this.dialogElement("otherHandler");
  596.               
  597.       // Fill application name textbox.
  598.       if (this.chosenApp && this.chosenApp.path) {
  599.         otherHandler.setAttribute("path", this.getPath(this.chosenApp));
  600.         otherHandler.label = this.chosenApp.leafName;
  601.         otherHandler.hidden = false;
  602.       }
  603.  
  604.       var useDefault = this.dialogElement("useSystemDefault");
  605.       var openHandler = this.dialogElement("openHandler");
  606.       openHandler.selectedIndex = 0;
  607.  
  608.       if (this.mLauncher.MIMEInfo.preferredAction == this.nsIMIMEInfo.useSystemDefault) {
  609.         // Open (using system default).
  610.         modeGroup.selectedItem = this.dialogElement("open");
  611.       } else if (this.mLauncher.MIMEInfo.preferredAction == this.nsIMIMEInfo.useHelperApp) {
  612.         // Open with given helper app.
  613.         modeGroup.selectedItem = this.dialogElement("open");
  614.         openHandler.selectedIndex = 1;
  615.       } else {
  616.         // Save to disk.
  617.         modeGroup.selectedItem = this.dialogElement("save");
  618.       }
  619.       
  620.       // If we don't have a "default app" then disable that choice.
  621.       if (!openWithDefaultOK) {
  622.         var useDefault = this.dialogElement("defaultHandler");
  623.         var isSelected = useDefault.selected;
  624.         
  625.         // Disable that choice.
  626.         useDefault.hidden = true;
  627.         // If that's the default, then switch to "save to disk."
  628.         if (isSelected) {
  629.           openHandler.selectedIndex = 1;
  630.           modeGroup.selectedItem = this.dialogElement("save");
  631.         }
  632.       }
  633.       
  634.       // otherHandler is always disabled on Mac
  635. //@line 718 "/build/buildd/firefox-2.0.0.3+1/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  636.       otherHandler.nextSibling.hidden = otherHandler.nextSibling.nextSibling.hidden = false;
  637. //@line 720 "/build/buildd/firefox-2.0.0.3+1/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  638.       this.updateOKButton();
  639.     },
  640.  
  641.     // Returns the user-selected application
  642.     helperAppChoice: function() {
  643.       return this.chosenApp;
  644.     },
  645.     
  646.     get saveToDisk() {
  647.       return this.dialogElement("save").selected;
  648.     },
  649.     
  650.     get useOtherHandler() {
  651.       return this.dialogElement("open").selected && this.dialogElement("openHandler").selectedIndex == 1;
  652.     },
  653.     
  654.     get useSystemDefault() {
  655.       return this.dialogElement("open").selected && this.dialogElement("openHandler").selectedIndex == 0;
  656.     },
  657.     
  658.     toggleRememberChoice: function (aCheckbox) {
  659.         this.dialogElement("settingsChange").hidden = !aCheckbox.checked;
  660.         this.mDialog.sizeToContent();
  661.     },
  662.     
  663.     openHandlerCommand: function () {
  664.       var openHandler = this.dialogElement("openHandler");
  665.       if (openHandler.selectedItem.id == "choose")
  666.         this.chooseApp();
  667.       else
  668.         openHandler.setAttribute("lastSelectedItemID", openHandler.selectedItem.id);
  669.     },
  670.  
  671.     updateOKButton: function() {
  672.       var ok = false;
  673.       if (this.dialogElement("save").selected) {
  674.         // This is always OK.
  675.         ok = true;
  676.       } 
  677.       else if (this.dialogElement("open").selected) {
  678.         switch (this.dialogElement("openHandler").selectedIndex) {
  679.         case 0:
  680.           // No app need be specified in this case.
  681.           ok = true;
  682.           break;
  683.         case 1:
  684.           // only enable the OK button if we have a default app to use or if 
  685.           // the user chose an app....
  686.           ok = this.chosenApp || /\S/.test(this.dialogElement("otherHandler").getAttribute("path")); 
  687.         break;
  688.         }
  689.       }
  690.  
  691.       // Enable Ok button if ok to press.
  692.       this.mDialog.document.documentElement.getButton("accept").disabled = !ok;
  693.     },
  694.     
  695.     // Returns true iff the user-specified helper app has been modified.
  696.     appChanged: function() {
  697.       return this.helperAppChoice() != this.mLauncher.MIMEInfo.preferredApplicationHandler;
  698.     },
  699.  
  700.     updateMIMEInfo: function() {
  701.       var needUpdate = false;
  702.       // If current selection differs from what's in the mime info object,
  703.       // then we need to update.
  704.       if (this.saveToDisk) {
  705.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.saveToDisk;
  706.         if (needUpdate)
  707.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.saveToDisk;
  708.       } 
  709.       else if (this.useSystemDefault) {
  710.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.useSystemDefault;
  711.         if (needUpdate)
  712.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.useSystemDefault;
  713.       } 
  714.       else {
  715.         // For "open with", we need to check both preferred action and whether the user chose
  716.         // a new app.
  717.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.useHelperApp || this.appChanged();
  718.         if (needUpdate) {
  719.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.useHelperApp;
  720.           // App may have changed - Update application and description
  721.           var app = this.helperAppChoice();
  722.           this.mLauncher.MIMEInfo.preferredApplicationHandler = app;
  723.           this.mLauncher.MIMEInfo.applicationDescription = "";
  724.         }
  725.       }
  726.       // We will also need to update if the "always ask" flag has changed.
  727.       needUpdate = needUpdate || this.mLauncher.MIMEInfo.alwaysAskBeforeHandling != (!this.dialogElement("rememberChoice").checked);
  728.  
  729.       // One last special case: If the input "always ask" flag was false, then we always
  730.       // update.  In that case we are displaying the helper app dialog for the first
  731.       // time for this mime type and we need to store the user's action in the mimeTypes.rdf
  732.       // data source (whether that action has changed or not; if it didn't change, then we need
  733.       // to store the "always ask" flag so the helper app dialog will or won't display
  734.       // next time, per the user's selection).
  735.       needUpdate = needUpdate || !this.mLauncher.MIMEInfo.alwaysAskBeforeHandling;
  736.  
  737.       // Make sure mime info has updated setting for the "always ask" flag.
  738.       this.mLauncher.MIMEInfo.alwaysAskBeforeHandling = !this.dialogElement("rememberChoice").checked;
  739.  
  740.       return needUpdate;        
  741.     },
  742.     
  743.     // See if the user changed things, and if so, update the
  744.     // mimeTypes.rdf entry for this mime type.
  745.     updateHelperAppPref: function() {
  746.       var ha = new this.mDialog.HelperApps();
  747.       ha.updateTypeInfo(this.mLauncher.MIMEInfo);
  748.       ha.destroy();
  749.     },
  750.     
  751.     // onOK:
  752.     onOK: function() {
  753.       // Verify typed app path, if necessary.
  754.       if (this.useOtherHandler) {
  755.         var helperApp = this.helperAppChoice();
  756.         if (!helperApp || !helperApp.exists()) {
  757.           // Show alert and try again.        
  758.           var bundle = this.dialogElement("strings");                    
  759.           var msg = bundle.getFormattedString("badApp", [this.dialogElement("otherHandler").path]);
  760.           var svc = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
  761.           svc.alert(this.mDialog, bundle.getString("badApp.title"), msg);
  762.  
  763.           // Disable the OK button.
  764.           this.mDialog.document.documentElement.getButton("accept").disabled = true;
  765.           this.dialogElement("mode").focus();          
  766.  
  767.           // Clear chosen application.
  768.           this.chosenApp = null;
  769.  
  770.           // Leave dialog up.
  771.           return false;
  772.         }
  773.       }
  774.         
  775.       // Remove our web progress listener (a progress dialog will be
  776.       // taking over).
  777.       this.mLauncher.setWebProgressListener(null);
  778.       
  779.       // saveToDisk and launchWithApplication can return errors in 
  780.       // certain circumstances (e.g. The user clicks cancel in the
  781.       // "Save to Disk" dialog. In those cases, we don't want to
  782.       // update the helper application preferences in the RDF file.
  783.       try {
  784.         var needUpdate = this.updateMIMEInfo();
  785.         
  786.         if (this.dialogElement("save").selected) {
  787.           // If we're using a default download location, create a path
  788.           // for the file to be saved to to pass to |saveToDisk| - otherwise
  789.           // we must ask the user to pick a save name.
  790.  
  791. //@line 887 "/build/buildd/firefox-2.0.0.3+1/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  792.           this.mLauncher.saveToDisk(null, false);
  793.         }
  794.         else
  795.           this.mLauncher.launchWithApplication(null, false);
  796.  
  797.         // Update user pref for this mime type (if necessary). We do not
  798.         // store anything in the mime type preferences for the ambiguous
  799.         // type application/octet-stream. We do NOT do this for 
  800.         // application/x-msdownload since we want users to be able to 
  801.         // autodownload these to disk. 
  802.         if (needUpdate && this.mLauncher.MIMEInfo.MIMEType != "application/octet-stream")
  803.           this.updateHelperAppPref();
  804.       } catch(e) { }
  805.  
  806.       // Unhook dialog from this object.
  807.       this.mDialog.dialog = null;
  808.  
  809.       // Close up dialog by returning true.
  810.       return true;
  811.     },
  812.  
  813.     // onCancel:
  814.     onCancel: function() {
  815.       // Remove our web progress listener.
  816.       this.mLauncher.setWebProgressListener(null);
  817.  
  818.       // Cancel app launcher.
  819.       try {
  820.         const NS_BINDING_ABORTED = 0x804b0002;
  821.         this.mLauncher.cancel(NS_BINDING_ABORTED);
  822.       } catch(exception) {
  823.       }
  824.  
  825.       // Unhook dialog from this object.
  826.       this.mDialog.dialog = null;
  827.  
  828.       // Close up dialog by returning true.
  829.       return true;
  830.     },
  831.  
  832.     // dialogElement:  Convenience. 
  833.     dialogElement: function(id) {
  834.       return this.mDialog.document.getElementById(id);
  835.     },
  836.  
  837.     // chooseApp:  Open file picker and prompt user for application.
  838.     chooseApp: function() {
  839.       var nsIFilePicker = Components.interfaces.nsIFilePicker;
  840.       var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  841.       fp.init(this.mDialog,
  842.               this.dialogElement("strings").getString("chooseAppFilePickerTitle"),
  843.               nsIFilePicker.modeOpen);
  844.  
  845.       fp.appendFilters(nsIFilePicker.filterApps);
  846.  
  847.       if (fp.show() == nsIFilePicker.returnOK && fp.file) {
  848.         // Show the "handler" menulist since we have a (user-specified) 
  849.         // application now.
  850.         this.dialogElement("modeDeck").setAttribute("selectedIndex", "0");
  851.         
  852.         // Remember the file they chose to run.
  853.         this.chosenApp = fp.file;
  854.         // Update dialog.
  855.         var otherHandler = this.dialogElement("otherHandler");
  856.         otherHandler.removeAttribute("hidden");
  857.         otherHandler.setAttribute("path", this.getPath(this.chosenApp));
  858.         otherHandler.label = this.chosenApp.leafName;
  859.         this.dialogElement("openHandler").selectedIndex = 1;
  860.         this.dialogElement("openHandler").setAttribute("lastSelectedItemID", "otherHandler");
  861.         
  862.         this.dialogElement("mode").selectedItem = this.dialogElement("open");
  863.       }
  864.       else {
  865.         var openHandler = this.dialogElement("openHandler");
  866.         var lastSelectedID = openHandler.getAttribute("lastSelectedItemID");
  867.         if (!lastSelectedID)
  868.           lastSelectedID = "defaultHandler";
  869.         openHandler.selectedItem = this.dialogElement(lastSelectedID);
  870.       }
  871.     },
  872.  
  873.     // Turn this on to get debugging messages.
  874.     debug: false,
  875.  
  876.     // Dump text (if debug is on).
  877.     dump: function( text ) {
  878.         if ( this.debug ) {
  879.             dump( text ); 
  880.         }
  881.     },
  882.  
  883.     // dumpInfo:
  884.     doDebug: function() {
  885.         const nsIProgressDialog = Components.interfaces.nsIProgressDialog;
  886.         // Open new progress dialog.
  887.         var progress = Components.classes[ "@mozilla.org/progressdialog;1" ]
  888.                          .createInstance( nsIProgressDialog );
  889.         // Show it.
  890.         progress.open( this.mDialog );
  891.     },
  892.  
  893.     // dumpObj:
  894.     dumpObj: function( spec ) {
  895.          var val = "<undefined>";
  896.          try {
  897.              val = eval( "this."+spec ).toString();
  898.          } catch( exception ) {
  899.          }
  900.          this.dump( spec + "=" + val + "\n" );
  901.     },
  902.  
  903.     // dumpObjectProperties
  904.     dumpObjectProperties: function( desc, obj ) {
  905.          for( prop in obj ) {
  906.              this.dump( desc + "." + prop + "=" );
  907.              var val = "<undefined>";
  908.              try {
  909.                  val = obj[ prop ];
  910.              } catch ( exception ) {
  911.              }
  912.              this.dump( val + "\n" );
  913.          }
  914.     }
  915. }
  916.  
  917. // This Component's module implementation.  All the code below is used to get this
  918. // component registered and accessible via XPCOM.
  919. var module = {
  920.     firstTime: true,
  921.  
  922.     // registerSelf: Register this component.
  923.     registerSelf: function (compMgr, fileSpec, location, type) {
  924.         if (this.firstTime) {
  925.             this.firstTime = false;
  926.             throw Components.results.NS_ERROR_FACTORY_REGISTER_AGAIN;
  927.         }
  928.         compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  929.  
  930.         compMgr.registerFactoryLocation( this.cid,
  931.                                          "Unknown Content Type Dialog",
  932.                                          this.contractId,
  933.                                          fileSpec,
  934.                                          location,
  935.                                          type );
  936.     },
  937.  
  938.     // getClassObject: Return this component's factory object.
  939.     getClassObject: function (compMgr, cid, iid) {
  940.         if (!cid.equals(this.cid)) {
  941.             throw Components.results.NS_ERROR_NO_INTERFACE;
  942.         }
  943.  
  944.         if (!iid.equals(Components.interfaces.nsIFactory)) {
  945.             throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  946.         }
  947.  
  948.         return this.factory;
  949.     },
  950.  
  951.     /* CID for this class */
  952.     cid: Components.ID("{F68578EB-6EC2-4169-AE19-8C6243F0ABE1}"),
  953.  
  954.     /* Contract ID for this class */
  955.     contractId: "@mozilla.org/helperapplauncherdialog;1",
  956.  
  957.     /* factory object */
  958.     factory: {
  959.         // createInstance: Return a new nsProgressDialog object.
  960.         createInstance: function (outer, iid) {
  961.             if (outer != null)
  962.                 throw Components.results.NS_ERROR_NO_AGGREGATION;
  963.  
  964.             return (new nsUnknownContentTypeDialog()).QueryInterface(iid);
  965.         }
  966.     },
  967.  
  968.     // canUnload: n/a (returns true)
  969.     canUnload: function(compMgr) {
  970.         return true;
  971.     }
  972. };
  973.  
  974. // NSGetModule: Return the nsIModule object.
  975. function NSGetModule(compMgr, fileSpec) {
  976.     return module;
  977. }
  978.