home *** CD-ROM | disk | FTP | other *** search
/ Computer Shopper 233 / Computer Shopper 233 / ComputerShopperDVD233.iso / Toolkit / Internet / Firefox / Firefox Setup 2.0.0.3.exe / nonlocalized / components / nsHelperAppDlg.js < prev    next >
Encoding:
JavaScript  |  2007-03-10  |  38.4 KB  |  986 lines

  1. /*
  2. //@line 42 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/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 142 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  103.           return "Pers";
  104. //@line 150 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/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.           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 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/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 604 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  540.         // Windows presents some special cases.
  541.         // We need to prevent use of "system default" when the file is
  542.         // executable (so the user doesn't launch nasty programs downloaded
  543.         // from the web), and, enable use of "system default" if it isn't
  544.         // executable (because we will prompt the user for the default app
  545.         // in that case).
  546.         
  547.         // Need to get temporary file and check for executable-ness.
  548.         var tmpFile = this.mLauncher.targetFile;
  549.         
  550.         //  Default is Ok if the file isn't executable (and vice-versa).
  551.         return !tmpFile.isExecutable();
  552. //@line 622 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  553.     },
  554.     
  555.     // Set "default" application description field.
  556.     initDefaultApp: function() {
  557.       // Use description, if we can get one.
  558.       var desc = this.mLauncher.MIMEInfo.defaultDescription;
  559.       if (desc) {
  560.         var defaultApp = this.dialogElement("strings").getFormattedString("defaultApp", [desc]);
  561.         this.dialogElement("defaultHandler").label = defaultApp;
  562.       }
  563.       else {
  564.         this.dialogElement("modeDeck").setAttribute("selectedIndex", "1");
  565.         // Hide the default handler item too, in case the user picks a 
  566.         // custom handler at a later date which triggers the menulist to show.
  567.         this.dialogElement("defaultHandler").hidden = true;
  568.       }
  569.     },
  570.  
  571.     // getPath:
  572.     getPath: function (aFile) {
  573. //@line 645 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  574.       return aFile.path;
  575. //@line 647 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  576.     },
  577.  
  578.     // initAppAndSaveToDiskValues:
  579.     initAppAndSaveToDiskValues: function() {
  580.       var modeGroup = this.dialogElement("mode");
  581.  
  582.       // We don't let users open .exe files or random binary data directly 
  583.       // from the browser at the moment because of security concerns. 
  584.       var openWithDefaultOK = this.openWithDefaultOK();
  585.       var mimeType = this.mLauncher.MIMEInfo.MIMEType;
  586.       if (this.mLauncher.targetFile.isExecutable() || (
  587.           (mimeType == "application/octet-stream" ||
  588.            mimeType == "application/x-msdownload") && 
  589.            !openWithDefaultOK)) {
  590.         this.dialogElement("open").disabled = true;
  591.         var openHandler = this.dialogElement("openHandler");
  592.         openHandler.disabled = true;
  593.         openHandler.selectedItem = null;
  594.         modeGroup.selectedItem = this.dialogElement("save");
  595.         return;
  596.       }
  597.     
  598.       // Fill in helper app info, if there is any.
  599.       this.chosenApp = this.mLauncher.MIMEInfo.preferredApplicationHandler;
  600.       // Initialize "default application" field.
  601.       this.initDefaultApp();
  602.  
  603.       var otherHandler = this.dialogElement("otherHandler");
  604.               
  605.       // Fill application name textbox.
  606.       if (this.chosenApp && this.chosenApp.path) {
  607.         otherHandler.setAttribute("path", this.getPath(this.chosenApp));
  608.         otherHandler.label = this.chosenApp.leafName;
  609.         otherHandler.hidden = false;
  610.       }
  611.  
  612.       var useDefault = this.dialogElement("useSystemDefault");
  613.       var openHandler = this.dialogElement("openHandler");
  614.       openHandler.selectedIndex = 0;
  615.  
  616.       if (this.mLauncher.MIMEInfo.preferredAction == this.nsIMIMEInfo.useSystemDefault) {
  617.         // Open (using system default).
  618.         modeGroup.selectedItem = this.dialogElement("open");
  619.       } else if (this.mLauncher.MIMEInfo.preferredAction == this.nsIMIMEInfo.useHelperApp) {
  620.         // Open with given helper app.
  621.         modeGroup.selectedItem = this.dialogElement("open");
  622.         openHandler.selectedIndex = 1;
  623.       } else {
  624.         // Save to disk.
  625.         modeGroup.selectedItem = this.dialogElement("save");
  626.       }
  627.       
  628.       // If we don't have a "default app" then disable that choice.
  629.       if (!openWithDefaultOK) {
  630.         var useDefault = this.dialogElement("defaultHandler");
  631.         var isSelected = useDefault.selected;
  632.         
  633.         // Disable that choice.
  634.         useDefault.hidden = true;
  635.         // If that's the default, then switch to "save to disk."
  636.         if (isSelected) {
  637.           openHandler.selectedIndex = 1;
  638.           modeGroup.selectedItem = this.dialogElement("save");
  639.         }
  640.       }
  641.       
  642.       // otherHandler is always disabled on Mac
  643. //@line 718 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  644.       otherHandler.nextSibling.hidden = otherHandler.nextSibling.nextSibling.hidden = false;
  645. //@line 720 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  646.       this.updateOKButton();
  647.     },
  648.  
  649.     // Returns the user-selected application
  650.     helperAppChoice: function() {
  651.       return this.chosenApp;
  652.     },
  653.     
  654.     get saveToDisk() {
  655.       return this.dialogElement("save").selected;
  656.     },
  657.     
  658.     get useOtherHandler() {
  659.       return this.dialogElement("open").selected && this.dialogElement("openHandler").selectedIndex == 1;
  660.     },
  661.     
  662.     get useSystemDefault() {
  663.       return this.dialogElement("open").selected && this.dialogElement("openHandler").selectedIndex == 0;
  664.     },
  665.     
  666.     toggleRememberChoice: function (aCheckbox) {
  667.         this.dialogElement("settingsChange").hidden = !aCheckbox.checked;
  668.         this.mDialog.sizeToContent();
  669.     },
  670.     
  671.     openHandlerCommand: function () {
  672.       var openHandler = this.dialogElement("openHandler");
  673.       if (openHandler.selectedItem.id == "choose")
  674.         this.chooseApp();
  675.       else
  676.         openHandler.setAttribute("lastSelectedItemID", openHandler.selectedItem.id);
  677.     },
  678.  
  679.     updateOKButton: function() {
  680.       var ok = false;
  681.       if (this.dialogElement("save").selected) {
  682.         // This is always OK.
  683.         ok = true;
  684.       } 
  685.       else if (this.dialogElement("open").selected) {
  686.         switch (this.dialogElement("openHandler").selectedIndex) {
  687.         case 0:
  688.           // No app need be specified in this case.
  689.           ok = true;
  690.           break;
  691.         case 1:
  692.           // only enable the OK button if we have a default app to use or if 
  693.           // the user chose an app....
  694.           ok = this.chosenApp || /\S/.test(this.dialogElement("otherHandler").getAttribute("path")); 
  695.         break;
  696.         }
  697.       }
  698.  
  699.       // Enable Ok button if ok to press.
  700.       this.mDialog.document.documentElement.getButton("accept").disabled = !ok;
  701.     },
  702.     
  703.     // Returns true iff the user-specified helper app has been modified.
  704.     appChanged: function() {
  705.       return this.helperAppChoice() != this.mLauncher.MIMEInfo.preferredApplicationHandler;
  706.     },
  707.  
  708.     updateMIMEInfo: function() {
  709.       var needUpdate = false;
  710.       // If current selection differs from what's in the mime info object,
  711.       // then we need to update.
  712.       if (this.saveToDisk) {
  713.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.saveToDisk;
  714.         if (needUpdate)
  715.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.saveToDisk;
  716.       } 
  717.       else if (this.useSystemDefault) {
  718.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.useSystemDefault;
  719.         if (needUpdate)
  720.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.useSystemDefault;
  721.       } 
  722.       else {
  723.         // For "open with", we need to check both preferred action and whether the user chose
  724.         // a new app.
  725.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.useHelperApp || this.appChanged();
  726.         if (needUpdate) {
  727.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.useHelperApp;
  728.           // App may have changed - Update application and description
  729.           var app = this.helperAppChoice();
  730.           this.mLauncher.MIMEInfo.preferredApplicationHandler = app;
  731.           this.mLauncher.MIMEInfo.applicationDescription = "";
  732.         }
  733.       }
  734.       // We will also need to update if the "always ask" flag has changed.
  735.       needUpdate = needUpdate || this.mLauncher.MIMEInfo.alwaysAskBeforeHandling != (!this.dialogElement("rememberChoice").checked);
  736.  
  737.       // One last special case: If the input "always ask" flag was false, then we always
  738.       // update.  In that case we are displaying the helper app dialog for the first
  739.       // time for this mime type and we need to store the user's action in the mimeTypes.rdf
  740.       // data source (whether that action has changed or not; if it didn't change, then we need
  741.       // to store the "always ask" flag so the helper app dialog will or won't display
  742.       // next time, per the user's selection).
  743.       needUpdate = needUpdate || !this.mLauncher.MIMEInfo.alwaysAskBeforeHandling;
  744.  
  745.       // Make sure mime info has updated setting for the "always ask" flag.
  746.       this.mLauncher.MIMEInfo.alwaysAskBeforeHandling = !this.dialogElement("rememberChoice").checked;
  747.  
  748.       return needUpdate;        
  749.     },
  750.     
  751.     // See if the user changed things, and if so, update the
  752.     // mimeTypes.rdf entry for this mime type.
  753.     updateHelperAppPref: function() {
  754.       var ha = new this.mDialog.HelperApps();
  755.       ha.updateTypeInfo(this.mLauncher.MIMEInfo);
  756.       ha.destroy();
  757.     },
  758.     
  759.     // onOK:
  760.     onOK: function() {
  761.       // Verify typed app path, if necessary.
  762.       if (this.useOtherHandler) {
  763.         var helperApp = this.helperAppChoice();
  764.         if (!helperApp || !helperApp.exists()) {
  765.           // Show alert and try again.        
  766.           var bundle = this.dialogElement("strings");                    
  767.           var msg = bundle.getFormattedString("badApp", [this.dialogElement("otherHandler").path]);
  768.           var svc = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
  769.           svc.alert(this.mDialog, bundle.getString("badApp.title"), msg);
  770.  
  771.           // Disable the OK button.
  772.           this.mDialog.document.documentElement.getButton("accept").disabled = true;
  773.           this.dialogElement("mode").focus();          
  774.  
  775.           // Clear chosen application.
  776.           this.chosenApp = null;
  777.  
  778.           // Leave dialog up.
  779.           return false;
  780.         }
  781.       }
  782.         
  783.       // Remove our web progress listener (a progress dialog will be
  784.       // taking over).
  785.       this.mLauncher.setWebProgressListener(null);
  786.       
  787.       // saveToDisk and launchWithApplication can return errors in 
  788.       // certain circumstances (e.g. The user clicks cancel in the
  789.       // "Save to Disk" dialog. In those cases, we don't want to
  790.       // update the helper application preferences in the RDF file.
  791.       try {
  792.         var needUpdate = this.updateMIMEInfo();
  793.         
  794.         if (this.dialogElement("save").selected) {
  795.           // If we're using a default download location, create a path
  796.           // for the file to be saved to to pass to |saveToDisk| - otherwise
  797.           // we must ask the user to pick a save name.
  798.  
  799. //@line 887 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  800.           this.mLauncher.saveToDisk(null, false);
  801.         }
  802.         else
  803.           this.mLauncher.launchWithApplication(null, false);
  804.  
  805.         // Update user pref for this mime type (if necessary). We do not
  806.         // store anything in the mime type preferences for the ambiguous
  807.         // type application/octet-stream. We do NOT do this for 
  808.         // application/x-msdownload since we want users to be able to 
  809.         // autodownload these to disk. 
  810.         if (needUpdate && this.mLauncher.MIMEInfo.MIMEType != "application/octet-stream")
  811.           this.updateHelperAppPref();
  812.       } catch(e) { }
  813.  
  814.       // Unhook dialog from this object.
  815.       this.mDialog.dialog = null;
  816.  
  817.       // Close up dialog by returning true.
  818.       return true;
  819.     },
  820.  
  821.     // onCancel:
  822.     onCancel: function() {
  823.       // Remove our web progress listener.
  824.       this.mLauncher.setWebProgressListener(null);
  825.  
  826.       // Cancel app launcher.
  827.       try {
  828.         const NS_BINDING_ABORTED = 0x804b0002;
  829.         this.mLauncher.cancel(NS_BINDING_ABORTED);
  830.       } catch(exception) {
  831.       }
  832.  
  833.       // Unhook dialog from this object.
  834.       this.mDialog.dialog = null;
  835.  
  836.       // Close up dialog by returning true.
  837.       return true;
  838.     },
  839.  
  840.     // dialogElement:  Convenience. 
  841.     dialogElement: function(id) {
  842.       return this.mDialog.document.getElementById(id);
  843.     },
  844.  
  845.     // chooseApp:  Open file picker and prompt user for application.
  846.     chooseApp: function() {
  847.       var nsIFilePicker = Components.interfaces.nsIFilePicker;
  848.       var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  849.       fp.init(this.mDialog,
  850.               this.dialogElement("strings").getString("chooseAppFilePickerTitle"),
  851.               nsIFilePicker.modeOpen);
  852.  
  853.       fp.appendFilters(nsIFilePicker.filterApps);
  854.  
  855.       if (fp.show() == nsIFilePicker.returnOK && fp.file) {
  856.         // Show the "handler" menulist since we have a (user-specified) 
  857.         // application now.
  858.         this.dialogElement("modeDeck").setAttribute("selectedIndex", "0");
  859.         
  860.         // Remember the file they chose to run.
  861.         this.chosenApp = fp.file;
  862.         // Update dialog.
  863.         var otherHandler = this.dialogElement("otherHandler");
  864.         otherHandler.removeAttribute("hidden");
  865.         otherHandler.setAttribute("path", this.getPath(this.chosenApp));
  866.         otherHandler.label = this.chosenApp.leafName;
  867.         this.dialogElement("openHandler").selectedIndex = 1;
  868.         this.dialogElement("openHandler").setAttribute("lastSelectedItemID", "otherHandler");
  869.         
  870.         this.dialogElement("mode").selectedItem = this.dialogElement("open");
  871.       }
  872.       else {
  873.         var openHandler = this.dialogElement("openHandler");
  874.         var lastSelectedID = openHandler.getAttribute("lastSelectedItemID");
  875.         if (!lastSelectedID)
  876.           lastSelectedID = "defaultHandler";
  877.         openHandler.selectedItem = this.dialogElement(lastSelectedID);
  878.       }
  879.     },
  880.  
  881.     // Turn this on to get debugging messages.
  882.     debug: false,
  883.  
  884.     // Dump text (if debug is on).
  885.     dump: function( text ) {
  886.         if ( this.debug ) {
  887.             dump( text ); 
  888.         }
  889.     },
  890.  
  891.     // dumpInfo:
  892.     doDebug: function() {
  893.         const nsIProgressDialog = Components.interfaces.nsIProgressDialog;
  894.         // Open new progress dialog.
  895.         var progress = Components.classes[ "@mozilla.org/progressdialog;1" ]
  896.                          .createInstance( nsIProgressDialog );
  897.         // Show it.
  898.         progress.open( this.mDialog );
  899.     },
  900.  
  901.     // dumpObj:
  902.     dumpObj: function( spec ) {
  903.          var val = "<undefined>";
  904.          try {
  905.              val = eval( "this."+spec ).toString();
  906.          } catch( exception ) {
  907.          }
  908.          this.dump( spec + "=" + val + "\n" );
  909.     },
  910.  
  911.     // dumpObjectProperties
  912.     dumpObjectProperties: function( desc, obj ) {
  913.          for( prop in obj ) {
  914.              this.dump( desc + "." + prop + "=" );
  915.              var val = "<undefined>";
  916.              try {
  917.                  val = obj[ prop ];
  918.              } catch ( exception ) {
  919.              }
  920.              this.dump( val + "\n" );
  921.          }
  922.     }
  923. }
  924.  
  925. // This Component's module implementation.  All the code below is used to get this
  926. // component registered and accessible via XPCOM.
  927. var module = {
  928.     firstTime: true,
  929.  
  930.     // registerSelf: Register this component.
  931.     registerSelf: function (compMgr, fileSpec, location, type) {
  932.         if (this.firstTime) {
  933.             this.firstTime = false;
  934.             throw Components.results.NS_ERROR_FACTORY_REGISTER_AGAIN;
  935.         }
  936.         compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  937.  
  938.         compMgr.registerFactoryLocation( this.cid,
  939.                                          "Unknown Content Type Dialog",
  940.                                          this.contractId,
  941.                                          fileSpec,
  942.                                          location,
  943.                                          type );
  944.     },
  945.  
  946.     // getClassObject: Return this component's factory object.
  947.     getClassObject: function (compMgr, cid, iid) {
  948.         if (!cid.equals(this.cid)) {
  949.             throw Components.results.NS_ERROR_NO_INTERFACE;
  950.         }
  951.  
  952.         if (!iid.equals(Components.interfaces.nsIFactory)) {
  953.             throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  954.         }
  955.  
  956.         return this.factory;
  957.     },
  958.  
  959.     /* CID for this class */
  960.     cid: Components.ID("{F68578EB-6EC2-4169-AE19-8C6243F0ABE1}"),
  961.  
  962.     /* Contract ID for this class */
  963.     contractId: "@mozilla.org/helperapplauncherdialog;1",
  964.  
  965.     /* factory object */
  966.     factory: {
  967.         // createInstance: Return a new nsProgressDialog object.
  968.         createInstance: function (outer, iid) {
  969.             if (outer != null)
  970.                 throw Components.results.NS_ERROR_NO_AGGREGATION;
  971.  
  972.             return (new nsUnknownContentTypeDialog()).QueryInterface(iid);
  973.         }
  974.     },
  975.  
  976.     // canUnload: n/a (returns true)
  977.     canUnload: function(compMgr) {
  978.         return true;
  979.     }
  980. };
  981.  
  982. // NSGetModule: Return the nsIModule object.
  983. function NSGetModule(compMgr, fileSpec) {
  984.     return module;
  985. }
  986.