home *** CD-ROM | disk | FTP | other *** search
/ Chip 2004 April / CMCD0404.ISO / Software / Complet / thunderbird / components / nsDownloadProgressListener.js < prev    next >
Encoding:
JavaScript  |  2004-02-07  |  11.0 KB  |  323 lines

  1. /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
  2. /* ***** BEGIN LICENSE BLOCK *****
  3.  * Version: NPL 1.1/GPL 2.0/LGPL 2.1
  4.  *
  5.  * The contents of this file are subject to the Netscape Public License
  6.  * Version 1.1 (the "License"); you may not use this file except in
  7.  * compliance with the License. You may obtain a copy of the License at
  8.  * http://www.mozilla.org/NPL/
  9.  *
  10.  * Software distributed under the License is distributed on an "AS IS" basis,
  11.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  12.  * for the specific language governing rights and limitations under the
  13.  * License.
  14.  *
  15.  * The Original Code is mozilla.org code.
  16.  *
  17.  * The Initial Developer of the Original Code is 
  18.  * Netscape Communications Corporation.
  19.  * Portions created by the Initial Developer are Copyright (C) 1998
  20.  * the Initial Developer. All Rights Reserved.
  21.  *
  22.  * Contributor(s):
  23.  *   Blake Ross <blaker@netscape.com> (Original Author)
  24.  *
  25.  * Alternatively, the contents of this file may be used under the terms of
  26.  * either the GNU General Public License Version 2 or later (the "GPL"), or 
  27.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  28.  * in which case the provisions of the GPL or the LGPL are applicable instead
  29.  * of those above. If you wish to allow use of your version of this file only
  30.  * under the terms of either the GPL or the LGPL, and not to allow others to
  31.  * use your version of this file under the terms of the NPL, indicate your
  32.  * decision by deleting the provisions above and replace them with the notice
  33.  * and other provisions required by the GPL or the LGPL. If you do not delete
  34.  * the provisions above, a recipient may use your version of this file under
  35.  * the terms of any one of the NPL, the GPL or the LGPL.
  36.  *
  37.  * ***** END LICENSE BLOCK ***** */
  38.  
  39. var gStrings = new Array;
  40. const interval = 500; // Update every 500 milliseconds.
  41.  
  42. function nsDownloadProgressListener() {
  43. }
  44.  
  45. nsDownloadProgressListener.prototype = {
  46.     elapsed: 0,
  47.     rateChanges: 0,
  48.     rateChangeLimit: 0,
  49.     priorRate: "",
  50.     lastUpdate: -500,
  51.     doc: null,
  52.     get document() {
  53.       return this.doc;
  54.     },
  55.     set document(newval) {
  56.       return this.doc = newval;
  57.     },
  58.     onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus, aDownload)
  59.     {
  60.       if (aStateFlags & Components.interfaces.nsIWebProgressListener.STATE_STOP)
  61.       {
  62.         var aDownloadID = aDownload.target.path;
  63.         var elt = this.doc.getElementById(aDownloadID).firstChild.firstChild;
  64.  
  65.         var timeRemainingCol = elt.nextSibling.nextSibling.nextSibling;
  66.         timeRemainingCol.setAttribute("label", "");
  67.         
  68.         var speedCol = timeRemainingCol.nextSibling.nextSibling;
  69.         speedCol.setAttribute("label", "");
  70.  
  71.         var elapsedCol = speedCol.nextSibling;
  72.         elapsedCol.setAttribute("label", "");
  73.  
  74.         // Fire an onselect event for the downloadView element
  75.         // to update menu status
  76.         var event = this.doc.createEvent('Events');
  77.         event.initEvent('select', false, true);
  78.         this.doc.getElementById("downloadView").dispatchEvent(event);
  79.       }
  80.     },
  81.  
  82.     onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress,
  83.                                aCurTotalProgress, aMaxTotalProgress, aDownload)
  84.     {
  85.       var overallProgress = aCurTotalProgress;
  86.       // Get current time.
  87.       var now = ( new Date() ).getTime();
  88.       // If interval hasn't elapsed, ignore it.
  89.       if ( now - this.lastUpdate < interval && aMaxTotalProgress != "-1" &&  parseInt(aCurTotalProgress) < parseInt(aMaxTotalProgress) ) {
  90.         return;
  91.       }
  92.  
  93.       // Update this time.
  94.       this.lastUpdate = now;
  95.  
  96.       // Update download rate.
  97.       this.elapsed = now - (aDownload.startTime / 1000);
  98.       var rate; // aCurTotalProgress/sec
  99.       if ( this.elapsed )
  100.         rate = ( aCurTotalProgress * 1000 ) / this.elapsed;
  101.       else
  102.         rate = 0;
  103.  
  104.       var aDownloadID = aDownload.target.path
  105.       var elt = this.doc.getElementById(aDownloadID).firstChild.firstChild;
  106.       if (this.doc.getElementById("TimeElapsed").getAttribute("hidden") != "true") {
  107.         elapsedCol = elt.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling;
  108.         // Update elapsed time display.
  109.         elapsedCol.setAttribute("label", formatSeconds( this.elapsed / 1000, this.doc ));
  110.       }
  111.       // Calculate percentage.
  112.       var percent;
  113.       var progressCol = elt.nextSibling;
  114.       if ( aMaxTotalProgress > 0)
  115.       {
  116.         percent = Math.floor((overallProgress*100.0)/aMaxTotalProgress);
  117.         if ( percent > 100 )
  118.           percent = 100;
  119.  
  120.         // Advance progress meter.
  121.         progressCol.setAttribute( "value", percent );
  122.  
  123.         progressCol.setAttribute("mode", "normal");
  124.       }
  125.       else
  126.       {
  127.         percent = -1;
  128.  
  129.         // Progress meter should be barber-pole in this case.
  130.         progressCol.setAttribute( "mode", "undetermined" );
  131.       }
  132.  
  133.       // now that we've set the progress and the time, update # bytes downloaded...
  134.       // Update status (nnK of mmK bytes at xx.xK aCurTotalProgress/sec)
  135.       var status = getString( "progressMsgNoRate", this.doc );
  136.  
  137.       // Insert 1 is the number of kilobytes downloaded so far.
  138.       status = replaceInsert( status, 1, parseInt( overallProgress/1024 + .5 ) );
  139.  
  140.       // Insert 2 is the total number of kilobytes to be downloaded (if known).
  141.       if ( aMaxTotalProgress != "-1" )
  142.          status = replaceInsert( status, 2, parseInt( aMaxTotalProgress/1024 + .5 ) );
  143.       else
  144.          status = replaceInsert( status, 2, "??" );
  145.       
  146.       var rateMsg = getString( "rateMsg", this.doc );
  147.       if ( rate )
  148.       {
  149.         // rate is bytes/sec
  150.         var kRate = (rate / 1024).toFixed(1); // kilobytes/sec
  151.         
  152.         // Don't update too often!
  153.         if ( kRate != this.priorRate )
  154.         {
  155.           if ( this.rateChanges++ == this.rateChangeLimit )
  156.           {
  157.              // Time to update download rate.
  158.              this.priorRate = kRate;
  159.              this.rateChanges = 0;
  160.           }
  161.           else
  162.           {
  163.             // Stick with old rate for a bit longer.
  164.             kRate = this.priorRate;
  165.           }
  166.         }
  167.         else
  168.           this.rateChanges = 0;
  169.  
  170.         // Insert 3 is the download rate (in kilobytes/sec).
  171.         rateMsg = replaceInsert( rateMsg, 1, kRate );
  172.       }
  173.       else
  174.         rateMsg = replaceInsert( rateMsg, 1, "??.?" );
  175.  
  176.       var timeRemainingCol = elt.nextSibling.nextSibling.nextSibling;
  177.  
  178.       // Update status msg.
  179.       var statusCol = timeRemainingCol.nextSibling;
  180.       statusCol.setAttribute("label", status);
  181.  
  182.       var speedCol = statusCol.nextSibling;
  183.       speedCol.setAttribute("label", rateMsg);
  184.       // Update percentage label on progress meter.      
  185.       if (this.doc.getElementById("ProgressPercent").getAttribute("hidden") != "true") {
  186.         var progressText = elt.nextSibling.nextSibling;
  187.         if (percent < 0)
  188.           progressText.setAttribute("label", "");
  189.         else {
  190.           var percentMsg = getString( "percentMsg", this.doc );      
  191.           percentMsg = replaceInsert( percentMsg, 1, percent );
  192.           progressText.setAttribute("label", percentMsg);
  193.         }
  194.       }
  195.       // Update time remaining.
  196.       if ( rate && (aMaxTotalProgress > 0) )
  197.       {
  198.         var rem = ( aMaxTotalProgress - aCurTotalProgress ) / rate;
  199.         rem = parseInt( rem + .5 );
  200.         timeRemainingCol.setAttribute("label", formatSeconds( rem, this.doc ));
  201.       }
  202.       else
  203.         timeRemainingCol.setAttribute("label", getString( "unknownTime", this.doc ));
  204.     },
  205.     onLocationChange: function(aWebProgress, aRequest, aLocation, aDownload)
  206.     {
  207.     },
  208.     onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage, aDownload)
  209.     {
  210.     },
  211.     onSecurityChange: function(aWebProgress, aRequest, state, aDownload)
  212.     {
  213.     },
  214.     QueryInterface : function(iid)
  215.     {
  216.      if (iid.equals(Components.interfaces.nsIDownloadProgressListener) ||
  217.          iid.equals(Components.interfaces.nsISupports))
  218.       return this;
  219.  
  220.      throw Components.results.NS_NOINTERFACE;
  221.     }
  222. };
  223.  
  224. var nsDownloadProgressListenerFactory = {
  225.   createInstance: function (outer, iid) {
  226.     if (outer != null)
  227.         throw Components.results.NS_ERROR_NO_AGGREGATION;
  228.  
  229.     return (new nsDownloadProgressListener()).QueryInterface(iid);
  230.   }
  231. };
  232.  
  233. var nsDownloadProgressListenerModule = {
  234.  
  235.   registerSelf: function (compMgr, fileSpec, location, type)
  236.   { 
  237.     var compReg = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  238.     compReg.registerFactoryLocation(Components.ID("{09cddbea-1dd2-11b2-aa15-c41ffea19d79}"),
  239.                                     "Download Progress Listener",
  240.                                     "@mozilla.org/download-manager/listener;1",
  241.                                     fileSpec, location, type);
  242.   },
  243.   canUnload: function(compMgr)
  244.   {
  245.     return true;
  246.   },
  247.  
  248.   getClassObject: function (compMgr, cid, iid) {
  249.     if (!cid.equals(Components.ID("{09cddbea-1dd2-11b2-aa15-c41ffea19d79}")))
  250.         throw Components.results.NS_ERROR_NO_INTERFACE;
  251.     
  252.     if (!iid.equals(Components.interfaces.nsIFactory))
  253.         throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  254.  
  255.     return nsDownloadProgressListenerFactory;
  256.   }
  257. };
  258.  
  259. function NSGetModule(compMgr, fileSpec) {
  260.     return nsDownloadProgressListenerModule;
  261. }
  262.  
  263. function replaceInsert( text, index, value ) {
  264.    var result = text;
  265.    var regExp = new RegExp( "#"+index );
  266.    result = result.replace( regExp, value );
  267.    return result;
  268. }
  269.  
  270. function getString( stringId, doc ) {
  271.    // Check if we've fetched this string already.
  272.    if ( !gStrings[ stringId ] ) {
  273.       // Try to get it.
  274.       var elem = doc.getElementById( "strings."+stringId );
  275.       try {
  276.         if ( elem
  277.            &&
  278.            elem.childNodes
  279.            &&
  280.            elem.childNodes[0]
  281.            &&
  282.            elem.childNodes[0].nodeValue ) {
  283.          gStrings[ stringId ] = elem.childNodes[0].nodeValue;
  284.         } else {
  285.           // If unable to fetch string, use an empty string.
  286.           gStrings[ stringId ] = "";
  287.         }
  288.       } catch (e) { gStrings[ stringId ] = ""; }
  289.    }
  290.    return gStrings[ stringId ];
  291. }
  292.  
  293. function formatSeconds( secs, doc )
  294. {
  295.   // Round the number of seconds to remove fractions.
  296.   secs = parseInt( secs + .5 );
  297.   var hours = parseInt( secs/3600 );
  298.   secs -= hours*3600;
  299.   var mins = parseInt( secs/60 );
  300.   secs -= mins*60;
  301.   var result;
  302.   if ( hours )
  303.     result = getString( "longTimeFormat", doc );
  304.   else
  305.     result = getString( "shortTimeFormat", doc );
  306.  
  307.   if ( hours < 10 )
  308.      hours = "0" + hours;
  309.   if ( mins < 10 )
  310.      mins = "0" + mins;
  311.   if ( secs < 10 )
  312.      secs = "0" + secs;
  313.  
  314.   // Insert hours, minutes, and seconds into result string.
  315.   result = replaceInsert( result, 1, hours );
  316.   result = replaceInsert( result, 2, mins );
  317.   result = replaceInsert( result, 3, secs );
  318.  
  319.   return result;
  320. }
  321.  
  322.  
  323.