home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / lib / firefox / components / nsHelperAppDlg.js < prev    next >
Encoding:
JavaScript  |  2006-08-18  |  36.5 KB  |  959 lines

  1. /*
  2. //@line 42 "/build/buildd/firefox-1.99+2.0b1+dfsg/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-1.99+2.0b1+dfsg/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  103.           return "Home";
  104. //@line 150 "/build/buildd/firefox-1.99+2.0b1+dfsg/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.       this.initAppAndSaveToDiskValues();
  379.  
  380.       // Initialize "always ask me" box. This should always be disabled
  381.       // and set to true for the ambiguous type application/octet-stream.
  382.       // We don't also check for application/x-msdownload here since we
  383.       // want users to be able to autodownload .exe files. 
  384.       var rememberChoice = this.dialogElement("rememberChoice");
  385.  
  386. //@line 451 "/build/buildd/firefox-1.99+2.0b1+dfsg/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  387.       var mimeType = this.mLauncher.MIMEInfo.MIMEType;
  388.       if (mimeType == "application/octet-stream" || 
  389.           mimeType == "application/x-msdownload" ||
  390.           this.mLauncher.targetFile.isExecutable()) {
  391.         rememberChoice.checked = false;
  392.         rememberChoice.disabled = true;
  393.       }
  394.       else {
  395.         rememberChoice.checked = !this.mLauncher.MIMEInfo.alwaysAskBeforeHandling;
  396.       }
  397.       this.toggleRememberChoice(rememberChoice);
  398.  
  399.       // XXXben - menulist won't init properly, hack. 
  400.       var openHandler = this.dialogElement("openHandler");
  401.       openHandler.parentNode.removeChild(openHandler);
  402.       var openHandlerBox = this.dialogElement("openHandlerBox");
  403.       openHandlerBox.appendChild(openHandler);
  404.  
  405.       this.mDialog.setTimeout("dialog.postShowCallback()", 0);
  406.       
  407.       this.mDialog.document.documentElement.getButton("accept").disabled = true;
  408.       const nsITimer = Components.interfaces.nsITimer;
  409.       this._timer = Components.classes["@mozilla.org/timer;1"]
  410.                               .createInstance(nsITimer);
  411.       this._timer.initWithCallback(this, 250, nsITimer.TYPE_ONE_SHOT);
  412.     },
  413.     
  414.     _timer: null,
  415.     notify: function (aTimer) {
  416.       try { // The user may have already canceled the dialog.
  417.         if (!this._blurred)
  418.           this.mDialog.document.documentElement.getButton('accept').disabled = false;
  419.       } catch (ex) {}
  420.       this._delayExpired = true;
  421.       this._timer = null; // the timer won't release us, so we have to release it
  422.     },
  423.     
  424.     postShowCallback: function () {
  425.       this.mDialog.sizeToContent();
  426.  
  427.       // Set initial focus
  428.       this.dialogElement("mode").focus();
  429.     },
  430.  
  431.     // initIntro:
  432.     initIntro: function(url, filename, displayname) {
  433.         this.dialogElement( "location" ).value = displayname;
  434.         this.dialogElement( "location" ).setAttribute("realname", filename);
  435.         this.dialogElement( "location" ).setAttribute("tooltiptext", displayname);
  436.  
  437.         // if mSourcePath is a local file, then let's use the pretty path name instead of an ugly
  438.         // url...
  439.         var pathString = this.mSourcePath;
  440.         try 
  441.         {
  442.           var fileURL = url.QueryInterface(Components.interfaces.nsIFileURL);
  443.           if (fileURL)
  444.           {
  445.             var fileObject = fileURL.file;
  446.             if (fileObject)
  447.             {
  448.               var parentObject = fileObject.parent;
  449.               if (parentObject)
  450.               {
  451.                 pathString = parentObject.path;
  452.               }
  453.             }
  454.           }
  455.         } catch(ex) {}
  456.  
  457.         if (pathString == this.mSourcePath)
  458.         {
  459.           // wasn't a fileURL
  460.           var tmpurl = url.clone(); // don't want to change the real url
  461.           try {
  462.             tmpurl.userPass = "";
  463.           } catch (ex) {}
  464.           pathString = tmpurl.prePath;
  465.         }
  466.  
  467.         // Set the location text, which is separate from the intro text so it can be cropped
  468.         var location = this.dialogElement( "source" );
  469.         location.value = pathString;
  470.         location.setAttribute("tooltiptext", this.mSourcePath);
  471.         
  472.         // Show the type of file. 
  473.         var type = this.dialogElement("type");
  474.         var mimeInfo = this.mLauncher.MIMEInfo;
  475.         
  476.         // 1. Try to use the pretty description of the type, if one is available.
  477.         var typeString = mimeInfo.description;
  478.         
  479.         if (typeString == "") {
  480.           // 2. If there is none, use the extension to identify the file, e.g. "ZIP file"
  481.           var primaryExtension = "";
  482.           try {
  483.             primaryExtension = mimeInfo.primaryExtension;
  484.           }
  485.           catch (ex) {
  486.           }
  487.           if (primaryExtension != "")
  488.             typeString = primaryExtension.toUpperCase() + " file";
  489.           // 3. If we can't even do that, just give up and show the MIME type. 
  490.           else
  491.             typeString = mimeInfo.MIMEType;
  492.         }
  493.         
  494.         type.value = typeString;
  495.     },
  496.     
  497.     _blurred: false,
  498.     _delayExpired: false, 
  499.     onBlur: function(aEvent) {
  500.       if (aEvent.target != this.mDialog.document)
  501.         return;
  502.       this._blurred = true;
  503.       this.mDialog.document.documentElement.getButton("accept").disabled = true;
  504.     },
  505.     
  506.     onFocus: function(aEvent) {
  507.       if (aEvent.target != this.mDialog.document)
  508.         return;
  509.       this._blurred = false;
  510.       if (this._delayExpired) {
  511.         var script = "document.documentElement.getButton('accept').disabled = false";
  512.         this.mDialog.setTimeout(script, 250);
  513.       }
  514.     },
  515.  
  516.     // Returns true if opening the default application makes sense.
  517.     openWithDefaultOK: function() {
  518.         var result;
  519.  
  520.         // The checking is different on Windows...
  521. //@line 599 "/build/buildd/firefox-1.99+2.0b1+dfsg/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  522.             // On other platforms, default is Ok if there is a default app.
  523.             // Note that nsIMIMEInfo providers need to ensure that this holds true
  524.             // on each platform.
  525.         return this.mLauncher.MIMEInfo.hasDefaultHandler;
  526. //@line 604 "/build/buildd/firefox-1.99+2.0b1+dfsg/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  527.     },
  528.     
  529.     // Set "default" application description field.
  530.     initDefaultApp: function() {
  531.       // Use description, if we can get one.
  532.       var desc = this.mLauncher.MIMEInfo.defaultDescription;
  533.       if (desc) {
  534.         var defaultApp = this.dialogElement("strings").getFormattedString("defaultApp", [desc]);
  535.         this.dialogElement("defaultHandler").label = defaultApp;
  536.       }
  537.       else {
  538.         this.dialogElement("modeDeck").setAttribute("selectedIndex", "1");
  539.         // Hide the default handler item too, in case the user picks a 
  540.         // custom handler at a later date which triggers the menulist to show.
  541.         this.dialogElement("defaultHandler").hidden = true;
  542.       }
  543.     },
  544.  
  545.     // getPath:
  546.     getPath: function (aFile) {
  547. //@line 627 "/build/buildd/firefox-1.99+2.0b1+dfsg/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  548.       return aFile.path;
  549. //@line 629 "/build/buildd/firefox-1.99+2.0b1+dfsg/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  550.     },
  551.  
  552.     // initAppAndSaveToDiskValues:
  553.     initAppAndSaveToDiskValues: function() {
  554.       var modeGroup = this.dialogElement("mode");
  555.  
  556.       // We don't let users open .exe files or random binary data directly 
  557.       // from the browser at the moment because of security concerns. 
  558.       var openWithDefaultOK = this.openWithDefaultOK();
  559.       var mimeType = this.mLauncher.MIMEInfo.MIMEType;
  560.       if (this.mLauncher.targetFile.isExecutable() || (
  561.           (mimeType == "application/octet-stream" ||
  562.            mimeType == "application/x-msdownload") && 
  563.            !openWithDefaultOK)) {
  564.         this.dialogElement("open").disabled = true;
  565.         var openHandler = this.dialogElement("openHandler");
  566.         openHandler.disabled = true;
  567.         openHandler.selectedItem = null;
  568.         modeGroup.selectedItem = this.dialogElement("save");
  569.         return;
  570.       }
  571.     
  572.       // Fill in helper app info, if there is any.
  573.       this.chosenApp = this.mLauncher.MIMEInfo.preferredApplicationHandler;
  574.       // Initialize "default application" field.
  575.       this.initDefaultApp();
  576.  
  577.       var otherHandler = this.dialogElement("otherHandler");
  578.               
  579.       // Fill application name textbox.
  580.       if (this.chosenApp && this.chosenApp.path) {
  581.         otherHandler.setAttribute("path", this.getPath(this.chosenApp));
  582.         otherHandler.label = this.chosenApp.leafName;
  583.         otherHandler.hidden = false;
  584.       }
  585.  
  586.       var useDefault = this.dialogElement("useSystemDefault");
  587.       var openHandler = this.dialogElement("openHandler");
  588.       openHandler.selectedIndex = 0;
  589.  
  590.       if (this.mLauncher.MIMEInfo.preferredAction == this.nsIMIMEInfo.useSystemDefault) {
  591.         // Open (using system default).
  592.         modeGroup.selectedItem = this.dialogElement("open");
  593.       } else if (this.mLauncher.MIMEInfo.preferredAction == this.nsIMIMEInfo.useHelperApp) {
  594.         // Open with given helper app.
  595.         modeGroup.selectedItem = this.dialogElement("open");
  596.         openHandler.selectedIndex = 1;
  597.       } else {
  598.         // Save to disk.
  599.         modeGroup.selectedItem = this.dialogElement("save");
  600.       }
  601.       
  602.       // If we don't have a "default app" then disable that choice.
  603.       if (!openWithDefaultOK) {
  604.         var useDefault = this.dialogElement("defaultHandler");
  605.         var isSelected = useDefault.selected;
  606.         
  607.         // Disable that choice.
  608.         useDefault.hidden = true;
  609.         // If that's the default, then switch to "save to disk."
  610.         if (isSelected) {
  611.           openHandler.selectedIndex = 1;
  612.           modeGroup.selectedItem = this.dialogElement("save");
  613.         }
  614.       }
  615.       
  616.       // otherHandler is always disabled on Mac
  617. //@line 700 "/build/buildd/firefox-1.99+2.0b1+dfsg/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  618.       otherHandler.nextSibling.hidden = otherHandler.nextSibling.nextSibling.hidden = false;
  619. //@line 702 "/build/buildd/firefox-1.99+2.0b1+dfsg/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  620.       this.updateOKButton();
  621.     },
  622.  
  623.     // Returns the user-selected application
  624.     helperAppChoice: function() {
  625.       return this.chosenApp;
  626.     },
  627.     
  628.     get saveToDisk() {
  629.       return this.dialogElement("save").selected;
  630.     },
  631.     
  632.     get useOtherHandler() {
  633.       return this.dialogElement("open").selected && this.dialogElement("openHandler").selectedIndex == 1;
  634.     },
  635.     
  636.     get useSystemDefault() {
  637.       return this.dialogElement("open").selected && this.dialogElement("openHandler").selectedIndex == 0;
  638.     },
  639.     
  640.     toggleRememberChoice: function (aCheckbox) {
  641.         this.dialogElement("settingsChange").hidden = !aCheckbox.checked;
  642.         this.mDialog.sizeToContent();
  643.     },
  644.     
  645.     openHandlerCommand: function () {
  646.       var openHandler = this.dialogElement("openHandler");
  647.       if (openHandler.selectedItem.id == "choose")
  648.         this.chooseApp();
  649.       else
  650.         openHandler.setAttribute("lastSelectedItemID", openHandler.selectedItem.id);
  651.     },
  652.  
  653.     updateOKButton: function() {
  654.       var ok = false;
  655.       if (this.dialogElement("save").selected) {
  656.         // This is always OK.
  657.         ok = true;
  658.       } 
  659.       else if (this.dialogElement("open").selected) {
  660.         switch (this.dialogElement("openHandler").selectedIndex) {
  661.         case 0:
  662.           // No app need be specified in this case.
  663.           ok = true;
  664.           break;
  665.         case 1:
  666.           // only enable the OK button if we have a default app to use or if 
  667.           // the user chose an app....
  668.           ok = this.chosenApp || /\S/.test(this.dialogElement("otherHandler").getAttribute("path")); 
  669.         break;
  670.         }
  671.       }
  672.  
  673.       // Enable Ok button if ok to press.
  674.       this.mDialog.document.documentElement.getButton("accept").disabled = !ok;
  675.     },
  676.     
  677.     // Returns true iff the user-specified helper app has been modified.
  678.     appChanged: function() {
  679.       return this.helperAppChoice() != this.mLauncher.MIMEInfo.preferredApplicationHandler;
  680.     },
  681.  
  682.     updateMIMEInfo: function() {
  683.       var needUpdate = false;
  684.       // If current selection differs from what's in the mime info object,
  685.       // then we need to update.
  686.       if (this.saveToDisk) {
  687.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.saveToDisk;
  688.         if (needUpdate)
  689.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.saveToDisk;
  690.       } 
  691.       else if (this.useSystemDefault) {
  692.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.useSystemDefault;
  693.         if (needUpdate)
  694.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.useSystemDefault;
  695.       } 
  696.       else {
  697.         // For "open with", we need to check both preferred action and whether the user chose
  698.         // a new app.
  699.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.useHelperApp || this.appChanged();
  700.         if (needUpdate) {
  701.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.useHelperApp;
  702.           // App may have changed - Update application and description
  703.           var app = this.helperAppChoice();
  704.           this.mLauncher.MIMEInfo.preferredApplicationHandler = app;
  705.           this.mLauncher.MIMEInfo.applicationDescription = "";
  706.         }
  707.       }
  708.       // We will also need to update if the "always ask" flag has changed.
  709.       needUpdate = needUpdate || this.mLauncher.MIMEInfo.alwaysAskBeforeHandling != (!this.dialogElement("rememberChoice").checked);
  710.  
  711.       // One last special case: If the input "always ask" flag was false, then we always
  712.       // update.  In that case we are displaying the helper app dialog for the first
  713.       // time for this mime type and we need to store the user's action in the mimeTypes.rdf
  714.       // data source (whether that action has changed or not; if it didn't change, then we need
  715.       // to store the "always ask" flag so the helper app dialog will or won't display
  716.       // next time, per the user's selection).
  717.       needUpdate = needUpdate || !this.mLauncher.MIMEInfo.alwaysAskBeforeHandling;
  718.  
  719.       // Make sure mime info has updated setting for the "always ask" flag.
  720.       this.mLauncher.MIMEInfo.alwaysAskBeforeHandling = !this.dialogElement("rememberChoice").checked;
  721.  
  722.       return needUpdate;        
  723.     },
  724.     
  725.     // See if the user changed things, and if so, update the
  726.     // mimeTypes.rdf entry for this mime type.
  727.     updateHelperAppPref: function() {
  728.       var ha = new this.mDialog.HelperApps();
  729.       ha.updateTypeInfo(this.mLauncher.MIMEInfo);
  730.     },
  731.     
  732.     // onOK:
  733.     onOK: function() {
  734.       // Verify typed app path, if necessary.
  735.       if (this.useOtherHandler) {
  736.         var helperApp = this.helperAppChoice();
  737.         if (!helperApp || !helperApp.exists()) {
  738.           // Show alert and try again.        
  739.           var bundle = this.dialogElement("strings");                    
  740.           var msg = bundle.getFormattedString("badApp", [this.dialogElement("otherHandler").path]);
  741.           var svc = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
  742.           svc.alert(this.mDialog, bundle.getString("badApp.title"), msg);
  743.  
  744.           // Disable the OK button.
  745.           this.mDialog.document.documentElement.getButton("accept").disabled = true;
  746.           this.dialogElement("mode").focus();          
  747.  
  748.           // Clear chosen application.
  749.           this.chosenApp = null;
  750.  
  751.           // Leave dialog up.
  752.           return false;
  753.         }
  754.       }
  755.         
  756.       // Remove our web progress listener (a progress dialog will be
  757.       // taking over).
  758.       this.mLauncher.setWebProgressListener(null);
  759.       
  760.       // saveToDisk and launchWithApplication can return errors in 
  761.       // certain circumstances (e.g. The user clicks cancel in the
  762.       // "Save to Disk" dialog. In those cases, we don't want to
  763.       // update the helper application preferences in the RDF file.
  764.       try {
  765.         var needUpdate = this.updateMIMEInfo();
  766.         
  767.         if (this.dialogElement("save").selected) {
  768.           // If we're using a default download location, create a path
  769.           // for the file to be saved to to pass to |saveToDisk| - otherwise
  770.           // we must ask the user to pick a save name.
  771.  
  772. //@line 868 "/build/buildd/firefox-1.99+2.0b1+dfsg/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  773.           this.mLauncher.saveToDisk(null, false);
  774.         }
  775.         else
  776.           this.mLauncher.launchWithApplication(null, false);
  777.  
  778.         // Update user pref for this mime type (if necessary). We do not
  779.         // store anything in the mime type preferences for the ambiguous
  780.         // type application/octet-stream. We do NOT do this for 
  781.         // application/x-msdownload since we want users to be able to 
  782.         // autodownload these to disk. 
  783.         if (needUpdate && this.mLauncher.MIMEInfo.MIMEType != "application/octet-stream")
  784.           this.updateHelperAppPref();
  785.       } catch(e) { }
  786.  
  787.       // Unhook dialog from this object.
  788.       this.mDialog.dialog = null;
  789.  
  790.       // Close up dialog by returning true.
  791.       return true;
  792.     },
  793.  
  794.     // onCancel:
  795.     onCancel: function() {
  796.       // Remove our web progress listener.
  797.       this.mLauncher.setWebProgressListener(null);
  798.  
  799.       // Cancel app launcher.
  800.       try {
  801.         const NS_BINDING_ABORTED = 0x804b0002;
  802.         this.mLauncher.cancel(NS_BINDING_ABORTED);
  803.       } catch(exception) {
  804.       }
  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.     // dialogElement:  Convenience. 
  814.     dialogElement: function(id) {
  815.       return this.mDialog.document.getElementById(id);
  816.     },
  817.  
  818.     // chooseApp:  Open file picker and prompt user for application.
  819.     chooseApp: function() {
  820.       var nsIFilePicker = Components.interfaces.nsIFilePicker;
  821.       var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  822.       fp.init(this.mDialog,
  823.               this.dialogElement("strings").getString("chooseAppFilePickerTitle"),
  824.               nsIFilePicker.modeOpen);
  825.  
  826.       fp.appendFilters(nsIFilePicker.filterApps);
  827.  
  828.       if (fp.show() == nsIFilePicker.returnOK && fp.file) {
  829.         // Show the "handler" menulist since we have a (user-specified) 
  830.         // application now.
  831.         this.dialogElement("modeDeck").setAttribute("selectedIndex", "0");
  832.         
  833.         // Remember the file they chose to run.
  834.         this.chosenApp = fp.file;
  835.         // Update dialog.
  836.         var otherHandler = this.dialogElement("otherHandler");
  837.         otherHandler.removeAttribute("hidden");
  838.         otherHandler.setAttribute("path", this.getPath(this.chosenApp));
  839.         otherHandler.label = this.chosenApp.leafName;
  840.         this.dialogElement("openHandler").selectedIndex = 1;
  841.         this.dialogElement("openHandler").setAttribute("lastSelectedItemID", "otherHandler");
  842.         
  843.         this.dialogElement("mode").selectedItem = this.dialogElement("open");
  844.       }
  845.       else {
  846.         var openHandler = this.dialogElement("openHandler");
  847.         var lastSelectedID = openHandler.getAttribute("lastSelectedItemID");
  848.         if (!lastSelectedID)
  849.           lastSelectedID = "defaultHandler";
  850.         openHandler.selectedItem = this.dialogElement(lastSelectedID);
  851.       }
  852.     },
  853.  
  854.     // Turn this on to get debugging messages.
  855.     debug: false,
  856.  
  857.     // Dump text (if debug is on).
  858.     dump: function( text ) {
  859.         if ( this.debug ) {
  860.             dump( text ); 
  861.         }
  862.     },
  863.  
  864.     // dumpInfo:
  865.     doDebug: function() {
  866.         const nsIProgressDialog = Components.interfaces.nsIProgressDialog;
  867.         // Open new progress dialog.
  868.         var progress = Components.classes[ "@mozilla.org/progressdialog;1" ]
  869.                          .createInstance( nsIProgressDialog );
  870.         // Show it.
  871.         progress.open( this.mDialog );
  872.     },
  873.  
  874.     // dumpObj:
  875.     dumpObj: function( spec ) {
  876.          var val = "<undefined>";
  877.          try {
  878.              val = eval( "this."+spec ).toString();
  879.          } catch( exception ) {
  880.          }
  881.          this.dump( spec + "=" + val + "\n" );
  882.     },
  883.  
  884.     // dumpObjectProperties
  885.     dumpObjectProperties: function( desc, obj ) {
  886.          for( prop in obj ) {
  887.              this.dump( desc + "." + prop + "=" );
  888.              var val = "<undefined>";
  889.              try {
  890.                  val = obj[ prop ];
  891.              } catch ( exception ) {
  892.              }
  893.              this.dump( val + "\n" );
  894.          }
  895.     }
  896. }
  897.  
  898. // This Component's module implementation.  All the code below is used to get this
  899. // component registered and accessible via XPCOM.
  900. var module = {
  901.     firstTime: true,
  902.  
  903.     // registerSelf: Register this component.
  904.     registerSelf: function (compMgr, fileSpec, location, type) {
  905.         if (this.firstTime) {
  906.             this.firstTime = false;
  907.             throw Components.results.NS_ERROR_FACTORY_REGISTER_AGAIN;
  908.         }
  909.         compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  910.  
  911.         compMgr.registerFactoryLocation( this.cid,
  912.                                          "Unknown Content Type Dialog",
  913.                                          this.contractId,
  914.                                          fileSpec,
  915.                                          location,
  916.                                          type );
  917.     },
  918.  
  919.     // getClassObject: Return this component's factory object.
  920.     getClassObject: function (compMgr, cid, iid) {
  921.         if (!cid.equals(this.cid)) {
  922.             throw Components.results.NS_ERROR_NO_INTERFACE;
  923.         }
  924.  
  925.         if (!iid.equals(Components.interfaces.nsIFactory)) {
  926.             throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  927.         }
  928.  
  929.         return this.factory;
  930.     },
  931.  
  932.     /* CID for this class */
  933.     cid: Components.ID("{F68578EB-6EC2-4169-AE19-8C6243F0ABE1}"),
  934.  
  935.     /* Contract ID for this class */
  936.     contractId: "@mozilla.org/helperapplauncherdialog;1",
  937.  
  938.     /* factory object */
  939.     factory: {
  940.         // createInstance: Return a new nsProgressDialog object.
  941.         createInstance: function (outer, iid) {
  942.             if (outer != null)
  943.                 throw Components.results.NS_ERROR_NO_AGGREGATION;
  944.  
  945.             return (new nsUnknownContentTypeDialog()).QueryInterface(iid);
  946.         }
  947.     },
  948.  
  949.     // canUnload: n/a (returns true)
  950.     canUnload: function(compMgr) {
  951.         return true;
  952.     }
  953. };
  954.  
  955. // NSGetModule: Return the nsIModule object.
  956. function NSGetModule(compMgr, fileSpec) {
  957.     return module;
  958. }
  959.