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 / mozilla-thunderbird / components / nsHelperAppDlg.js < prev    next >
Encoding:
JavaScript  |  2007-04-03  |  35.6 KB  |  932 lines

  1. /*
  2. //@line 42 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/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/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  103.           return "Home";
  104. //@line 150 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/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.           var newDir = result.parent;
  195.           prefs.setComplexValue("browser.download.dir", Components.interfaces.nsILocalFile, newDir);
  196.         }
  197.       }
  198.       return result;
  199.     },
  200.     
  201.     validateLeafName: function (aLocalFile, aLeafName, aFileExt)
  202.     {
  203.       if (!aLocalFile || !aLocalFile.exists())
  204.         return null;
  205.  
  206.       if (aLeafName == "")
  207.         aLeafName = "unnamed" + (aFileExt ? "." + aFileExt : "");
  208.       aLocalFile.append(aLeafName);
  209.  
  210.       this.makeFileUnique(aLocalFile);
  211.  
  212.       if (aLocalFile.isExecutable() && !this.mLauncher.targetFile.isExecutable()) {
  213.         var f = aLocalFile.clone();
  214.         aLocalFile.leafName = aLocalFile.leafName + "." + this.mLauncher.MIMEInfo.primaryExtension; 
  215.  
  216.         f.remove(false);
  217.         this.makeFileUnique(aLocalFile);
  218.       }
  219.       return aLocalFile;
  220.     },
  221.  
  222.     makeFileUnique: function (aLocalFile)
  223.     {
  224.       try {
  225.         // Since we're automatically downloading, we don't get the file picker's 
  226.         // logic to check for existing files, so we need to do that here.
  227.         //
  228.         // Note - this code is identical to that in 
  229.         //   toolkit/content/contentAreaUtils.js.
  230.         // If you are updating this code, update that code too! We can't share code
  231.         // here since this is called in a js component. 
  232.         var collisionCount = 0;
  233.         while (aLocalFile.exists()) {
  234.           collisionCount++;
  235.           if (collisionCount == 1) {
  236.             // Append "(2)" before the last dot in (or at the end of) the filename
  237.             // special case .ext.gz etc files so we don't wind up with .tar(2).gz
  238.             if (aLocalFile.leafName.match(/\.[^\.]{1,3}\.(gz|bz2|Z)$/i)) {
  239.               aLocalFile.leafName = aLocalFile.leafName.replace(/\.[^\.]{1,3}\.(gz|bz2|Z)$/i, "(2)$&");
  240.             }
  241.             else {
  242.               aLocalFile.leafName = aLocalFile.leafName.replace(/(\.[^\.]*)?$/, "(2)$&");
  243.             }
  244.           }
  245.           else {
  246.             // replace the last (n) in the filename with (n+1)
  247.             aLocalFile.leafName = aLocalFile.leafName.replace(/^(.*\()\d+\)/, "$1" + (collisionCount+1) + ")");
  248.           }
  249.         }
  250.         aLocalFile.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0600);
  251.       }
  252.       catch (e) {
  253.         dump("*** exception in validateLeafName: " + e + "\n");
  254.         if (aLocalFile.leafName == "" || aLocalFile.isDirectory()) {
  255.           aLocalFile.append("unnamed");
  256.           if (aLocalFile.exists())
  257.             aLocalFile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0600);
  258.         }
  259.       }
  260.     },
  261.     
  262.     // ---------- implementation methods ----------
  263.  
  264.     // Web progress listener so we can detect errors while mLauncher is
  265.     // streaming the data to a temporary file.
  266.     progressListener: {
  267.         // Implementation properties.
  268.         helperAppDlg: null,
  269.  
  270.         // nsIWebProgressListener methods.
  271.         // Look for error notifications and display alert to user.
  272.         onStatusChange: function( aWebProgress, aRequest, aStatus, aMessage ) {
  273.             if ( aStatus != Components.results.NS_OK ) {
  274.                 // Get prompt service.
  275.                 var prompter = Components.classes[ "@mozilla.org/embedcomp/prompt-service;1" ]
  276.                                    .getService( Components.interfaces.nsIPromptService );
  277.                 // Display error alert (using text supplied by back-end).
  278.                 prompter.alert( this.dialog, this.helperAppDlg.mTitle, aMessage );
  279.  
  280.                 // Close the dialog.
  281.                 this.helperAppDlg.onCancel();
  282.                 if ( this.helperAppDlg.mDialog ) {
  283.                     this.helperAppDlg.mDialog.close();
  284.                 }
  285.             }
  286.         },
  287.  
  288.         // Ignore onProgressChange, onStateChange, onLocationChange, and onSecurityChange notifications.
  289.         onProgressChange: function( aWebProgress,
  290.                                     aRequest,
  291.                                     aCurSelfProgress,
  292.                                     aMaxSelfProgress,
  293.                                     aCurTotalProgress,
  294.                                     aMaxTotalProgress ) {
  295.         },
  296.  
  297.         onProgressChange64: function( aWebProgress,
  298.                                       aRequest,
  299.                                       aCurSelfProgress,
  300.                                       aMaxSelfProgress,
  301.                                       aCurTotalProgress,
  302.                                       aMaxTotalProgress ) {
  303.         },
  304.  
  305.  
  306.  
  307.         onStateChange: function( aWebProgress, aRequest, aStateFlags, aStatus ) {
  308.         },
  309.  
  310.         onLocationChange: function( aWebProgress, aRequest, aLocation ) {
  311.         },
  312.  
  313.         onSecurityChange: function( aWebProgress, aRequest, state ) {
  314.         }
  315.     },
  316.  
  317.     // initDialog:  Fill various dialog fields with initial content.
  318.     initDialog : function() {
  319.       // Put file name in window title.
  320.       var suggestedFileName = this.mLauncher.suggestedFileName;
  321.  
  322.       // Some URIs do not implement nsIURL, so we can't just QI.
  323.       var url   = this.mLauncher.source;
  324.       var fname = "";
  325.       this.mSourcePath = url.prePath;
  326.       try {
  327.           url = url.QueryInterface( Components.interfaces.nsIURL );
  328.           // A url, use file name from it.
  329.           fname = url.fileName;
  330.           this.mSourcePath += url.directory;
  331.       } catch (ex) {
  332.           // A generic uri, use path.
  333.           fname = url.path;
  334.           this.mSourcePath += url.path;
  335.       }
  336.  
  337.       if (suggestedFileName)
  338.         fname = suggestedFileName;
  339.       
  340.       var displayName = fname.replace(/ +/g, " ");
  341.  
  342.       this.mTitle = this.dialogElement("strings").getFormattedString("title", [displayName]);
  343.       this.mDialog.document.title = this.mTitle;
  344.  
  345.       // Put content type, filename and location into intro.
  346.       this.initIntro(url, fname, displayName);
  347.  
  348.       var iconString = "moz-icon://" + fname + "?size=16&contentType=" + this.mLauncher.MIMEInfo.MIMEType;
  349.       this.dialogElement("contentTypeImage").setAttribute("src", iconString);
  350.  
  351.       this.initAppAndSaveToDiskValues();
  352.  
  353.       // Initialize "always ask me" box. This should always be disabled
  354.       // and set to true for the ambiguous type application/octet-stream.
  355.       // We don't also check for application/x-msdownload here since we
  356.       // want users to be able to autodownload .exe files. 
  357.       var rememberChoice = this.dialogElement("rememberChoice");
  358.  
  359. //@line 424 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  360.       var mimeType = this.mLauncher.MIMEInfo.MIMEType;
  361.       if (mimeType == "application/octet-stream" || 
  362.           mimeType == "application/x-msdownload" ||
  363.           this.mLauncher.targetFile.isExecutable()) {
  364.         rememberChoice.checked = false;
  365.         rememberChoice.disabled = true;
  366.       }
  367.       else {
  368.         rememberChoice.checked = !this.mLauncher.MIMEInfo.alwaysAskBeforeHandling;
  369.       }
  370.       this.toggleRememberChoice(rememberChoice);
  371.  
  372.       // XXXben - menulist won't init properly, hack. 
  373.       var openHandler = this.dialogElement("openHandler");
  374.       openHandler.parentNode.removeChild(openHandler);
  375.       var openHandlerBox = this.dialogElement("openHandlerBox");
  376.       openHandlerBox.appendChild(openHandler);
  377.  
  378.       this.mDialog.setTimeout("dialog.postShowCallback()", 0);
  379.       
  380.       this.mDialog.document.documentElement.getButton("accept").disabled = true;
  381.       const nsITimer = Components.interfaces.nsITimer;
  382.       this._timer = Components.classes["@mozilla.org/timer;1"]
  383.                               .createInstance(nsITimer);
  384.       this._timer.initWithCallback(this, 250, nsITimer.TYPE_ONE_SHOT);
  385.     },
  386.     
  387.     _timer: null,
  388.     notify: function (aTimer) {
  389.       try { // The user may have already canceled the dialog.
  390.         if (!this._blurred)
  391.           this.mDialog.document.documentElement.getButton('accept').disabled = false;
  392.       } catch (ex) {}
  393.       this._delayExpired = true;
  394.       this._timer = null; // the timer won't release us, so we have to release it
  395.     },
  396.     
  397.     postShowCallback: function () {
  398.       this.mDialog.sizeToContent();
  399.  
  400.       // Set initial focus
  401.       this.dialogElement("mode").focus();
  402.     },
  403.  
  404.     // initIntro:
  405.     initIntro: function(url, filename, displayname) {
  406.         this.dialogElement( "location" ).value = displayname;
  407.         this.dialogElement( "location" ).setAttribute("realname", filename);
  408.         this.dialogElement( "location" ).setAttribute("tooltiptext", displayname);
  409.  
  410.         // if mSourcePath is a local file, then let's use the pretty path name instead of an ugly
  411.         // url...
  412.         var pathString = this.mSourcePath;
  413.         try 
  414.         {
  415.           var fileURL = url.QueryInterface(Components.interfaces.nsIFileURL);
  416.           if (fileURL)
  417.           {
  418.             var fileObject = fileURL.file;
  419.             if (fileObject)
  420.             {
  421.               var parentObject = fileObject.parent;
  422.               if (parentObject)
  423.               {
  424.                 pathString = parentObject.path;
  425.               }
  426.             }
  427.           }
  428.         } catch(ex) {}
  429.  
  430.         if (pathString == this.mSourcePath)
  431.         {
  432.           // wasn't a fileURL
  433.           var tmpurl = url.clone(); // don't want to change the real url
  434.           try {
  435.             tmpurl.userPass = "";
  436.           } catch (ex) {}
  437.           pathString = tmpurl.prePath;
  438.         }
  439.  
  440.         // Set the location text, which is separate from the intro text so it can be cropped
  441.         var location = this.dialogElement( "source" );
  442.         location.value = pathString;
  443.         location.setAttribute("tooltiptext", this.mSourcePath);
  444.         
  445.         // Show the type of file. 
  446.         var type = this.dialogElement("type");
  447.         var mimeInfo = this.mLauncher.MIMEInfo;
  448.         
  449.         // 1. Try to use the pretty description of the type, if one is available.
  450.         var typeString = mimeInfo.description;
  451.         
  452.         if (typeString == "") {
  453.           // 2. If there is none, use the extension to identify the file, e.g. "ZIP file"
  454.           var primaryExtension = "";
  455.           try {
  456.             primaryExtension = mimeInfo.primaryExtension;
  457.           }
  458.           catch (ex) {
  459.           }
  460.           if (primaryExtension != "")
  461.             typeString = primaryExtension.toUpperCase() + " file";
  462.           // 3. If we can't even do that, just give up and show the MIME type. 
  463.           else
  464.             typeString = mimeInfo.MIMEType;
  465.         }
  466.         
  467.         type.value = typeString;
  468.     },
  469.     
  470.     _blurred: false,
  471.     _delayExpired: false, 
  472.     onBlur: function(aEvent) {
  473.       if (aEvent.target != this.mDialog.document)
  474.         return;
  475.       this._blurred = true;
  476.       this.mDialog.document.documentElement.getButton("accept").disabled = true;
  477.     },
  478.     
  479.     onFocus: function(aEvent) {
  480.       if (aEvent.target != this.mDialog.document)
  481.         return;
  482.       this._blurred = false;
  483.       if (this._delayExpired) {
  484.         var script = "document.documentElement.getButton('accept').disabled = false";
  485.         this.mDialog.setTimeout(script, 250);
  486.       }
  487.     },
  488.  
  489.     // Returns true if opening the default application makes sense.
  490.     openWithDefaultOK: function() {
  491.         var result;
  492.  
  493.         // The checking is different on Windows...
  494. //@line 572 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  495.             // On other platforms, default is Ok if there is a default app.
  496.             // Note that nsIMIMEInfo providers need to ensure that this holds true
  497.             // on each platform.
  498.         return this.mLauncher.MIMEInfo.hasDefaultHandler;
  499. //@line 577 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  500.     },
  501.     
  502.     // Set "default" application description field.
  503.     initDefaultApp: function() {
  504.       // Use description, if we can get one.
  505.       var desc = this.mLauncher.MIMEInfo.defaultDescription;
  506.       if (desc) {
  507.         var defaultApp = this.dialogElement("strings").getFormattedString("defaultApp", [desc]);
  508.         this.dialogElement("defaultHandler").label = defaultApp;
  509.       }
  510.       else {
  511.         this.dialogElement("modeDeck").setAttribute("selectedIndex", "1");
  512.         // Hide the default handler item too, in case the user picks a 
  513.         // custom handler at a later date which triggers the menulist to show.
  514.         this.dialogElement("defaultHandler").hidden = true;
  515.       }
  516.     },
  517.  
  518.     // getPath:
  519.     getPath: function (aFile) {
  520. //@line 600 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  521.       return aFile.path;
  522. //@line 602 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  523.     },
  524.  
  525.     // initAppAndSaveToDiskValues:
  526.     initAppAndSaveToDiskValues: function() {
  527.       var modeGroup = this.dialogElement("mode");
  528.  
  529.       // We don't let users open .exe files or random binary data directly 
  530.       // from the browser at the moment because of security concerns. 
  531.       var openWithDefaultOK = this.openWithDefaultOK();
  532.       var mimeType = this.mLauncher.MIMEInfo.MIMEType;
  533.       if (this.mLauncher.targetFile.isExecutable() || (
  534.           (mimeType == "application/octet-stream" ||
  535.            mimeType == "application/x-msdownload") && 
  536.            !openWithDefaultOK)) {
  537.         this.dialogElement("open").disabled = true;
  538.         var openHandler = this.dialogElement("openHandler");
  539.         openHandler.disabled = true;
  540.         openHandler.selectedItem = null;
  541.         modeGroup.selectedItem = this.dialogElement("save");
  542.         return;
  543.       }
  544.     
  545.       // Fill in helper app info, if there is any.
  546.       this.chosenApp = this.mLauncher.MIMEInfo.preferredApplicationHandler;
  547.       // Initialize "default application" field.
  548.       this.initDefaultApp();
  549.  
  550.       var otherHandler = this.dialogElement("otherHandler");
  551.               
  552.       // Fill application name textbox.
  553.       if (this.chosenApp && this.chosenApp.path) {
  554.         otherHandler.setAttribute("path", this.getPath(this.chosenApp));
  555.         otherHandler.label = this.chosenApp.leafName;
  556.         otherHandler.hidden = false;
  557.       }
  558.  
  559.       var useDefault = this.dialogElement("useSystemDefault");
  560.       var openHandler = this.dialogElement("openHandler");
  561.       openHandler.selectedIndex = 0;
  562.  
  563.       if (this.mLauncher.MIMEInfo.preferredAction == this.nsIMIMEInfo.useSystemDefault) {
  564.         // Open (using system default).
  565.         modeGroup.selectedItem = this.dialogElement("open");
  566.       } else if (this.mLauncher.MIMEInfo.preferredAction == this.nsIMIMEInfo.useHelperApp) {
  567.         // Open with given helper app.
  568.         modeGroup.selectedItem = this.dialogElement("open");
  569.         openHandler.selectedIndex = 1;
  570.       } else {
  571.         // Save to disk.
  572.         modeGroup.selectedItem = this.dialogElement("save");
  573.       }
  574.       
  575.       // If we don't have a "default app" then disable that choice.
  576.       if (!openWithDefaultOK) {
  577.         var useDefault = this.dialogElement("defaultHandler");
  578.         var isSelected = useDefault.selected;
  579.         
  580.         // Disable that choice.
  581.         useDefault.hidden = true;
  582.         // If that's the default, then switch to "save to disk."
  583.         if (isSelected) {
  584.           openHandler.selectedIndex = 1;
  585.           modeGroup.selectedItem = this.dialogElement("save");
  586.         }
  587.       }
  588.       
  589.       // otherHandler is always disabled on Mac
  590. //@line 673 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  591.       otherHandler.nextSibling.hidden = otherHandler.nextSibling.nextSibling.hidden = false;
  592. //@line 675 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  593.       this.updateOKButton();
  594.     },
  595.  
  596.     // Returns the user-selected application
  597.     helperAppChoice: function() {
  598.       return this.chosenApp;
  599.     },
  600.     
  601.     get saveToDisk() {
  602.       return this.dialogElement("save").selected;
  603.     },
  604.     
  605.     get useOtherHandler() {
  606.       return this.dialogElement("open").selected && this.dialogElement("openHandler").selectedIndex == 1;
  607.     },
  608.     
  609.     get useSystemDefault() {
  610.       return this.dialogElement("open").selected && this.dialogElement("openHandler").selectedIndex == 0;
  611.     },
  612.     
  613.     toggleRememberChoice: function (aCheckbox) {
  614.         this.dialogElement("settingsChange").hidden = !aCheckbox.checked;
  615.         this.mDialog.sizeToContent();
  616.     },
  617.     
  618.     openHandlerCommand: function () {
  619.       var openHandler = this.dialogElement("openHandler");
  620.       if (openHandler.selectedItem.id == "choose")
  621.         this.chooseApp();
  622.       else
  623.         openHandler.setAttribute("lastSelectedItemID", openHandler.selectedItem.id);
  624.     },
  625.  
  626.     updateOKButton: function() {
  627.       var ok = false;
  628.       if (this.dialogElement("save").selected) {
  629.         // This is always OK.
  630.         ok = true;
  631.       } 
  632.       else if (this.dialogElement("open").selected) {
  633.         switch (this.dialogElement("openHandler").selectedIndex) {
  634.         case 0:
  635.           // No app need be specified in this case.
  636.           ok = true;
  637.           break;
  638.         case 1:
  639.           // only enable the OK button if we have a default app to use or if 
  640.           // the user chose an app....
  641.           ok = this.chosenApp || /\S/.test(this.dialogElement("otherHandler").getAttribute("path")); 
  642.         break;
  643.         }
  644.       }
  645.  
  646.       // Enable Ok button if ok to press.
  647.       this.mDialog.document.documentElement.getButton("accept").disabled = !ok;
  648.     },
  649.     
  650.     // Returns true iff the user-specified helper app has been modified.
  651.     appChanged: function() {
  652.       return this.helperAppChoice() != this.mLauncher.MIMEInfo.preferredApplicationHandler;
  653.     },
  654.  
  655.     updateMIMEInfo: function() {
  656.       var needUpdate = false;
  657.       // If current selection differs from what's in the mime info object,
  658.       // then we need to update.
  659.       if (this.saveToDisk) {
  660.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.saveToDisk;
  661.         if (needUpdate)
  662.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.saveToDisk;
  663.       } 
  664.       else if (this.useSystemDefault) {
  665.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.useSystemDefault;
  666.         if (needUpdate)
  667.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.useSystemDefault;
  668.       } 
  669.       else {
  670.         // For "open with", we need to check both preferred action and whether the user chose
  671.         // a new app.
  672.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.useHelperApp || this.appChanged();
  673.         if (needUpdate) {
  674.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.useHelperApp;
  675.           // App may have changed - Update application and description
  676.           var app = this.helperAppChoice();
  677.           this.mLauncher.MIMEInfo.preferredApplicationHandler = app;
  678.           this.mLauncher.MIMEInfo.applicationDescription = "";
  679.         }
  680.       }
  681.       // We will also need to update if the "always ask" flag has changed.
  682.       needUpdate = needUpdate || this.mLauncher.MIMEInfo.alwaysAskBeforeHandling != (!this.dialogElement("rememberChoice").checked);
  683.  
  684.       // One last special case: If the input "always ask" flag was false, then we always
  685.       // update.  In that case we are displaying the helper app dialog for the first
  686.       // time for this mime type and we need to store the user's action in the mimeTypes.rdf
  687.       // data source (whether that action has changed or not; if it didn't change, then we need
  688.       // to store the "always ask" flag so the helper app dialog will or won't display
  689.       // next time, per the user's selection).
  690.       needUpdate = needUpdate || !this.mLauncher.MIMEInfo.alwaysAskBeforeHandling;
  691.  
  692.       // Make sure mime info has updated setting for the "always ask" flag.
  693.       this.mLauncher.MIMEInfo.alwaysAskBeforeHandling = !this.dialogElement("rememberChoice").checked;
  694.  
  695.       return needUpdate;        
  696.     },
  697.     
  698.     // See if the user changed things, and if so, update the
  699.     // mimeTypes.rdf entry for this mime type.
  700.     updateHelperAppPref: function() {
  701.       var ha = new this.mDialog.HelperApps();
  702.       ha.updateTypeInfo(this.mLauncher.MIMEInfo);
  703.     },
  704.     
  705.     // onOK:
  706.     onOK: function() {
  707.       // Verify typed app path, if necessary.
  708.       if (this.useOtherHandler) {
  709.         var helperApp = this.helperAppChoice();
  710.         if (!helperApp || !helperApp.exists()) {
  711.           // Show alert and try again.        
  712.           var bundle = this.dialogElement("strings");                    
  713.           var msg = bundle.getFormattedString("badApp", [this.dialogElement("otherHandler").path]);
  714.           var svc = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
  715.           svc.alert(this.mDialog, bundle.getString("badApp.title"), msg);
  716.  
  717.           // Disable the OK button.
  718.           this.mDialog.document.documentElement.getButton("accept").disabled = true;
  719.           this.dialogElement("mode").focus();          
  720.  
  721.           // Clear chosen application.
  722.           this.chosenApp = null;
  723.  
  724.           // Leave dialog up.
  725.           return false;
  726.         }
  727.       }
  728.         
  729.       // Remove our web progress listener (a progress dialog will be
  730.       // taking over).
  731.       this.mLauncher.setWebProgressListener(null);
  732.       
  733.       // saveToDisk and launchWithApplication can return errors in 
  734.       // certain circumstances (e.g. The user clicks cancel in the
  735.       // "Save to Disk" dialog. In those cases, we don't want to
  736.       // update the helper application preferences in the RDF file.
  737.       try {
  738.         var needUpdate = this.updateMIMEInfo();
  739.         
  740.         if (this.dialogElement("save").selected) {
  741.           // If we're using a default download location, create a path
  742.           // for the file to be saved to to pass to |saveToDisk| - otherwise
  743.           // we must ask the user to pick a save name.
  744.  
  745. //@line 841 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  746.           this.mLauncher.saveToDisk(null, false);
  747.         }
  748.         else
  749.           this.mLauncher.launchWithApplication(null, false);
  750.  
  751.         // Update user pref for this mime type (if necessary). We do not
  752.         // store anything in the mime type preferences for the ambiguous
  753.         // type application/octet-stream. We do NOT do this for 
  754.         // application/x-msdownload since we want users to be able to 
  755.         // autodownload these to disk. 
  756.         if (needUpdate && this.mLauncher.MIMEInfo.MIMEType != "application/octet-stream")
  757.           this.updateHelperAppPref();
  758.       } catch(e) { }
  759.  
  760.       // Unhook dialog from this object.
  761.       this.mDialog.dialog = null;
  762.  
  763.       // Close up dialog by returning true.
  764.       return true;
  765.     },
  766.  
  767.     // onCancel:
  768.     onCancel: function() {
  769.       // Remove our web progress listener.
  770.       this.mLauncher.setWebProgressListener(null);
  771.  
  772.       // Cancel app launcher.
  773.       try {
  774.         const NS_BINDING_ABORTED = 0x804b0002;
  775.         this.mLauncher.cancel(NS_BINDING_ABORTED);
  776.       } catch(exception) {
  777.       }
  778.  
  779.       // Unhook dialog from this object.
  780.       this.mDialog.dialog = null;
  781.  
  782.       // Close up dialog by returning true.
  783.       return true;
  784.     },
  785.  
  786.     // dialogElement:  Convenience. 
  787.     dialogElement: function(id) {
  788.       return this.mDialog.document.getElementById(id);
  789.     },
  790.  
  791.     // chooseApp:  Open file picker and prompt user for application.
  792.     chooseApp: function() {
  793.       var nsIFilePicker = Components.interfaces.nsIFilePicker;
  794.       var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  795.       fp.init(this.mDialog,
  796.               this.dialogElement("strings").getString("chooseAppFilePickerTitle"),
  797.               nsIFilePicker.modeOpen);
  798.  
  799.       fp.appendFilters(nsIFilePicker.filterApps);
  800.  
  801.       if (fp.show() == nsIFilePicker.returnOK && fp.file) {
  802.         // Show the "handler" menulist since we have a (user-specified) 
  803.         // application now.
  804.         this.dialogElement("modeDeck").setAttribute("selectedIndex", "0");
  805.         
  806.         // Remember the file they chose to run.
  807.         this.chosenApp = fp.file;
  808.         // Update dialog.
  809.         var otherHandler = this.dialogElement("otherHandler");
  810.         otherHandler.removeAttribute("hidden");
  811.         otherHandler.setAttribute("path", this.getPath(this.chosenApp));
  812.         otherHandler.label = this.chosenApp.leafName;
  813.         this.dialogElement("openHandler").selectedIndex = 1;
  814.         this.dialogElement("openHandler").setAttribute("lastSelectedItemID", "otherHandler");
  815.         
  816.         this.dialogElement("mode").selectedItem = this.dialogElement("open");
  817.       }
  818.       else {
  819.         var openHandler = this.dialogElement("openHandler");
  820.         var lastSelectedID = openHandler.getAttribute("lastSelectedItemID");
  821.         if (!lastSelectedID)
  822.           lastSelectedID = "defaultHandler";
  823.         openHandler.selectedItem = this.dialogElement(lastSelectedID);
  824.       }
  825.     },
  826.  
  827.     // Turn this on to get debugging messages.
  828.     debug: false,
  829.  
  830.     // Dump text (if debug is on).
  831.     dump: function( text ) {
  832.         if ( this.debug ) {
  833.             dump( text ); 
  834.         }
  835.     },
  836.  
  837.     // dumpInfo:
  838.     doDebug: function() {
  839.         const nsIProgressDialog = Components.interfaces.nsIProgressDialog;
  840.         // Open new progress dialog.
  841.         var progress = Components.classes[ "@mozilla.org/progressdialog;1" ]
  842.                          .createInstance( nsIProgressDialog );
  843.         // Show it.
  844.         progress.open( this.mDialog );
  845.     },
  846.  
  847.     // dumpObj:
  848.     dumpObj: function( spec ) {
  849.          var val = "<undefined>";
  850.          try {
  851.              val = eval( "this."+spec ).toString();
  852.          } catch( exception ) {
  853.          }
  854.          this.dump( spec + "=" + val + "\n" );
  855.     },
  856.  
  857.     // dumpObjectProperties
  858.     dumpObjectProperties: function( desc, obj ) {
  859.          for( prop in obj ) {
  860.              this.dump( desc + "." + prop + "=" );
  861.              var val = "<undefined>";
  862.              try {
  863.                  val = obj[ prop ];
  864.              } catch ( exception ) {
  865.              }
  866.              this.dump( val + "\n" );
  867.          }
  868.     }
  869. }
  870.  
  871. // This Component's module implementation.  All the code below is used to get this
  872. // component registered and accessible via XPCOM.
  873. var module = {
  874.     firstTime: true,
  875.  
  876.     // registerSelf: Register this component.
  877.     registerSelf: function (compMgr, fileSpec, location, type) {
  878.         if (this.firstTime) {
  879.             this.firstTime = false;
  880.             throw Components.results.NS_ERROR_FACTORY_REGISTER_AGAIN;
  881.         }
  882.         compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  883.  
  884.         compMgr.registerFactoryLocation( this.cid,
  885.                                          "Unknown Content Type Dialog",
  886.                                          this.contractId,
  887.                                          fileSpec,
  888.                                          location,
  889.                                          type );
  890.     },
  891.  
  892.     // getClassObject: Return this component's factory object.
  893.     getClassObject: function (compMgr, cid, iid) {
  894.         if (!cid.equals(this.cid)) {
  895.             throw Components.results.NS_ERROR_NO_INTERFACE;
  896.         }
  897.  
  898.         if (!iid.equals(Components.interfaces.nsIFactory)) {
  899.             throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  900.         }
  901.  
  902.         return this.factory;
  903.     },
  904.  
  905.     /* CID for this class */
  906.     cid: Components.ID("{F68578EB-6EC2-4169-AE19-8C6243F0ABE1}"),
  907.  
  908.     /* Contract ID for this class */
  909.     contractId: "@mozilla.org/helperapplauncherdialog;1",
  910.  
  911.     /* factory object */
  912.     factory: {
  913.         // createInstance: Return a new nsProgressDialog object.
  914.         createInstance: function (outer, iid) {
  915.             if (outer != null)
  916.                 throw Components.results.NS_ERROR_NO_AGGREGATION;
  917.  
  918.             return (new nsUnknownContentTypeDialog()).QueryInterface(iid);
  919.         }
  920.     },
  921.  
  922.     // canUnload: n/a (returns true)
  923.     canUnload: function(compMgr) {
  924.         return true;
  925.     }
  926. };
  927.  
  928. // NSGetModule: Return the nsIModule object.
  929. function NSGetModule(compMgr, fileSpec) {
  930.     return module;
  931. }
  932.