home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 35 Internet / 35-Internet.zip / phoenx05.zip / phoenix / components / nsDownloadProgressListener.js < prev    next >
Text File  |  2002-12-10  |  11KB  |  320 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: 0,
  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.persistentDescriptor;
  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.     },
  75.  
  76.     onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress,
  77.                                aCurTotalProgress, aMaxTotalProgress, aDownload)
  78.     {
  79.       var overallProgress = aCurTotalProgress;
  80.       // Get current time.
  81.       var now = ( new Date() ).getTime();
  82.       // If interval hasn't elapsed, ignore it.
  83.       if ( now - this.lastUpdate < interval && aMaxTotalProgress != "-1" &&  parseInt(aCurTotalProgress) < parseInt(aMaxTotalProgress) ) {
  84.         return;
  85.       }
  86.  
  87.       // Update this time.
  88.       this.lastUpdate = now;
  89.  
  90.       // Update download rate.
  91.       this.elapsed = now - (aDownload.startTime / 1000);
  92.       var rate; // aCurTotalProgress/sec
  93.       if ( this.elapsed )
  94.         rate = ( aCurTotalProgress * 1000 ) / this.elapsed;
  95.       else
  96.         rate = 0;
  97.  
  98.       var aDownloadID = aDownload.target.persistentDescriptor;
  99.       var elt = this.doc.getElementById(aDownloadID).firstChild.firstChild;
  100.       if (this.doc.getElementById("TimeElapsed").getAttribute("hidden") != "true") {
  101.         elapsedCol = elt.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling;
  102.         // Update elapsed time display.
  103.         elapsedCol.setAttribute("label", formatSeconds( this.elapsed / 1000, this.doc ));
  104.       }
  105.       // Calculate percentage.
  106.       var percent;
  107.       var progressCol = elt.nextSibling;
  108.       if ( aMaxTotalProgress > 0)
  109.       {
  110.         percent = Math.floor((overallProgress*100.0)/aMaxTotalProgress);
  111.         if ( percent > 100 )
  112.           percent = 100;
  113.  
  114.         // Advance progress meter.
  115.         progressCol.setAttribute( "value", percent );
  116.  
  117.         progressCol.setAttribute("mode", "normal");
  118.       }
  119.       else
  120.       {
  121.         percent = -1;
  122.  
  123.         // Progress meter should be barber-pole in this case.
  124.         progressCol.setAttribute( "mode", "undetermined" );
  125.       }
  126.  
  127.       // now that we've set the progress and the time, update # bytes downloaded...
  128.       // Update status (nnK of mmK bytes at xx.xK aCurTotalProgress/sec)
  129.       var status = getString( "progressMsgNoRate", this.doc );
  130.  
  131.       // Insert 1 is the number of kilobytes downloaded so far.
  132.       status = replaceInsert( status, 1, parseInt( overallProgress/1024 + .5 ) );
  133.  
  134.       // Insert 2 is the total number of kilobytes to be downloaded (if known).
  135.       if ( aMaxTotalProgress != "-1" )
  136.          status = replaceInsert( status, 2, parseInt( aMaxTotalProgress/1024 + .5 ) );
  137.       else
  138.          status = replaceInsert( status, 2, "??" );
  139.       
  140.       var rateMsg = getString( "rateMsg", this.doc );
  141.       if ( rate )
  142.       {
  143.         // rate is bytes/sec
  144.         var kRate = rate / 1024; // K bytes/sec;
  145.         kRate = parseInt( kRate * 10 + .5 ); // xxx (3 digits)
  146.         // Don't update too often!
  147.         if ( kRate != this.priorRate )
  148.         {
  149.           if ( this.rateChanges++ == this.rateChangeLimit )
  150.           {
  151.              // Time to update download rate.
  152.              this.priorRate = kRate;
  153.              this.rateChanges = 0;
  154.           }
  155.           else
  156.           {
  157.             // Stick with old rate for a bit longer.
  158.             kRate = this.priorRate;
  159.           }
  160.         }
  161.         else
  162.           this.rateChanges = 0;
  163.  
  164.          var fraction = kRate % 10;
  165.          kRate = parseInt( ( kRate - fraction ) / 10 );
  166.  
  167.          // Insert 3 is the download rate (in kilobytes/sec).
  168.          rateMsg = replaceInsert( rateMsg, 1, kRate + "." + fraction );
  169.       }
  170.       else
  171.        rateMsg = replaceInsert( rateMsg, 1, "??.?" );
  172.  
  173.       var timeRemainingCol = elt.nextSibling.nextSibling.nextSibling;
  174.  
  175.       // Update status msg.
  176.       var statusCol = timeRemainingCol.nextSibling;
  177.       statusCol.setAttribute("label", status);
  178.  
  179.       var speedCol = statusCol.nextSibling;
  180.       speedCol.setAttribute("label", rateMsg);
  181.       // Update percentage label on progress meter.      
  182.       if (this.doc.getElementById("ProgressPercent").getAttribute("hidden") != "true") {
  183.         var progressText = elt.nextSibling.nextSibling;
  184.         if (percent < 0)
  185.           progressText.setAttribute("label", "");
  186.         else {
  187.           var percentMsg = getString( "percentMsg", this.doc );      
  188.           percentMsg = replaceInsert( percentMsg, 1, percent );
  189.           progressText.setAttribute("label", percentMsg);
  190.         }
  191.       }
  192.       // Update time remaining.
  193.       if ( rate && (aMaxTotalProgress > 0) )
  194.       {
  195.         var rem = ( aMaxTotalProgress - aCurTotalProgress ) / rate;
  196.         rem = parseInt( rem + .5 );
  197.         timeRemainingCol.setAttribute("label", formatSeconds( rem, this.doc ));
  198.       }
  199.       else
  200.         timeRemainingCol.setAttribute("label", getString( "unknownTime", this.doc ));
  201.     },
  202.     onLocationChange: function(aWebProgress, aRequest, aLocation, aDownload)
  203.     {
  204.     },
  205.     onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage, aDownload)
  206.     {
  207.     },
  208.     onSecurityChange: function(aWebProgress, aRequest, state, aDownload)
  209.     {
  210.     },
  211.     QueryInterface : function(iid)
  212.     {
  213.      if (iid.equals(Components.interfaces.nsIDownloadProgressListener) ||
  214.          iid.equals(Components.interfaces.nsISupports))
  215.       return this;
  216.  
  217.      throw Components.results.NS_NOINTERFACE;
  218.     }
  219. };
  220.  
  221. var nsDownloadProgressListenerFactory = {
  222.   createInstance: function (outer, iid) {
  223.     if (outer != null)
  224.         throw Components.results.NS_ERROR_NO_AGGREGATION;
  225.  
  226.     return (new nsDownloadProgressListener()).QueryInterface(iid);
  227.   }
  228. };
  229.  
  230. var nsDownloadProgressListenerModule = {
  231.  
  232.   registerSelf: function (compMgr, fileSpec, location, type)
  233.   { 
  234.     compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentManagerObsolete);
  235.     compMgr.registerComponentWithType(Components.ID("{09cddbea-1dd2-11b2-aa15-c41ffea19d79}"),
  236.                                       "Download Progress Listener",
  237.                                       "@mozilla.org/download-manager/listener;1", fileSpec,
  238.                                       location, true, true, type);
  239.   },
  240.   canUnload: function(compMgr)
  241.   {
  242.     return true;
  243.   },
  244.  
  245.   getClassObject: function (compMgr, cid, iid) {
  246.     if (!cid.equals(Components.ID("{09cddbea-1dd2-11b2-aa15-c41ffea19d79}")))
  247.         throw Components.results.NS_ERROR_NO_INTERFACE;
  248.     
  249.     if (!iid.equals(Components.interfaces.nsIFactory))
  250.         throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  251.  
  252.     return nsDownloadProgressListenerFactory;
  253.   }
  254. };
  255.  
  256. function NSGetModule(compMgr, fileSpec) {
  257.     return nsDownloadProgressListenerModule;
  258. }
  259.  
  260. function replaceInsert( text, index, value ) {
  261.    var result = text;
  262.    var regExp = new RegExp( "#"+index );
  263.    result = result.replace( regExp, value );
  264.    return result;
  265. }
  266.  
  267. function getString( stringId, doc ) {
  268.    // Check if we've fetched this string already.
  269.    if ( !gStrings[ stringId ] ) {
  270.       // Try to get it.
  271.       var elem = doc.getElementById( "strings."+stringId );
  272.       try {
  273.         if ( elem
  274.            &&
  275.            elem.childNodes
  276.            &&
  277.            elem.childNodes[0]
  278.            &&
  279.            elem.childNodes[0].nodeValue ) {
  280.          gStrings[ stringId ] = elem.childNodes[0].nodeValue;
  281.         } else {
  282.           // If unable to fetch string, use an empty string.
  283.           gStrings[ stringId ] = "";
  284.         }
  285.       } catch (e) { gStrings[ stringId ] = ""; }
  286.    }
  287.    return gStrings[ stringId ];
  288. }
  289.  
  290. function formatSeconds( secs, doc )
  291. {
  292.   // Round the number of seconds to remove fractions.
  293.   secs = parseInt( secs + .5 );
  294.   var hours = parseInt( secs/3600 );
  295.   secs -= hours*3600;
  296.   var mins = parseInt( secs/60 );
  297.   secs -= mins*60;
  298.   var result;
  299.   if ( hours )
  300.     result = getString( "longTimeFormat", doc );
  301.   else
  302.     result = getString( "shortTimeFormat", doc );
  303.  
  304.   if ( hours < 10 )
  305.      hours = "0" + hours;
  306.   if ( mins < 10 )
  307.      mins = "0" + mins;
  308.   if ( secs < 10 )
  309.      secs = "0" + secs;
  310.  
  311.   // Insert hours, minutes, and seconds into result string.
  312.   result = replaceInsert( result, 1, hours );
  313.   result = replaceInsert( result, 2, mins );
  314.   result = replaceInsert( result, 3, secs );
  315.  
  316.   return result;
  317. }
  318.  
  319.  
  320.