home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 35 Internet / 35-Internet.zip / mozil06.zip / bin / chrome / toolkit.jar / content / global / helperAppDldProgress.js < prev    next >
Text File  |  2001-02-14  |  11KB  |  345 lines

  1. /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /*
  3.  * The contents of this file are subject to the Netscape Public License
  4.  * Version 1.0 (the "License"); you may not use this file except in
  5.  * compliance with the License.  You may obtain a copy of the License at
  6.  * http://www.mozilla.org/NPL/
  7.  *
  8.  * Software distributed under the License is distributed on an "AS IS" basis,
  9.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  10.  * for the specific language governing rights and limitations under the
  11.  * License.
  12.  *
  13.  * The Original Code is Mozilla Communicator client code, 
  14.  * released March 31, 1998. 
  15.  *
  16.  * The Initial Developer of the Original Code is Netscape Communications 
  17.  * Corporation.  Portions created by Netscape are 
  18.  * Copyright (C) 1998 Netscape Communications Corporation.  All Rights
  19.  * Reserved.
  20.  *
  21.  * Contributors:
  22.  *     William A. ("PowerGUI") Law <law@netscape.com>
  23.  *     Scott MacGregor <mscott@netscape.com>
  24.  */
  25.  
  26. // dialog is just an array we'll use to store various properties from the dialog document...
  27. var dialog;
  28.  
  29. // the helperAppLoader is a nsIHelperAppLauncher object
  30. var helperAppLoader; 
  31.  
  32. // random global variables...
  33. var started   = false;
  34. var completed = false;
  35. var startTime;
  36. // since this progress dialog is brought up after we've already started downloading, we need to record the # bytes already 
  37. // downloaded before we started showing progress. This is used to make sure our time remaining calculation works correctly...
  38. var initialByteOffset;
  39. var elapsed = 0;
  40. var interval = 1000; // Update every 1000 milliseconds.
  41. var lastUpdate = -interval; // Update initially.
  42.  
  43. // These are to throttle down the updating of the download rate figure.
  44. var priorRate = 0;
  45. var rateChanges = 0;
  46. var rateChangeLimit = 2;
  47.  
  48. var warningLimit = 30000; // Warn on Cancel after 30 sec (30000 milleseconds).
  49.  
  50. // all progress notifications are done through our nsIWebProgressListener implementation...
  51. var progressListener = {
  52.     onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus)
  53.     {
  54.       if (aStateFlags & Components.interfaces.nsIWebProgressListener.STATE_STOP)
  55.       {
  56.         // we are done downloading...
  57.         completed = true;
  58.         // Indicate completion in status area.
  59.         var msg = getString( "completeMsg" );
  60.         msg = replaceInsert( msg, 1, formatSeconds( elapsed/1000 ) );
  61.         dialog.status.setAttribute("value", msg);
  62.  
  63.         // Put progress meter at 100%.
  64.         dialog.progress.setAttribute( "value", 100 );
  65.         dialog.progress.setAttribute( "mode", "normal" );
  66.         try {
  67.           // Close the window in 2 seconds (to ensure user sees we're done).
  68.           window.setTimeout( "window.close();", 2000 );
  69.         } 
  70.         catch ( exception ) 
  71.         {
  72.           dump( "Error setting close timeout\n" );
  73.           // OK, try to just close the window immediately.
  74.           window.close();
  75.           // If that's not working either, change button text to give user a clue.
  76.           dialog.cancel.childNodes[0].nodeValue = "Close";
  77.         }
  78.       }
  79.     },
  80.     
  81.     onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress)
  82.     {
  83.       // Check for first time.
  84.       if ( !started ) 
  85.       {
  86.         // Initialize download start time.
  87.         started = true;
  88.         startTime = ( new Date() ).getTime();
  89.         initialByteOffset = aCurTotalProgress;
  90.       }
  91.  
  92.       var overallProgress = aCurTotalProgress;
  93.  
  94.       aCurTotalProgress -= initialByteOffset;
  95.  
  96.       // Get current time.
  97.       var now = ( new Date() ).getTime();
  98.       // If interval hasn't elapsed, ignore it.
  99.       if ( now - lastUpdate < interval && aMaxTotalProgress != "-1" &&  eval(aCurTotalProgress) < eval(aMaxTotalProgress) ) 
  100.         return;
  101.  
  102.       // Update this time.
  103.       lastUpdate = now;
  104.  
  105.       // Update download rate.
  106.       elapsed = now - startTime;
  107.       var rate; // aCurTotalProgress/sec
  108.       if ( elapsed )
  109.         rate = ( aCurTotalProgress * 1000 ) / elapsed;
  110.       else 
  111.         rate = 0;
  112.  
  113.       // Update elapsed time display.
  114.       dialog.timeElapsed.setAttribute("value", formatSeconds( elapsed / 1000 ));
  115.  
  116.       // Calculate percentage.
  117.       var percent;
  118.       if ( aMaxTotalProgress != "-1" ) 
  119.       {
  120.         percent = parseInt( (overallProgress*100)/aMaxTotalProgress + .5 );
  121.         if ( percent > 100 )
  122.           percent = 100;
  123.         
  124.         // Advance progress meter.
  125.         dialog.progress.setAttribute( "value", percent );
  126.       } 
  127.       else 
  128.       {
  129.         percent = "??";
  130.  
  131.         // Progress meter should be barber-pole in this case.
  132.         dialog.progress.setAttribute( "mode", "undetermined" );
  133.       }
  134.  
  135.       // now that we've set the progress and the time, update # bytes downloaded...
  136.       // Update status (nnK of mmK bytes at xx.xK aCurTotalProgress/sec)
  137.       var status = getString( "progressMsg" );
  138.  
  139.       // Insert 1 is the number of kilobytes downloaded so far.
  140.       status = replaceInsert( status, 1, parseInt( overallProgress/1024 + .5 ) );
  141.  
  142.       // Insert 2 is the total number of kilobytes to be downloaded (if known).
  143.       if ( aMaxTotalProgress != "-1" )
  144.          status = replaceInsert( status, 2, parseInt( aMaxTotalProgress/1024 + .5 ) );
  145.       else 
  146.          status = replaceInsert( status, 2, "??" );
  147.  
  148.       if ( rate ) 
  149.       {
  150.         // rate is bytes/sec
  151.         var kRate = rate / 1024; // K bytes/sec;
  152.         kRate = parseInt( kRate * 10 + .5 ); // xxx (3 digits)
  153.         // Don't update too often!
  154.         if ( kRate != priorRate ) 
  155.         {
  156.           if ( rateChanges++ == rateChangeLimit ) 
  157.           {
  158.              // Time to update download rate.
  159.              priorRate = kRate;
  160.              rateChanges = 0;
  161.           } 
  162.           else 
  163.           {
  164.             // Stick with old rate for a bit longer.
  165.             kRate = priorRate;
  166.           }
  167.         }
  168.         else
  169.           rateChanges = 0;
  170.  
  171.          var fraction = kRate % 10;
  172.          kRate = parseInt( ( kRate - fraction ) / 10 );
  173.  
  174.          // Insert 3 is the download rate (in kilobytes/sec).
  175.          status = replaceInsert( status, 3, kRate + "." + fraction );
  176.       } 
  177.       else
  178.        status = replaceInsert( status, 3, "??.?" );
  179.  
  180.       // Update status msg.
  181.       dialog.status.setAttribute("value", status);
  182.  
  183.       // Update percentage label on progress meter.
  184.       var percentMsg = getString( "percentMsg" );
  185.       percentMsg = replaceInsert( percentMsg, 1, percent );
  186.       dialog.progress.progresstext = percentMsg;
  187.  
  188.       // Update time remaining.
  189.       if ( rate && aMaxTotalProgress != "-1" ) 
  190.       {
  191.         var rem = ( aMaxTotalProgress - aCurTotalProgress ) / rate;
  192.             rem = parseInt( rem + .5 );
  193.             dialog.timeLeft.setAttribute("value", formatSeconds( rem ));
  194.       }
  195.       else
  196.             dialog.timeLeft.setAttribute("value", getString( "unknownTime" ));
  197.     },
  198.       onLocationChange: function(aWebProgress, aRequest, aLocation)
  199.     {
  200.       // we can ignore this notification
  201.     },
  202.     onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage)
  203.     {
  204.       if (aMessage)
  205.         dialog.status.setAttribute("value", status);
  206.     },
  207.     onSecurityChange: function(aWebProgress, aRequest, state)
  208.     {
  209.     }
  210. };
  211.  
  212. function getString( stringId ) {
  213.    // Check if we've fetched this string already.
  214.    if ( !dialog.strings[ stringId ] ) {
  215.       // Try to get it.
  216.       var elem = document.getElementById( "dialog.strings."+stringId );
  217.       try {
  218.         if ( elem
  219.            &&
  220.            elem.childNodes
  221.            &&
  222.            elem.childNodes[0]
  223.            &&
  224.            elem.childNodes[0].nodeValue ) {
  225.          dialog.strings[ stringId ] = elem.childNodes[0].nodeValue;
  226.         } else {
  227.           // If unable to fetch string, use an empty string.
  228.           dialog.strings[ stringId ] = "";
  229.         }
  230.       } catch (e) { dialog.strings[ stringId ] = ""; }
  231.    }
  232.    return dialog.strings[ stringId ];
  233. }
  234.  
  235. function formatSeconds( secs ) 
  236. {
  237.   // Round the number of seconds to remove fractions.
  238.   secs = parseInt( secs + .5 );
  239.   var hours = parseInt( secs/3600 );
  240.   secs -= hours*3600;
  241.   var mins = parseInt( secs/60 );
  242.   secs -= mins*60;
  243.   var result;
  244.   if ( hours ) 
  245.     result = getString( "longTimeFormat" );
  246.   else 
  247.     result = getString( "shortTimeFormat" );
  248.   
  249.   if ( hours < 10 ) 
  250.      hours = "0" + hours;
  251.   if ( mins < 10 )
  252.      mins = "0" + mins;
  253.   if ( secs < 10 )
  254.      secs = "0" + secs;
  255.  
  256.   // Insert hours, minutes, and seconds into result string.
  257.   result = replaceInsert( result, 1, hours );
  258.   result = replaceInsert( result, 2, mins );
  259.   result = replaceInsert( result, 3, secs );
  260.  
  261.   return result;
  262. }
  263.  
  264. function loadDialog() {
  265.   var sourceUrlValue = {};
  266.   var targetFile =  helperAppLoader.getDownloadInfo(sourceUrlValue);
  267.   var sourceUrl = sourceUrlValue.value;
  268.  
  269.   dialog.location.setAttribute("value", sourceUrlValue.value.spec );
  270.   dialog.fileName.setAttribute( "value", targetFile.unicodePath );
  271. }
  272.  
  273. function replaceInsert( text, index, value ) {
  274.    var result = text;
  275.    var regExp = eval( "/#"+index+"/" );
  276.    result = result.replace( regExp, value );
  277.    return result;
  278. }
  279.  
  280. function onLoad() {
  281.     // Set global variables.
  282.     helperAppLoader = window.arguments[0];
  283.  
  284.     if ( !helperAppLoader ) {
  285.         dump( "Invalid argument to downloadProgress.xul\n" );
  286.         window.close()
  287.         return;
  288.     }
  289.  
  290.     dialog = new Object;
  291.     dialog.strings = new Array;
  292.     dialog.location    = document.getElementById("dialog.location");
  293.     dialog.contentType = document.getElementById("dialog.contentType");
  294.     dialog.fileName    = document.getElementById("dialog.fileName");
  295.     dialog.status      = document.getElementById("dialog.status");
  296.     dialog.progress    = document.getElementById("dialog.progress");
  297.     dialog.timeLeft    = document.getElementById("dialog.timeLeft");
  298.     dialog.timeElapsed = document.getElementById("dialog.timeElapsed");
  299.     dialog.cancel      = document.getElementById("dialog.cancel");
  300.  
  301.     // Set up dialog button callbacks.
  302.     var object = this;
  303.     doSetOKCancel("", function () { return object.onCancel();});
  304.  
  305.     // Fill dialog.
  306.     loadDialog();
  307.  
  308.     // set our web progress listener on the helper app launcher
  309.     helperAppLoader.setWebProgressListener(progressListener);
  310.     moveToAlertPosition();
  311. }
  312.  
  313. function onUnload() 
  314. {
  315.    // Cancel app launcher.
  316.    if (helperAppLoader)
  317.    {
  318.      try 
  319.      {
  320.        helperAppLoader.closeProgressWindow();
  321.        helperAppLoader = null;
  322.      }
  323.       
  324.      catch( exception ) {}
  325.    }
  326. }
  327.  
  328. // If the user presses cancel, tell the app launcher and close the dialog...
  329. function onCancel () 
  330. {
  331.    // Cancel app launcher.
  332.    if (helperAppLoader)
  333.    {
  334.      try 
  335.      {
  336.        helperAppLoader.Cancel();
  337.      }
  338.       
  339.      catch( exception ) {}
  340.    }
  341.     
  342.   // Close up dialog by returning true.
  343.   return true;
  344. }
  345.