<?xml version="1.0"?>
<!--
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla 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/MPL/
 *
 * 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.org code.
 *
 * The Initial Developer of the Original Code is
 * Mozilla Corporation.
 * Portions created by the Initial Developer are Copyright (C) 2008
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Shawn Wilsher <me@shawnwilsher.com> (Original Author)
 *   Edward Lee <edward.lee@engineering.uiuc.edu>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

/**
 * This tests that the download manager UI closes upon download completion when
 * browser.download.manager.retention is set to 0.  This test was added in bug
 * 413093.
 */
-->

<window title="Download Manager Test"
        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
        onload="test();">

  <script type="application/javascript"
          src="chrome://mochikit/content/MochiKit/packed.js"/>
  <script type="application/javascript"
          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
  <script type="application/javascript"
          src="utils.js"/>

  <script type="application/javascript">
  <![CDATA[

function setPref(aDoTest)
{
  let prefs = Cc["@mozilla.org/preferences-service;1"].
              getService(Ci.nsIPrefBranch);

  // If we're testing, set retention to auto-remove and auto-close
  prefs.setIntPref("browser.download.manager.retention", aDoTest ? 0 : 2);
  prefs.setBoolPref("browser.download.manager.closeWhenDone", aDoTest);
}

function bug413093obs()
{
  this.mDownload = null;
  this.wasPaused = false;
}
bug413093obs.prototype = {
  observe: function(aSubject, aTopic, aData)
  {
    if ("domwindowopened" == aTopic) {
      // If we opened before we were paused, we need to set up our proper state
      // We also should not try to resume (we weren't paused!)
      if (!this.wasPaused) {
        dump("domwindowopened callback - not pausing or resuming\n");
        this.wasPaused = true;
        return;
      }

      dump("domwindowopened callback - resuming download\n");

      // Resume the download now that UI is up and running
      let dm = Cc["@mozilla.org/download-manager;1"].
                getService(Ci.nsIDownloadManager);
      dm.resumeDownload(this.mDownload.id);
    }
    else if("domwindowclosed" == aTopic) {
      let ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
               getService(Ci.nsIWindowWatcher);
      ww.unregisterNotification(this);

      // Let the UI finish doing whatever it needs to do
      SimpleTest.executeSoon(function() {
        setPref(false);

        let dmui = Cc["@mozilla.org/download-manager-ui;1"].
                   getService(Ci.nsIDownloadManagerUI);
        ok(!dmui.visible, "Download Manager UI is not showing");

        // reset the changed config values to default value
        let prefs = Cc["@mozilla.org/preferences-service;1"].
                    getService(Ci.nsIPrefService);
        try {
          prefs.clearUserPref("browser.download.manager.retention");
        }
        catch (err) { }
        try {
          prefs.clearUserPref("browser.download.manager.closeWhenDone");
        }
        catch (err) { }

        SimpleTest.finish();
      });
    }
  },

  onDownloadStateChange: function(aOldState, aDownload)
  {
    if (aDownload.state == Ci.nsIDownloadManager.DOWNLOAD_DOWNLOADING &&
        !this.wasPaused) {
      dump("onDownloadStateChange - pausing download\n");
      this.wasPaused = true;

      // Pause the download until the UI shows up
      let dm = Cc["@mozilla.org/download-manager;1"].
                getService(Ci.nsIDownloadManager);
      dm.pauseDownload(aDownload.id);
    }

    if (aDownload.state == Ci.nsIDownloadManager.DOWNLOAD_FINISHED) {
      aDownload.targetFile.remove(false);

      let dm = Cc["@mozilla.org/download-manager;1"].
                getService(Ci.nsIDownloadManager);
      dm.removeListener(this);

      // If this test is going to pass, we'll get a domwindowclosed notification
    }
  },
  onStateChange: function(a, b, c, d, e) { },
  onProgressChange: function(a, b, c, d, e, f, g) { },
  onSecurityChange: function(a, b, c, d) { },
};
function test()
{
  function addDownload() {
    function createURI(aObj) {
      let ios = Cc["@mozilla.org/network/io-service;1"].
                getService(Ci.nsIIOService);
      return (aObj instanceof Ci.nsIFile) ? ios.newFileURI(aObj) :
                                            ios.newURI(aObj, null, null);
    }

    const nsIWBP = Ci.nsIWebBrowserPersist;
    let persist = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
                  .createInstance(Ci.nsIWebBrowserPersist);
    persist.persistFlags = nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES |
                           nsIWBP.PERSIST_FLAGS_BYPASS_CACHE |
                           nsIWBP.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;

    let dirSvc = Cc["@mozilla.org/file/directory_service;1"].
                 getService(Ci.nsIProperties);
    let destFile = dirSvc.get("ProfD", Ci.nsIFile);
    destFile.append("download.result");
    if (destFile.exists())
      destFile.remove(false);

    let src = createURI("http://example.com/httpd.js");
    let target = createURI(destFile);
    let tr = Cc["@mozilla.org/transfer;1"].createInstance(Ci.nsITransfer);
    tr.init(src, target, "test download", null, Math.round(Date.now() * 1000),
            null, persist);
    persist.progressListener = tr;
    persist.saveURI(src, null, null, null, null, destFile);
  }

  // First, we clear out the database
  let dm = Cc["@mozilla.org/download-manager;1"].
           getService(Ci.nsIDownloadManager);
  dm.DBConnection.executeSimpleSQL("DELETE FROM moz_downloads");

  // See if the DM is already open, and if it is, close it!
  let wm = Cc["@mozilla.org/appshell/window-mediator;1"].
           getService(Ci.nsIWindowMediator);
  let win = wm.getMostRecentWindow("Download:Manager");
  if (win)
    win.close();

  let obs = new bug413093obs();
  dm.addListener(obs);
  setPref(true);

  // Start the test when the download manager window loads
  let ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
           getService(Ci.nsIWindowWatcher);
  ww.registerNotification(obs);

  addDownload();

  SimpleTest.waitForExplicitFinish();
}

  ]]>
  </script>

  <body xmlns="http://www.w3.org/1999/xhtml">
    <p id="display"></p>
    <div id="content" style="display:none;"></div>
    <pre id="test"></pre>
  </body>
</window>
