Fork download manager for phoenix.

This commit is contained in:
bryner@netscape.com
2002-09-28 01:31:19 +00:00
parent 53e5c51e5f
commit 5d824fba32
20 changed files with 3042 additions and 18 deletions

View File

@@ -42,6 +42,6 @@ VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
DIRS = prefwindow history bookmarks console
DIRS = prefwindow history bookmarks console downloads build
include $(topsrcdir)/config/rules.mk

View File

@@ -11,14 +11,22 @@ EXPORT_LIBRARY = 1
FORCE_SHARED_LIB = 1
IS_COMPONENT = 1
REQUIRES = xpcom \
string \
toolkitcomps \
mork \
pref \
rdf \
intl \
$(NULL)
REQUIRES = \
xpcom \
string \
toolkitcomps \
mork \
pref \
rdf \
intl \
downloads \
uriloader \
dom \
necko \
webbrowserpersist \
progressDlg \
mimetype \
$(NULL)
EXPORTS = nsBrowserCompsCID.h
@@ -26,17 +34,20 @@ CPPSRCS = nsModule.cpp \
$(NULL)
LOCAL_INCLUDES = \
-I$(srcdir)/../history/src \
-I$(srcdir)/../history/src \
-I$(srcdir)/../downloads/src \
$(NULL)
SHARED_LIBRARY_LIBS = \
$(DIST)/lib/$(LIB_PREFIX)history_s.$(LIB_SUFFIX) \
$(NULL)
$(DIST)/lib/$(LIB_PREFIX)history_s.$(LIB_SUFFIX) \
$(DIST)/lib/$(LIB_PREFIX)download_s.$(LIB_SUFFIX) \
$(NULL)
EXTRA_DSO_LDOPTS += \
$(EXTRA_DSO_LIBS) \
$(MOZ_UNICHARUTIL_LIBS) \
$(MOZ_COMPONENT_LIBS) \
$(MOZ_JS_LIBS) \
$(NULL)
$(EXTRA_DSO_LIBS) \
$(MOZ_UNICHARUTIL_LIBS) \
$(MOZ_COMPONENT_LIBS) \
$(MOZ_JS_LIBS) \
$(NULL)
include $(topsrcdir)/config/rules.mk

View File

@@ -40,10 +40,14 @@
#include "nsBrowserCompsCID.h"
#include "nsGlobalHistory.h"
#include "nsDownloadManager.h"
#include "nsDownloadProxy.h"
/////////////////////////////////////////////////////////////////////////////
NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsGlobalHistory, Init)
NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsDownloadManager, Init)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsDownloadProxy)
/////////////////////////////////////////////////////////////////////////////
@@ -62,7 +66,15 @@ static const nsModuleComponentInfo components[] =
{ "Global History",
NS_GLOBALHISTORY_CID,
NS_GLOBALHISTORY_AUTOCOMPLETE_CONTRACTID,
nsGlobalHistoryConstructor }
nsGlobalHistoryConstructor },
{ "Download Manager",
NS_DOWNLOADMANAGER_CID, NS_DOWNLOADMANAGER_CONTRACTID,
nsDownloadManagerConstructor },
{ "Download",
NS_DOWNLOAD_CID, NS_DOWNLOAD_CONTRACTID,
nsDownloadProxyConstructor }
};
NS_IMPL_NSGETMODULE(nsBrowserCompsModule, components);

View File

@@ -0,0 +1 @@
Makefile

View File

@@ -0,0 +1,32 @@
#
# 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.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
DIRS = public src
include $(topsrcdir)/config/rules.mk

View File

@@ -0,0 +1,332 @@
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* 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.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Ben Goodger <ben@netscape.com> (Original Author)
* Blake Ross <blakeross@telocity.com>
* Jan Varga <varga@utcru.sk>
*
* 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 NPL, 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 NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
const NC_NS = "http://home.netscape.com/NC-rdf#";
var gDownloadView = null;
var gDownloadManager = null;
var gRDFService = null;
var gNC_File = null;
var gStatusBar = null;
const dlObserver = {
observe: function(subject, topic, state) {
if (topic != "download-starting") return;
selectDownload(subject.QueryInterface(Components.interfaces.nsIDownload));
}
};
function selectDownload(aDownload)
{
var dlElt = document.getElementById(aDownload.target.path);
var dlIndex = gDownloadView.contentView.getIndexOfItem(dlElt);
gDownloadView.treeBoxObject.selection.select(dlIndex);
gDownloadView.treeBoxObject.ensureRowIsVisible(dlIndex);
}
function Startup()
{
if (!window.arguments.length)
return;
try {
var observerService = Components.classes[kObserverServiceProgID]
.getService(Components.interfaces.nsIObserverService);
observerService.addObserver(dlObserver, "download-starting", false);
}
catch (ex) {
}
const rdfSvcContractID = "@mozilla.org/rdf/rdf-service;1";
const rdfSvcIID = Components.interfaces.nsIRDFService;
gRDFService = Components.classes[rdfSvcContractID].getService(rdfSvcIID);
gNC_File = gRDFService.GetResource(NC_NS + "File");
gDownloadView = document.getElementById("downloadView");
const dlmgrContractID = "@mozilla.org/download-manager;1";
const dlmgrIID = Components.interfaces.nsIDownloadManager;
gDownloadManager = Components.classes[dlmgrContractID].getService(dlmgrIID);
var ds = window.arguments[0];
gDownloadView.database.AddDataSource(ds);
gDownloadView.builder.rebuild();
window.setTimeout(onRebuild, 0);
var key;
if (navigator.platform.indexOf("Win") != -1)
key = "Win";
else if (navigator.platform.indexOf("Mac") != -1)
key = "Mac";
else {
key = "Unix";
document.getElementById("btn_openfile").hidden = true;
}
var bundle = document.getElementById("dlMgrBundle")
var label = bundle.getString("showInShellLabel" + key);
var accesskey = bundle.getString("showInShellAccesskey" + key);
var showBtn = document.getElementById("btn_showinshell");
showBtn.setAttribute("label", label);
showBtn.setAttribute("accesskey", accesskey);
}
function onRebuild() {
gDownloadView.controllers.appendController(downloadViewController);
gDownloadView.focus();
// If the window was opened automatically because
// a download started, select the new download
if (window.arguments.length > 1 && window.arguments[1]) {
var dl = window.arguments[1];
selectDownload(dl.QueryInterface(Components.interfaces.nsIDownload));
}
else if (gDownloadView.view.rowCount) {
// Select the first item in the view, if any.
gDownloadView.treeBoxObject.selection.select(0);
}
}
function onSelect(aEvent) {
if (!gStatusBar)
gStatusBar = document.getElementById("statusbar-text");
var selectionCount = gDownloadView.treeBoxObject.selection.count;
if (selectionCount == 1)
gStatusBar.label = getSelectedItem().id;
else
gStatusBar.label = "";
window.updateCommands("tree-select");
}
var downloadViewController = {
supportsCommand: function dVC_supportsCommand (aCommand)
{
switch (aCommand) {
case "cmd_properties":
case "cmd_pause":
case "cmd_cancel":
case "cmd_remove":
case "cmd_openfile":
case "cmd_showinshell":
case "cmd_selectAll":
return true;
}
return false;
},
isCommandEnabled: function dVC_isCommandEnabled (aCommand)
{
var selectionCount = gDownloadView.treeBoxObject.selection.count;
if (!selectionCount) return false;
var selectedItem = getSelectedItem();
var isDownloading = gDownloadManager.getDownload(selectedItem.id);
switch (aCommand) {
case "cmd_openfile":
try {
if (isDownloading || getFileForItem(selectedItem).isExecutable())
return false;
} catch(e) {
// Exception means file doesn't exist; launch is not allowed.
return false;
}
case "cmd_showinshell":
// some apps like kazaa/morpheus let you "preview" in-progress downloads because
// that's possible for movies and music. for now, just disable indiscriminately.
return selectionCount == 1;
case "cmd_properties":
return selectionCount == 1 && isDownloading;
case "cmd_pause":
return false;
case "cmd_cancel":
// XXX check if selection is still in progress
// how to handle multiple selection?
return isDownloading;
case "cmd_remove":
// XXX ensure selection isn't still in progress
// and how to handle multiple selection?
return !isDownloading;
case "cmd_selectAll":
return gDownloadView.view.rowCount != selectionCount;
default:
return false;
}
},
doCommand: function dVC_doCommand (aCommand)
{
var selectedItem, selectedItems;
var file, i;
switch (aCommand) {
case "cmd_properties":
selectedItem = getSelectedItem();
gDownloadManager.openProgressDialogFor(selectedItem.id, window);
break;
case "cmd_openfile":
selectedItem = getSelectedItem();
file = getFileForItem(selectedItem);
file.launch();
break;
case "cmd_showinshell":
selectedItem = getSelectedItem();
file = getFileForItem(selectedItem);
// on unix, open a browser window rooted at the parent
if (navigator.platform.indexOf("Win") == -1 && navigator.platform.indexOf("Mac") == -1) {
file = file.QueryInterface(Components.interfaces.nsIFile);
var parent = file.parent;
if (parent) {
const browserURL = "chrome://navigator/content/navigator.xul";
window.openDialog(browserURL, "_blank", "chrome,all,dialog=no", parent.path);
}
}
else {
file.reveal();
}
break;
case "cmd_pause":
break;
case "cmd_cancel":
// XXX we should probably prompt the user
selectedItems = getSelectedItems();
for (i = 0; i < selectedItems.length; i++)
gDownloadManager.cancelDownload(selectedItems[i].id);
window.updateCommands("tree-select");
break;
case "cmd_remove":
selectedItems = getSelectedItems();
gDownloadManager.startBatchUpdate();
// Notify the datasource that we're about to begin a batch operation
var observer = gDownloadView.builder.QueryInterface(Components.interfaces.nsIRDFObserver);
var ds = gDownloadView.database;
observer.beginUpdateBatch(ds);
for (i = 0; i <= selectedItems.length - 1; ++i) {
gDownloadManager.removeDownload(selectedItems[i].id);
}
gDownloadManager.endBatchUpdate();
observer.endUpdateBatch(ds);
var remote = window.arguments[0].QueryInterface(Components.interfaces.nsIRDFRemoteDataSource);
remote.Flush();
gDownloadView.builder.rebuild();
if (minValue >= gDownloadView.treeBoxObject.view.rowCount)
--minValue;
gDownloadView.treeBoxObject.selection.select(minValue);
break;
case "cmd_selectAll":
gDownloadView.treeBoxObject.selection.selectAll();
break;
default:
}
},
onEvent: function dVC_onEvent (aEvent)
{
switch (aEvent) {
case "tree-select":
this.onCommandUpdate();
}
},
onCommandUpdate: function dVC_onCommandUpdate ()
{
var cmds = ["cmd_properties", "cmd_pause", "cmd_cancel", "cmd_remove",
"cmd_openfile", "cmd_showinshell"];
for (var command in cmds)
goUpdateCommand(cmds[command]);
}
};
function getSelectedItem()
{
return gDownloadView.contentView.getItemAtIndex(gDownloadView.currentIndex);
}
function getSelectedItems()
{
var items = [];
var k = 0;
var selection = gDownloadView.treeBoxObject.selection;
var rangeCount = selection.getRangeCount();
for (var i = 0; i < rangeCount; i++) {
var startIndex = {};
var endIndex = {};
selection.getRangeAt(i, startIndex, endIndex);
for (var j = startIndex.value; j <= endIndex.value; j++)
items[k++] = gDownloadView.contentView.getItemAtIndex(j);
}
return items;
}
function getFileForItem(aElement)
{
var itemResource = gRDFService.GetResource(aElement.id);
var fileResource = gDownloadView.database.GetTarget(itemResource, gNC_File, true);
fileResource = fileResource.QueryInterface(Components.interfaces.nsIRDFResource);
return createLocalFile(fileResource.Value);
}
function createLocalFile(aFilePath)
{
var lfContractID = "@mozilla.org/file/local;1";
var lfIID = Components.interfaces.nsILocalFile;
var lf = Components.classes[lfContractID].createInstance(lfIID);
lf.initWithPath(aFilePath);
return lf;
}
function Shutdown()
{
try {
var observerService = Components.classes[kObserverServiceProgID]
.getService(Components.interfaces.nsIObserverService);
observerService.removeObserver(dlObserver, "download-starting");
}
catch (ex) {
}
}

View File

@@ -0,0 +1,212 @@
<?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.org code.
The Initial Developer of the Original Code is Netscape
Communications Corporation. Portions created by Netscape are
Copyright (C) 1998 Netscape Communications Corporation. All
Rights Reserved.
Contributor(s):
Ben Goodger <ben@netscape.com> (Original Author)
Blake Ross <blaker@netscape.com>
Jan Varga <varga@utcru.sk>
-->
<?xml-stylesheet href="chrome://communicator/skin/"?>
<?xul-overlay href="chrome://communicator/content/tasksOverlay.xul"?>
<?xul-overlay href="chrome://communicator/content/utilityOverlay.xul"?>
<!DOCTYPE window [
<!ENTITY % downloadManagerDTD SYSTEM "chrome://communicator/locale/downloadmanager/downloadmanager.dtd">
%downloadManagerDTD;
<!ENTITY % downloadProgressDTD SYSTEM "chrome://global/locale/nsProgressDialog.dtd" >
%downloadProgressDTD;
]>
<window id="downloadManager"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
windowtype="Download:Manager"
width="500" height="300" screenX="10" screenY="10"
persist="width height screenX screenY"
title="&downloadManager.title;"
onload="Startup();"
onunload="Shutdown();">
<script type="application/x-javascript" src="chrome://global/content/globalOverlay.js"/>
<script type="application/x-javascript" src="chrome://communicator/content/downloadmanager/downloadmanager.js"/>
<stringbundle id="dlMgrBundle"
src="chrome://communicator/locale/downloadmanager/downloadmanager.properties"/>
<stringbundle id="dlProgressDlgBundle"
src="chrome://global/locale/nsProgressDialog.properties"/>
<data id="strings.confirmCancel">&confirmCancel;</data>
<data id="strings.progressMsgNoRate">&progressMsgNoRate;</data>
<data id="strings.rateMsg">&rateMsg;</data>
<data id="strings.completeMsg">&completeMsg;</data>
<data id="strings.percentMsg">&percentMsg;</data>
<data id="strings.shortTimeFormat">&shortTimeFormat;</data>
<data id="strings.longTimeFormat">&longTimeFormat;</data>
<data id="strings.unknownTime">&unknownTime;</data>
<data id="strings.pausedMsg">&pausedMsg;</data>
<commandset id="commands">
<commandset id="commandUpdate_Downloads"
commandupdater="true"
events="focus,tree-select"
oncommandupdate="downloadViewController.onCommandUpdate()"/>
<commandset id="downloadCommands">
<command id="cmd_properties"
oncommand="goDoCommand('cmd_properties');"/>
<command id="cmd_pause"
oncommand="goDoCommand('cmd_pause');"/>
<command id="cmd_cancel"
oncommand="goDoCommand('cmd_cancel');"/>
<command id="cmd_remove"
oncommand="goDoCommand('cmd_remove');"/>
<command id="cmd_openfile"
oncommand="goDoCommand('cmd_openfile');"/>
<command id="cmd_showinshell"
oncommand="goDoCommand('cmd_showinshell');"/>
</commandset>
<!-- File Menu -->
<command id="cmd_newNavigator"/>
<command id="cmd_close" oncommand="close()"/>
<command id="cmd_quit"/>
</commandset>
<broadcasterset id="navBroadcasters"/>
<keyset id="tasksKeys">
<!-- File Menu -->
<key id="key_newNavigator"/>
<key id="key_close"/>
<key id="key_quit"/>
<!-- These keybindings do not have a command specified in the overlay,
which is good, but we need to specify it ourselves here -->
<key id="key_selectAll" command="cmd_selectAll"/>
<key id="key_remove" keycode="VK_DELETE" command="cmd_remove"/>
<key id="key_properties" key="&cmd.properties.keybinding;"
command="cmd_properties" modifiers="accel"/>
</keyset>
<toolbox id="toolbox">
<toolbar id="download-toolbar" tbalign="stretch" class="chromeclass-toolbar" persist="collapsed" grippytooltiptext="&dm.tooltip;">
<toolbarbutton label="&cmd.properties.label;" accesskey="&cmd.properties.accesskey;"
command="cmd_properties"/>
<toolbarseparator/>
<toolbarbutton label="&cmd.cancel.label;" accesskey="&cmd.cancel.accesskey;"
command="cmd_cancel"/>
<toolbarbutton label="&cmd.remove.label;" accesskey="&cmd.remove.accesskey;"
command="cmd_remove"/>
<toolbarseparator/>
<toolbarbutton id="btn_openfile" label="&cmd.openfile.label;" accesskey="&cmd.openfile.accesskey;"
command="cmd_openfile"/>
<toolbarbutton id="btn_showinshell" command="cmd_showinshell"/>
</toolbar>
</toolbox>
<tree id="downloadView" flex="1" class="plain"
datasources="rdf:null" ref="NC:DownloadsRoot" flags="dont-test-empty"
ondblclick="return goDoCommand('cmd_properties');" enableColumnDrag="true"
onselect="onSelect(event);">
<treecols>
<treecol id="Name" primary="true"
label="&view.header.name.label;"
class="sortDirectionIndicator" width="3*" flex="3"
sort="http://home.netscape.com/NC-rdf#Name"
persist="width sortActive sortDirection"/>
<splitter class="tree-splitter"/>
<treecol id="Progress" type="progressmeter"
label="&view.header.progress.label;"
class="sortDirectionIndicator" width="3*" flex="3"
sort="http://home.netscape.com/NC-rdf#ProgressPercent"
persist="width hidden sortActive sortDirection"
sortActive="true" sortDirection="descending"/>
<splitter class="tree-splitter"/>
<treecol id="ProgressPercent" hidden="true"
label="&view.header.progresstext.label;"
class="sortDirectionIndicator" width="1*" flex="1"
sort="http://home.netscape.com/NC-rdf#ProgressPercent"
persist="width hidden sortActive sortDirection"/>
<splitter class="tree-splitter"/>
<treecol id="TimeRemaining"
label="&view.header.timeremaining.label;"
class="sortDirectionIndicator" width="1*" flex="1"
sort="http://home.netscape.com/NC-rdf#TimeRemaining"
persist="width hidden sortActive sortDirection"/>
<splitter class="tree-splitter"/>
<treecol id="Transferred"
label="&view.header.transferred.label;"
class="sortDirectionIndicator" width="1*" flex="1"
sort="http://home.netscape.com/NC-rdf#Transferred"
persist="width hidden sortActive sortDirection"/>
<splitter class="tree-splitter"/>
<treecol id="TransferRate"
label="&view.header.transferrate.label;"
class="sortDirectionIndicator" width="1*" flex="1"
sort="http://home.netscape.com/NC-rdf#TransferRate"
persist="width hidden sortActive sortDirection"/>
<splitter class="tree-splitter"/>
<treecol id="TimeElapsed" hidden="true"
label="&view.header.timeelapsed.label;"
class="sortDirectionIndicator" width="1*" flex="1"
sort="http://home.netscape.com/NC-rdf#TimeElapsed"
persist="width hidden sortActive sortDirection"/>
<splitter class="tree-splitter"/>
<treecol id="Source" hidden="true"
label="&view.header.source.label;"
class="sortDirectionIndicator" width="1*" flex="1"
sort="http://home.netscape.com/NC-rdf#URL"
persist="width hidden sortActive sortDirection"/>
</treecols>
<template>
<rule>
<treechildren>
<treeitem uri="rdf:*">
<treerow>
<treecell src="moz-icon:rdf:http://home.netscape.com/NC-rdf#File"
label="rdf:http://home.netscape.com/NC-rdf#Name"/>
<treecell mode="rdf:http://home.netscape.com/NC-rdf#ProgressMode"
value="rdf:http://home.netscape.com/NC-rdf#ProgressPercent"
label="rdf:http://home.netscape.com/NC-rdf#StatusText"/>
<treecell label="rdf:http://home.netscape.com/NC-rdf#ProgressPercent"/>
<treecell label="rdf:http://home.netscape.com/NC-rdf#TimeRemaining"/>
<treecell label="rdf:http://home.netscape.com/NC-rdf#Transferred"/>
<treecell label="rdf:http://home.netscape.com/NC-rdf#TransferRate"/>
<treecell label="rdf:http://home.netscape.com/NC-rdf#TimeElapsed"/>
<treecell label="rdf:http://home.netscape.com/NC-rdf#URL"/>
</treerow>
</treeitem>
</treechildren>
</rule>
</template>
</tree>
<statusbar id="status-bar" class="chromeclass-status">
<statusbarpanel id="statusbar-text" label="" flex="1"/>
</statusbar>
</window>

View File

@@ -0,0 +1,8 @@
browser.jar:
content/browser/downloads/downloadmanager.xul (content/downloadmanager.xul)
content/browser/downloads/downloadmanager.js (content/downloadmanager.js)
en-US.jar:
locale/en-US/browser/downloads/downloadmanager.dtd (locale/downloadmanager.dtd)
locale/en-US/browser/downloads/downloadmanager.properties (locale/downloadmanager.properties)

View File

@@ -0,0 +1,27 @@
<!ENTITY view.header.name.label "Name">
<!ENTITY view.header.progress.label "Progress">
<!ENTITY view.header.status.label "Status">
<!ENTITY view.header.timeremaining.label "Time Remaining">
<!ENTITY view.header.transferred.label "Transferred">
<!ENTITY view.header.transferrate.label "Speed">
<!ENTITY view.header.timeelapsed.label "Time Elapsed">
<!ENTITY view.header.progresstext.label "&#37;">
<!ENTITY view.header.source.label "Source">
<!ENTITY downloadManager.title "Download Manager">
<!ENTITY cmd.properties.label "Properties">
<!ENTITY cmd.properties.accesskey "i">
<!ENTITY cmd.properties.keybinding "i">
<!ENTITY cmd.pause.label "Pause">
<!ENTITY cmd.pause.accesskey "p">
<!ENTITY cmd.remove.label "Remove from List">
<!ENTITY cmd.remove.accesskey "r">
<!ENTITY cmd.cancel.label "Cancel">
<!ENTITY cmd.cancel.accesskey "c">
<!ENTITY cmd.openfile.label "Launch File">
<!ENTITY cmd.openfile.accesskey "L">
<!ENTITY dm.tooltip "Toolbar">
<!ENTITY confirmCancel "Are you sure you want to cancel the saving of this file?">
<!ENTITY progressMsgNoRate "#1KB of #2KB">
<!ENTITY rateMsg "#1KB/sec">

View File

@@ -0,0 +1,16 @@
transferred=%1SKB of %2SKB
downloading=Downloading
notStarted=Not Started
failed=Failed
finished=Finished
canceled=Canceled
alertTitle=Download Error
showInShellLabelWin=Show in Explorer
showInShellAccesskeyWin=E
showInShellLabelMac=Show in Finder
showInShellAccesskeyMac=F
showInShellLabelUnix=Show in Browser
showInShellAccesskeyUnix=B

View File

@@ -0,0 +1 @@
Makefile

View File

@@ -0,0 +1,35 @@
#
# 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.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
DEPTH = ../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = downloads
XPIDLSRCS = nsIDownloadManager.idl \
nsIDownloadProgressListener.idl \
include $(topsrcdir)/config/rules.mk

View File

@@ -0,0 +1,173 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* 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.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Blake Ross <blaker@netscape.com>
* Ben Goodger <ben@netscape.com>
*
* 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 NPL, 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 NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// Keeps track of ongoing downloads, in the form of nsIDownload's.
#include "nsISupports.idl"
interface nsIDOMWindow;
interface nsIURI;
interface nsILocalFile;
interface nsIDownload;
interface nsIWebBrowserPersist;
interface nsIMIMEInfo;
[scriptable, uuid(9be66cc0-1dd1-11b2-8617-e3a3ed26e3b0)]
interface nsIDownloadManager : nsISupports {
// Methods called by clients to carry out various managing functions
/**
* Creates an nsIDownload and adds it to be managed by the download manager.
*
* @param aSource The source (nsIURI) of the download.
*
* @param aTarget The local file to which the download is being saved.
*
* @param aDisplayName The user-readable description of the download.
*
* @param aPersist The "persist" used to transfer the download. If set,
* the manager will set its listener to the download item
* and use it for cancellation. If not set, the client
* is expected to set the download item as the listener on
* whatever transfer component is being used, and to
* set an observer on the download item that listens for
* the "oncancel" topic and cancels the download.
*
* @return The newly created download item with the passed-in properties.
*/
nsIDownload addDownload(in nsIURI aSource,
in nsILocalFile aTarget,
in wstring aDisplayName,
in nsIMIMEInfo aMIMEInfo,
in long long startTime,
in nsIWebBrowserPersist aPersist);
/**
* Retrieves an in-progress download managed by the download manager.
*
* @param aPersistentDescriptor The unique identifier used to describe a
* a download, and an attribute of nsILocalFile.
* On Windows and Linux, this is just the path
* of the target, but on Mac this is guaranteed
* to be unique.
*
* @return The download with the specified persistent descriptor.
*/
nsIDownload getDownload(in string aPersistentDescriptor);
/**
* Cancels the download with the specified persistent descriptor if it's
* currently in progress. If a "persist" was specified for the download,
* nsIWebBrowserPersist::CancelSave will be called. If an observer was set
* on the nsIDownload, it will be notified with the "oncancel" topic. Clients
* that don't provide a "persist" must listen for this topic and cancel the
* download.
*
* @param aPersistentDescriptor The persistent descriptor of the download to
* be cancelled.
*/
void cancelDownload(in string aPersistentDescriptor);
/**
* Removes the download with the specified persistent descriptor if it's not
* currently in progress. Whereas cancelDownload simply cancels the transfer
* but retains information about it, removeDownload removes all knowledge of it.
*
* @param aPersistentDescriptor The persistent descriptor of the download to
* be removed.
*/
void removeDownload(in string aPersistentDescriptor);
// UI-related methods
/**
* Opens the Download Manager front end.
*
* @param aParent The parent, or opener, of the front end (optional).
* @param aDownload A download to pass to the manager window. Useful
* if, for example, you want the window to select a
* certain download (optional).
*/
void open(in nsIDOMWindow aParent, in nsIDownload aDownload);
/**
* Opens an individual progress dialog displaying progress for the download.
*
* @param aPersistentDescriptor The persistent descriptor of the download to
* display progress for.
*
* @param aParent The parent, or opener, of the front end (optional).
*/
void openProgressDialogFor(in string aPersistentDescriptor, in nsIDOMWindow aParent);
/**
* Called when the download manager front end is closed. Useful for
* third party managers to let us know when they've closed.
*/
void onClose();
/**
* Indicate that a batch update (e.g. mass removal) is about to start.
*/
void startBatchUpdate();
/**
* Indicate that a batch update is ending.
*/
void endBatchUpdate();
};
%{C++
#define NS_DOWNLOADMANAGER_CONTRACTID "@mozilla.org/download-manager;1"
#define NS_DOWNLOADMANAGER_CLASSNAME "Mozilla Download Manager"
// {EDB0490E-1DD1-11B2-83B8-DBF8D85906A6}
#define NS_DOWNLOADMANAGER_CID \
{ 0xedb0490e, 0x1dd1, 0x11b2, { 0x83, 0xb8, 0xdb, 0xf8, 0xd8, 0x59, 0x06, 0xa6 } }
%}

View File

@@ -0,0 +1,95 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* 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.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Blake Ross <blaker@netscape.com>
*
* 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 NPL, 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 NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/* A minimally extended progress listener used by download manager
* to update its default UI. This is implemented in nsDownloadProgressListener.js.
* See nsIWebProgressListener for documentation, and use its constants. This isn't
* too pretty, but the alternative is having this extend nsIWebProgressListener and
* adding an |item| attribute, which would mean a separate nsIDownloadProgressListener
* for every nsIDownloadItem, which is a waste...
*/
#include "nsISupports.idl"
interface nsIWebProgress;
interface nsIRequest;
interface nsIURI;
interface nsIDownload;
interface nsIDOMDocument;
[scriptable, uuid(09cddbea-1dd2-11b2-aa15-c41ffea19d79)]
interface nsIDownloadProgressListener : nsISupports {
/**
* document
* The document of the download manager frontend.
*/
attribute nsIDOMDocument document;
void onStateChange(in nsIWebProgress aWebProgress,
in nsIRequest aRequest,
in unsigned long aStateFlags,
in nsresult aStatus,
in nsIDownload aDownload);
void onProgressChange(in nsIWebProgress aWebProgress,
in nsIRequest aRequest,
in long aCurSelfProgress,
in long aMaxSelfProgress,
in long aCurTotalProgress,
in long aMaxTotalProgress,
in nsIDownload aDownload);
void onStatusChange(in nsIWebProgress aWebProgress,
in nsIRequest aRequest,
in nsresult aStatus,
in wstring aMessage,
in nsIDownload aDownload);
void onLocationChange(in nsIWebProgress aWebProgress,
in nsIRequest aRequest,
in nsIURI aLocation,
in nsIDownload aDownload);
void onSecurityChange(in nsIWebProgress aWebProgress,
in nsIRequest aRequest,
in unsigned long aState,
in nsIDownload aDownload);
};

View File

@@ -0,0 +1 @@
Makefile

View File

@@ -0,0 +1,59 @@
#! gmake
#
# 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 Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 2000 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Stuart Parmenter <pavlov@netscape.com>
#
DEPTH = ../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = downloads
LIBRARY_NAME = download_s
REQUIRES = xpcom \
string \
rdf \
uriloader \
mimetype \
necko \
progressDlg \
intl \
windowwatcher \
webbrowserpersist \
appshell \
dom \
$(NULL)
CPPSRCS = \
nsDownloadManager.cpp \
$(NULL)
EXTRA_COMPONENTS = nsDownloadProgressListener.js
# we don't want the shared lib, but we want to force the creation of a
# static lib.
FORCE_STATIC_LIB = 1
include $(topsrcdir)/config/rules.mk
EXTRA_DSO_LDOPTS += $(MOZ_COMPONENT_LIBS)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,154 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* 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.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Blake Ross <blaker@netscape.com>
* Ben Goodger <ben@netscape.com>
*
* 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 NPL, 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 NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef downloadmanager___h___
#define downloadmanager___h___
#include "nsIDownloadManager.h"
#include "nsIDownloadProgressListener.h"
#include "nsIDownload.h"
#include "nsIRDFDataSource.h"
#include "nsIRDFRemoteDataSource.h"
#include "nsIRDFService.h"
#include "nsIDOMDocument.h"
#include "nsIDOMEventListener.h"
#include "nsIRDFContainerUtils.h"
#include "nsIWebProgressListener.h"
#include "nsIURI.h"
#include "nsIWebBrowserPersist.h"
#include "nsILocalFile.h"
#include "nsHashtable.h"
#include "nsIRequest.h"
#include "nsIObserver.h"
#include "nsIStringBundle.h"
#include "nsIProgressDialog.h"
#include "nsIMIMEInfo.h"
enum DownloadState { NOTSTARTED = -1, DOWNLOADING, FINISHED, FAILED, CANCELED };
class nsDownloadManager : public nsIDownloadManager,
public nsIDOMEventListener,
public nsIObserver
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIDOWNLOADMANAGER
NS_DECL_NSIDOMEVENTLISTENER
NS_DECL_NSIOBSERVER
nsresult Init();
nsDownloadManager();
virtual ~nsDownloadManager();
protected:
nsresult GetDownloadsContainer(nsIRDFContainer** aResult);
nsresult GetProfileDownloadsFileURL(nsCString& aDownloadsFileURL);
nsresult GetInternalListener(nsIDownloadProgressListener** aInternalListener);
nsresult GetDataSource(nsIRDFDataSource** aDataSource);
nsresult AssertProgressInfo();
nsresult AssertProgressInfoFor(const char* aPersistentDescriptor);
nsresult DownloadStarted(const char* aPersistentDescriptor);
nsresult DownloadEnded(const char* aPersistentDescriptor, const PRUnichar* aMessage);
PRBool MustUpdateUI() { if (mDocument) return PR_TRUE; return PR_FALSE; }
private:
nsCOMPtr<nsIRDFDataSource> mDataSource;
nsCOMPtr<nsIDOMDocument> mDocument;
nsCOMPtr<nsIRDFContainer> mDownloadsContainer;
nsCOMPtr<nsIDownloadProgressListener> mListener;
nsCOMPtr<nsIRDFContainerUtils> mRDFContainerUtils;
nsCOMPtr<nsIStringBundle> mBundle;
PRInt32 mBatches;
nsHashtable mCurrDownloads;
friend class nsDownload;
};
class nsDownload : public nsIDownload,
public nsIWebProgressListener
{
public:
NS_DECL_NSIWEBPROGRESSLISTENER
NS_DECL_NSIDOWNLOAD
NS_DECL_ISUPPORTS
nsDownload();
virtual ~nsDownload();
protected:
nsresult SetDownloadManager(nsDownloadManager* aDownloadManager);
nsresult SetDialogListener(nsIWebProgressListener* aInternalListener);
nsresult GetDialogListener(nsIWebProgressListener** aInternalListener);
nsresult SetDialog(nsIProgressDialog* aDialog);
nsresult GetDialog(nsIProgressDialog** aDialog);
nsresult SetPersist(nsIWebBrowserPersist* aPersist);
nsresult SetTarget(nsILocalFile* aTarget);
nsresult SetSource(nsIURI* aSource);
nsresult GetTransferInformation(PRInt32* aCurr, PRInt32* aMax);
nsresult GetDownloadState(DownloadState* aState);
nsresult SetDownloadState(DownloadState aState);
nsresult SetMIMEInfo(nsIMIMEInfo* aMIMEInfo);
nsresult SetStartTime(PRInt64 aStartTime);
private:
nsDownloadManager* mDownloadManager;
nsString mDisplayName;
nsCOMPtr<nsILocalFile> mTarget;
nsCOMPtr<nsIURI> mSource;
nsCOMPtr<nsIWebProgressListener> mListener;
nsCOMPtr<nsIWebProgressListener> mDialogListener;
nsCOMPtr<nsIWebBrowserPersist> mPersist;
nsCOMPtr<nsIRequest> mRequest;
nsCOMPtr<nsIProgressDialog> mDialog;
nsCOMPtr<nsIObserver> mObserver;
nsCOMPtr<nsIMIMEInfo> mMIMEInfo;
DownloadState mDownloadState;
PRInt32 mPercentComplete;
PRInt32 mCurrBytes;
PRInt32 mMaxBytes;
PRInt64 mStartTime;
PRTime mLastUpdate;
friend class nsDownloadManager;
};
#endif

View File

@@ -0,0 +1,319 @@
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* 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.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Blake Ross <blaker@netscape.com> (Original Author)
*
* 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 NPL, 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 NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
var gStrings = new Array;
const interval = 500; // Update every 500 milliseconds.
function nsDownloadProgressListener() {
}
nsDownloadProgressListener.prototype = {
elapsed: 0,
rateChanges: 0,
rateChangeLimit: 0,
priorRate: 0,
lastUpdate: -500,
doc: null,
get document() {
return this.doc;
},
set document(newval) {
return this.doc = newval;
},
onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus, aDownload)
{
if (aStateFlags & Components.interfaces.nsIWebProgressListener.STATE_STOP)
{
var aDownloadID = aDownload.target.persistentDescriptor;
var elt = this.doc.getElementById(aDownloadID).firstChild.firstChild;
var timeRemainingCol = elt.nextSibling.nextSibling.nextSibling;
timeRemainingCol.setAttribute("label", "");
var speedCol = timeRemainingCol.nextSibling.nextSibling;
speedCol.setAttribute("label", "");
var elapsedCol = speedCol.nextSibling;
elapsedCol.setAttribute("label", "");
}
},
onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress,
aCurTotalProgress, aMaxTotalProgress, aDownload)
{
var overallProgress = aCurTotalProgress;
// Get current time.
var now = ( new Date() ).getTime();
// If interval hasn't elapsed, ignore it.
if ( now - this.lastUpdate < interval && aMaxTotalProgress != "-1" && parseInt(aCurTotalProgress) < parseInt(aMaxTotalProgress) ) {
return;
}
// Update this time.
this.lastUpdate = now;
// Update download rate.
this.elapsed = now - (aDownload.startTime / 1000);
var rate; // aCurTotalProgress/sec
if ( this.elapsed )
rate = ( aCurTotalProgress * 1000 ) / this.elapsed;
else
rate = 0;
var aDownloadID = aDownload.target.persistentDescriptor;
var elt = this.doc.getElementById(aDownloadID).firstChild.firstChild;
if (this.doc.getElementById("TimeElapsed").getAttribute("hidden") != "true") {
elapsedCol = elt.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling;
// Update elapsed time display.
elapsedCol.setAttribute("label", formatSeconds( this.elapsed / 1000, this.doc ));
}
// Calculate percentage.
var percent;
var progressCol = elt.nextSibling;
if ( aMaxTotalProgress > 0)
{
percent = Math.floor((overallProgress*100.0)/aMaxTotalProgress);
if ( percent > 100 )
percent = 100;
// Advance progress meter.
progressCol.setAttribute( "value", percent );
progressCol.setAttribute("mode", "normal");
}
else
{
percent = -1;
// Progress meter should be barber-pole in this case.
progressCol.setAttribute( "mode", "undetermined" );
}
// now that we've set the progress and the time, update # bytes downloaded...
// Update status (nnK of mmK bytes at xx.xK aCurTotalProgress/sec)
var status = getString( "progressMsgNoRate", this.doc );
// Insert 1 is the number of kilobytes downloaded so far.
status = replaceInsert( status, 1, parseInt( overallProgress/1024 + .5 ) );
// Insert 2 is the total number of kilobytes to be downloaded (if known).
if ( aMaxTotalProgress != "-1" )
status = replaceInsert( status, 2, parseInt( aMaxTotalProgress/1024 + .5 ) );
else
status = replaceInsert( status, 2, "??" );
var rateMsg = getString( "rateMsg", this.doc );
if ( rate )
{
// rate is bytes/sec
var kRate = rate / 1024; // K bytes/sec;
kRate = parseInt( kRate * 10 + .5 ); // xxx (3 digits)
// Don't update too often!
if ( kRate != this.priorRate )
{
if ( this.rateChanges++ == this.rateChangeLimit )
{
// Time to update download rate.
this.priorRate = kRate;
this.rateChanges = 0;
}
else
{
// Stick with old rate for a bit longer.
kRate = this.priorRate;
}
}
else
this.rateChanges = 0;
var fraction = kRate % 10;
kRate = parseInt( ( kRate - fraction ) / 10 );
// Insert 3 is the download rate (in kilobytes/sec).
rateMsg = replaceInsert( rateMsg, 1, kRate + "." + fraction );
}
else
rateMsg = replaceInsert( rateMsg, 1, "??.?" );
var timeRemainingCol = elt.nextSibling.nextSibling.nextSibling;
// Update status msg.
var statusCol = timeRemainingCol.nextSibling;
statusCol.setAttribute("label", status);
var speedCol = statusCol.nextSibling;
speedCol.setAttribute("label", rateMsg);
// Update percentage label on progress meter.
if (this.doc.getElementById("ProgressPercent").getAttribute("hidden") != "true") {
var progressText = elt.nextSibling.nextSibling;
if (percent < 0)
progressText.setAttribute("label", "");
else {
var percentMsg = getString( "percentMsg", this.doc );
percentMsg = replaceInsert( percentMsg, 1, percent );
progressText.setAttribute("label", percentMsg);
}
}
// Update time remaining.
if ( rate && (aMaxTotalProgress > 0) )
{
var rem = ( aMaxTotalProgress - aCurTotalProgress ) / rate;
rem = parseInt( rem + .5 );
timeRemainingCol.setAttribute("label", formatSeconds( rem, this.doc ));
}
else
timeRemainingCol.setAttribute("label", getString( "unknownTime", this.doc ));
},
onLocationChange: function(aWebProgress, aRequest, aLocation, aDownload)
{
},
onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage, aDownload)
{
},
onSecurityChange: function(aWebProgress, aRequest, state, aDownload)
{
},
QueryInterface : function(iid)
{
if (iid.equals(Components.interfaces.nsIDownloadProgressListener) ||
iid.equals(Components.interfaces.nsISupports))
return this;
throw Components.results.NS_NOINTERFACE;
}
};
var nsDownloadProgressListenerFactory = {
createInstance: function (outer, iid) {
if (outer != null)
throw Components.results.NS_ERROR_NO_AGGREGATION;
return (new nsDownloadProgressListener()).QueryInterface(iid);
}
};
var nsDownloadProgressListenerModule = {
registerSelf: function (compMgr, fileSpec, location, type)
{
compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentManagerObsolete);
compMgr.registerComponentWithType(Components.ID("{09cddbea-1dd2-11b2-aa15-c41ffea19d79}"),
"Download Progress Listener",
"@mozilla.org/download-manager/listener;1", fileSpec,
location, true, true, type);
},
canUnload: function(compMgr)
{
return true;
},
getClassObject: function (compMgr, cid, iid) {
if (!cid.equals(Components.ID("{09cddbea-1dd2-11b2-aa15-c41ffea19d79}")))
throw Components.results.NS_ERROR_NO_INTERFACE;
if (!iid.equals(Components.interfaces.nsIFactory))
throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
return nsDownloadProgressListenerFactory;
}
};
function NSGetModule(compMgr, fileSpec) {
return nsDownloadProgressListenerModule;
}
function replaceInsert( text, index, value ) {
var result = text;
var regExp = new RegExp( "#"+index );
result = result.replace( regExp, value );
return result;
}
function getString( stringId, doc ) {
// Check if we've fetched this string already.
if ( !gStrings[ stringId ] ) {
// Try to get it.
var elem = doc.getElementById( "strings."+stringId );
try {
if ( elem
&&
elem.childNodes
&&
elem.childNodes[0]
&&
elem.childNodes[0].nodeValue ) {
gStrings[ stringId ] = elem.childNodes[0].nodeValue;
} else {
// If unable to fetch string, use an empty string.
gStrings[ stringId ] = "";
}
} catch (e) { gStrings[ stringId ] = ""; }
}
return gStrings[ stringId ];
}
function formatSeconds( secs, doc )
{
// Round the number of seconds to remove fractions.
secs = parseInt( secs + .5 );
var hours = parseInt( secs/3600 );
secs -= hours*3600;
var mins = parseInt( secs/60 );
secs -= mins*60;
var result;
if ( hours )
result = getString( "longTimeFormat", doc );
else
result = getString( "shortTimeFormat", doc );
if ( hours < 10 )
hours = "0" + hours;
if ( mins < 10 )
mins = "0" + mins;
if ( secs < 10 )
secs = "0" + secs;
// Insert hours, minutes, and seconds into result string.
result = replaceInsert( result, 1, hours );
result = replaceInsert( result, 2, mins );
result = replaceInsert( result, 3, secs );
return result;
}

View File

@@ -0,0 +1,209 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* 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.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Blake Ross <blaker@netscape.com> (Original Author)
*
* 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 NPL, 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 NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef downloadproxy___h___
#define downloadproxy___h___
#include "nsIDownload.h"
#include "nsIDownloadManager.h"
#include "nsIPrefBranch.h"
#include "nsIPrefService.h"
#include "nsIMIMEInfo.h"
#define DOWNLOAD_MANAGER_BEHAVIOR_PREF "browser.downloadmanager.behavior"
class nsDownloadProxy : public nsIDownload,
public nsIWebProgressListener
{
public:
nsDownloadProxy() { NS_INIT_ISUPPORTS(); }
virtual ~nsDownloadProxy() { };
NS_DECL_ISUPPORTS
NS_IMETHODIMP Init(nsIURI* aSource,
nsILocalFile* aTarget,
const PRUnichar* aDisplayName,
nsIMIMEInfo *aMIMEInfo,
PRInt64 aStartTime,
nsIWebBrowserPersist* aPersist) {
nsresult rv;
nsCOMPtr<nsIDownloadManager> dm = do_GetService("@mozilla.org/download-manager;1", &rv);
if (NS_FAILED(rv)) return rv;
rv = dm->AddDownload(aSource, aTarget, aDisplayName, aMIMEInfo, aStartTime, aPersist, getter_AddRefs(mInner));
if (NS_FAILED(rv)) return rv;
PRInt32 behavior = 0;
nsCOMPtr<nsIPrefService> prefs = do_GetService("@mozilla.org/preferences-service;1", &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIPrefBranch> branch = do_QueryInterface(prefs);
branch->GetIntPref(DOWNLOAD_MANAGER_BEHAVIOR_PREF, &behavior);
if (behavior == 0)
return dm->Open(nsnull, this);
if (behavior == 1) {
nsCAutoString path;
rv = aTarget->GetNativePath(path);
if (NS_FAILED(rv)) return rv;
return dm->OpenProgressDialogFor(path.get(), nsnull);
}
return rv;
}
NS_IMETHODIMP GetDisplayName(PRUnichar** aDisplayName)
{
return mInner->GetDisplayName(aDisplayName);
}
NS_IMETHODIMP SetDisplayName(const PRUnichar* aDisplayName)
{
return mInner->SetDisplayName(aDisplayName);
}
NS_IMETHODIMP GetMIMEInfo(nsIMIMEInfo** aMIMEInfo)
{
return mInner->GetMIMEInfo(aMIMEInfo);
}
NS_IMETHODIMP GetSource(nsIURI** aSource)
{
return mInner->GetSource(aSource);
}
NS_IMETHODIMP GetTarget(nsILocalFile** aTarget)
{
return mInner->GetTarget(aTarget);
}
NS_IMETHODIMP GetStartTime(PRInt64* aStartTime)
{
return mInner->GetStartTime(aStartTime);
}
NS_IMETHODIMP GetPercentComplete(PRInt32* aPercentComplete)
{
return mInner->GetPercentComplete(aPercentComplete);
}
NS_IMETHODIMP GetListener(nsIWebProgressListener** aListener)
{
return mInner->GetListener(aListener);
}
NS_IMETHODIMP SetListener(nsIWebProgressListener* aListener)
{
return mInner->SetListener(aListener);
}
NS_IMETHODIMP GetObserver(nsIObserver** aObserver)
{
return mInner->GetObserver(aObserver);
}
NS_IMETHODIMP SetObserver(nsIObserver* aObserver)
{
return mInner->SetObserver(aObserver);
}
NS_IMETHODIMP GetPersist(nsIWebBrowserPersist** aPersist)
{
return mInner->GetPersist(aPersist);
}
NS_IMETHODIMP OnStateChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest, PRUint32 aStateFlags,
PRUint32 aStatus)
{
nsCOMPtr<nsIWebProgressListener> listener = do_QueryInterface(mInner);
if (listener)
return listener->OnStateChange(aWebProgress, aRequest, aStateFlags, aStatus);
return NS_OK;
}
NS_IMETHODIMP OnStatusChange(nsIWebProgress *aWebProgress,
nsIRequest *aRequest, nsresult aStatus,
const PRUnichar *aMessage)
{
nsCOMPtr<nsIWebProgressListener> listener = do_QueryInterface(mInner);
if (listener)
return listener->OnStatusChange(aWebProgress, aRequest, aStatus, aMessage);
return NS_OK;
}
NS_IMETHODIMP OnLocationChange(nsIWebProgress *aWebProgress,
nsIRequest *aRequest, nsIURI *aLocation)
{
nsCOMPtr<nsIWebProgressListener> listener = do_QueryInterface(mInner);
if (listener)
return listener->OnLocationChange(aWebProgress, aRequest, aLocation);
return NS_OK;
}
NS_IMETHODIMP OnProgressChange(nsIWebProgress *aWebProgress,
nsIRequest *aRequest,
PRInt32 aCurSelfProgress,
PRInt32 aMaxSelfProgress,
PRInt32 aCurTotalProgress,
PRInt32 aMaxTotalProgress)
{
nsCOMPtr<nsIWebProgressListener> listener = do_QueryInterface(mInner);
if (listener)
return listener->OnProgressChange(aWebProgress, aRequest, aCurSelfProgress,
aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress);
return NS_OK;
}
NS_IMETHODIMP OnSecurityChange(nsIWebProgress *aWebProgress,
nsIRequest *aRequest, PRUint32 aState)
{
nsCOMPtr<nsIWebProgressListener> listener = do_QueryInterface(mInner);
if (listener)
return listener->OnSecurityChange(aWebProgress, aRequest, aState);
return NS_OK;
}
private:
nsCOMPtr<nsIDownload> mInner;
};
NS_IMPL_ISUPPORTS2(nsDownloadProxy, nsIDownload, nsIWebProgressListener)
#endif