<?xml version="1.0"?>
<!--
   The contents of this file are subject to the Netscape Public
   License Version 1.1 (the "License"); you may not use this file
   except in compliance with the License. You may obtain a copy of
   the License at http://www.mozilla.org/NPL/
    
   Software distributed under the License is distributed on an "AS
   IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
   implied. See the License for the specific language governing
   rights and limitations under the License.
    
   The Original Code is Mozilla Communicator client code, released
   March 31, 1998.
   
   The Initial Developer of the Original Code is Netscape
   Communications Corporation. Portions created by Netscape are
   Copyright (C) 1998-1999 Netscape Communications Corporation. All
   Rights Reserved.
   
   Contributor(s): 
     Ben Goodger <ben@netscape.com>, original implementor
  -->

<?xml-stylesheet href="chrome://communicator/skin/"?>
<?xml-stylesheet href="chrome://communicator/skin/prefpanels.css" type="text/css"?>

<?xul-overlay href="chrome://global/content/dialogOverlay.xul"?>

<!DOCTYPE window SYSTEM "chrome://communicator/locale/pref/pref-applications-edit.dtd">

<window id="pickAppHandler"
        class="dialog" style="width: 30em; -moz-user-focus: ignore;"
        orient="vertical"
        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
        title="&editType.label;"
        onload="Startup();">
    <stringbundle id="bundle_prefApplications"
                  src="chrome://communicator/locale/pref/pref-applications.properties"/>
  <script type="application/x-javascript" src="chrome://communicator/content/pref/overrideHandler.js"/>
  <script type="application/x-javascript">
  <![CDATA[
    var gExtensionLabel   = null;
    var gMIMEField        = null;
    var gHandlerGroup     = null;
    var gAppPath          = null;
    var gAskBeforeOpen    = null;
    var gContentType      = null;
    var gPrefApplicationsBundle = null;

    var gOldMIME          = null;
    var gOldDesc          = null;
    var gOldExtensions   = null;
    
    function Startup()
    {
      doSetOKCancel(onOK);
      
      gContentType      = document.getElementById("contentType");
      gExtensionLabel   = document.getElementById("extension");
      gMIMEField        = document.getElementById("mimeType");
      gHandlerGroup     = document.getElementById("handler");
      gAppPath          = document.getElementById("appPath");
      gAskBeforeOpen    = document.getElementById("askBeforeOpen");
        
      gPrefApplicationsBundle = document.getElementById("bundle_prefApplications");
      
      var handlerInfo = window.arguments[0];

      // Test to see if this dialog is being called from the helper app dialog.
      if ( !( "URI" in handlerInfo ) ) {
        // Arg is an nsHelperAppDlg object in this case.
        window.gHelperAppDlg = window.arguments[0];
        var info = window.arguments[0].mLauncher.MIMEInfo;

        // Get mime type from which we can construct a HandlerInfo...
        var mimeType = info.MIMEType;

        // Construct what we need from mime type URI.
        getDS();
        handlerInfo = window.arguments[0] = new HandlerOverride( MIME_URI( mimeType ) );
      }

      gExtensionLabel.setAttribute("value", handlerInfo.extensions);
      gMIMEField.value = handlerInfo.mimeType;
      gOldMIME = handlerInfo.mimeType;
      gOldDesc = handlerInfo.description;
      gOldExtensions = handlerInfo.extensions;
      
      // figure out how this type is handled
      var data = 0;
      if (handlerInfo.handleInternal == "true")
        data = 0;
      else if (handlerInfo.saveToDisk == "true")
        data = 1;
      else 
        data = 2;
        
      gHandlerGroup.selectedItem = gHandlerGroup.getElementsByAttribute("value", data)[0];
      doEnabling();
      
      var appPath = handlerInfo.appPath;
      if (appPath != undefined)
        gAppPath.value = appPath;

      var prefs = Components.classes["@mozilla.org/preferences;1"].
        getService(Components.interfaces.nsIPrefBranch);
      var forceAlwaysAsk = prefs.
        getBoolPref("browser.helperApps.alwaysAsk.force");

      if (forceAlwaysAsk)
      {
        gAskBeforeOpen.checked = true;
        gAskBeforeOpen.disabled = true;
      }
      else
      {
        gAskBeforeOpen.checked = handlerInfo.alwaysAsk == "true" ? true : false;
      }
      
      gContentType.setAttribute("value", handlerInfo.description);
      var ext;
      var posOfFirstSpace = handlerInfo.extensions.indexOf(" ");
      if (posOfFirstSpace > -1)
        ext = handlerInfo.extensions.substr(0, posOfFirstSpace);
      else
        ext = handlerInfo.extensions;
      var imageString = "moz-icon://" + "dummy." + ext.toLowerCase() + "?size=32&contentType=" + handlerInfo.mimeType;
      document.getElementById("contentTypeImage").setAttribute("src", imageString);
      
      gMIMEField.focus();
    }
    
    function doEnabling()
    {
    }
    
    function chooseApp()
    {
      var filePicker = Components.classes["@mozilla.org/filepicker;1"].createInstance();
      if (filePicker)
        filePicker = filePicker.QueryInterface(Components.interfaces.nsIFilePicker);
      if (filePicker) {
        const FP = Components.interfaces.nsIFilePicker
        var windowTitle = gPrefApplicationsBundle.getString("chooseHandler");
        var programsFilter = gPrefApplicationsBundle.getString("programsFilter");
        filePicker.init(window, windowTitle, FP.modeOpen);
        if (navigator.platform == "Win32")
          filePicker.appendFilter(programsFilter, "*.exe; *.com");
        else
          filePicker.appendFilters(FP.filterAll);
        filePicker.show();
        var file = filePicker.file.QueryInterface(Components.interfaces.nsILocalFile);
        gAppPath.value = file.path;
        gAppPath.select();
        selectAppRadio();
      }
    }
    
    function selectAppRadio()
    {
      if (gHandlerGroup.value != "2") 
        gHandlerGroup.selectedItem = gHandlerGroup.getElementsByAttribute("value", "2")[0];
      doEnabling();
    }

    var gDS = null;
    function getDS()
    {
      const mimeTypes = "UMimTyp";
      var fileLocator = Components.classes["@mozilla.org/file/directory_service;1"].getService();
      if (fileLocator)
        fileLocator = fileLocator.QueryInterface(Components.interfaces.nsIProperties);
      var file = fileLocator.get(mimeTypes, Components.interfaces.nsIFile);
      gDS = gRDF.GetDataSource(file.URL);
      if (gDS)
        gDS = gDS.QueryInterface(Components.interfaces.nsIRDFDataSource);
    }

    function onOK()
    {
      getDS();
      // figure out if this mime type already exists. 
      if (gMIMEField.value != gOldMIME) {
        var exists = mimeHandlerExists(gMIMEField.value);
        if (exists) {
          var titleMsg = gPrefApplicationsBundle.getString("handlerExistsTitle");
          var dialogMsg = gPrefApplicationsBundle.getString("handlerExists");
          dialogMsg = dialogMsg.replace(/%mime%/g, gMIMEField.value);
          var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
          var replace = promptService.confirm(window, titleMsg, dialogMsg);
          if (!replace)
            window.close();
          
          // delete mimetype we're overwriting
          if (gMIMEField.value)
            removeOverride(gMIMEField.value);
        }
      }
      
      if (gOldMIME)
        removeOverride(gOldMIME); // delete old handler

      // now save the information
      var handlerInfo = new HandlerOverride(MIME_URI(gMIMEField.value));
      handlerInfo.mUpdateMode = mimeHandlerExists(gMIMEField.value);
      handlerInfo.mimeType = gMIMEField.value;
    
      // set description, editable, and extensions
      handlerInfo.description = gOldDesc
      handlerInfo.isEditable = true;
      var extensions = gOldExtensions.split(" ");
      for (var i = 0; i < extensions.length; i++) {
        var currExtension = extensions[i];
        handlerInfo.addExtension(currExtension);
      }
    
      // other info we need to set (not reflected in UI)
      if (gHandlerGroup.value == "2") {
        handlerInfo.appPath = gAppPath.value;
        handlerInfo.setHandlerProcedure("saveToDisk", "false");
        handlerInfo.setHandlerProcedure("handleInternal", "false");
      }
      else if (gHandlerGroup.value == "1")
        handlerInfo.saveToDisk = true;
      else
        handlerInfo.handleInternal = true;
    
      handlerInfo.alwaysAsk = gAskBeforeOpen.checked;
    
      // need to make the following dynamic to track changes. otherwise the 
      // app pretty name remains the same.
      // better still, find a way to XP dynamically discover the pretty name of the app
      // from the OS. 
      var file = Components.classes["@mozilla.org/file/local;1"].createInstance();
      if (file)
        file = file.QueryInterface(Components.interfaces.nsILocalFile);
      if (file) {
        try {
          file.initWithPath(gAppPath.value);
          handlerInfo.appDisplayName = file.unicodeLeafName;
        }
        catch(e) {
          handlerInfo.appDisplayName = gAppPath.value;    
        }
      }

      // do the rest of the work (ugly yes, but it works)
      handlerInfo.buildLinks();
      
      // flush the ds to disk.   
      var remoteDS = gDS.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource);
      if (remoteDS)
        remoteDS.Flush();
      
      // See if invoked on behalf of helper app dialog...
      if ( "gHelperAppDlg" in window ) {
          // Get mime info.
          var info = gHelperAppDlg.mLauncher.MIMEInfo;
    
          // Update fields that might have changed.
          if ( gHandlerGroup.value == "1" ) {
              info.preferredAction = Components.interfaces.nsIMIMEInfo.saveToDisk;
          } else if ( gHandlerGroup.value == "2" ) {
              info.preferredAction = Components.interfaces.nsIMIMEInfo.useHelperApp;
              info.preferredApplicationHandler = file;
              info.applicationDescription = handlerInfo.appDisplayName;
          } else {
              info.preferredAction = Components.interfaces.nsIMIMEInfo.handleInternally;
          }
      }
    
      window.opener.gUpdateTypeRV = true;
      window.close();  
    }
  ]]>
  </script>
  
  <keyset id="dialogKeys"/>
  
  <hbox autostretch="never">
    <image id="contentTypeImage"/>
    <text class="label" id="contentType" crop="right"/>
  </hbox>
  
  <separator class="thin"/>

  <separator class="groove"/>
  
  <separator class="thin"/>

  <grid>
    <columns>
      <column flex="1"/>
      <column flex="3"/>
    </columns>
    
    <rows>
      <row autostretch="never">
        <text class="label" value="&extension.label;"/>
        <text class="label" id="extension"/>
      </row>
      <row autostretch="never">
        <text class="label" value="&mimetype.label;" accesskey="&mimetype.accesskey;"
              for="mimeType"/>
        <textbox id="mimeType" flex="1"/>
      </row>
    </rows>
  </grid>
  
  <hbox autostretch="never">
    <checkbox id="outgoingDefault" label="&outgoingDefault.label;" accesskey="&outgoingDefault.accesskey;" disabled="true"/>
  </hbox>
  
  <separator class="thin"/>

  <groupbox orient="vertical">
    <label value="&handledby.label;"/>
    
    <radiogroup id="handler" orient="vertical">
      <vbox autostretch="never">
<!-- Turn this off since we can't make it work yet
        <radio value="4" group="handler" label="&useDefault.label;" accesskey="&useDefault.accesskey;" oncommand="doEnabling();"/>
-->
        <radio value="1" group="handler" label="&saveToDisk.label;" accesskey="&saveToDisk.accesskey;" oncommand="doEnabling();"/>
      </vbox>
      <hbox autostretch="never">
        <radio value="2" group="handler" label="&application.label;" accesskey="&application.accesskey;" oncommand="doEnabling();"/>
        <textbox id="appPath" flex="1" onchange="selectAppRadio();"/>
      </hbox>
      <hbox autostretch="never" halign="right">
        <button label="&browse.label;" accesskey="&browse.accesskey;"
                oncommand="chooseApp();"/>
      </hbox>
    </radiogroup>
    
  </groupbox>              

  <hbox autostretch="never">
    <checkbox id="askBeforeOpen" label="&askBeforeOpen.label;" accesskey="&askBeforeOpen.accesskey;"/>         
  </hbox>
  
  <separator/>
  
  <hbox id="okCancelButtonsRight"/>
  
</window>
        
