Compare commits

..

1 Commits

Author SHA1 Message Date
(no author)
258dc9fead This commit was manufactured by cvs2svn to create branch 'src'.
git-svn-id: svn://10.0.0.236/branches/src@33658 18797224-902f-48f8-a5cc-f745e15eee43
1999-06-03 23:10:01 +00:00
130 changed files with 18627 additions and 8607 deletions

View File

@@ -1,824 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsCOMPtr.h"
#include "nsIModule.h"
#include "nsIGenericFactory.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsICategoryManager.h"
#include "nsIOService.h"
#include "nsNetModuleMgr.h"
#include "nsFileTransportService.h"
#include "nsSocketTransportService.h"
#include "nsSocketProviderService.h"
#include "nscore.h"
#include "nsStdURLParser.h"
#include "nsAuthURLParser.h"
#include "nsNoAuthURLParser.h"
#include "nsStdURL.h"
#include "nsSimpleURI.h"
#include "nsDnsService.h"
#include "nsLoadGroup.h"
#include "nsInputStreamChannel.h"
#include "nsStreamLoader.h"
#include "nsDownloader.h"
#include "nsAsyncStreamListener.h"
//#include "nsSyncStreamListener.h"
#include "nsFileStreams.h"
#include "nsBufferedStreams.h"
#include "nsProtocolProxyService.h"
#include "nsSOCKSSocketProvider.h"
#include "nsNetCID.h"
///////////////////////////////////////////////////////////////////////////////
#include "nsStreamConverterService.h"
///////////////////////////////////////////////////////////////////////////////
#include "nsINetDataCache.h"
#include "nsINetDataCacheManager.h"
#include "nsMemCacheCID.h"
#include "nsMemCache.h"
#include "nsNetDiskCache.h"
#include "nsNetDiskCacheCID.h"
#include "nsCacheManager.h"
// Factory method to create a new nsMemCache instance. Used
// by nsNetDataCacheModule
NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsMemCache, Init)
NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsNetDiskCache, Init)
NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsCacheManager, Init)
///////////////////////////////////////////////////////////////////////////////
#include "nsMIMEService.h"
#include "nsXMLMIMEDataSource.h"
#include "nsMIMEInfoImpl.h"
NS_GENERIC_FACTORY_CONSTRUCTOR(nsMIMEInfoImpl)
///////////////////////////////////////////////////////////////////////////////
#include "nsStreamObserverProxy.h"
#include "nsStreamListenerProxy.h"
#include "nsStreamProviderProxy.h"
#include "nsSimpleStreamListener.h"
#include "nsSimpleStreamProvider.h"
NS_GENERIC_FACTORY_CONSTRUCTOR(nsStreamObserverProxy)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsStreamListenerProxy)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsStreamProviderProxy)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsSimpleStreamListener)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsSimpleStreamProvider)
///////////////////////////////////////////////////////////////////////////////
#include "nsStorageTransport.h"
NS_GENERIC_FACTORY_CONSTRUCTOR(nsStorageTransport)
///////////////////////////////////////////////////////////////////////////////
#include "nsIHTTPProtocolHandler.h"
#include "nsHTTPHandler.h"
#include "nsHTTPSHandler.h"
#include "nsBasicAuth.h"
NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsHTTPHandler, Init);
//NS_GENERIC_FACTORY_CONSTRUCTOR(nsHTTPSHandler);
#define NS_HTTPS_HANDLER_FACTORY_CID { 0xd2771480, 0xcac4, 0x11d3, { 0x8c, 0xaf, 0x0, 0x0, 0x64, 0x65, 0x73, 0x74 } }
NS_GENERIC_FACTORY_CONSTRUCTOR(nsBasicAuth);
#define NS_BASICAUTH_CID { 0xd5c9bc48, 0x1dd1, 0x11b2, { 0x9a, 0x0b, 0xf7, 0x3f, 0x59, 0x53, 0x19, 0xae } }
#define NS_BASICAUTH_CONTRACTID "@mozilla.org/network/http-basic-auth;1"
/* XXX this should all be data-driven, via NS_IMPL_GETMODULE_WITH_CATEGORIES */
static NS_METHOD
RegisterBasicAuth(nsIComponentManager *aCompMgr, nsIFile *aPath,
const char *registryLocation, const char *componentType)
{
nsresult rv;
nsCOMPtr<nsICategoryManager> catman =
do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
nsXPIDLCString previous;
return catman->AddCategoryEntry("http-auth", "basic", NS_BASICAUTH_CONTRACTID,
PR_TRUE, PR_TRUE, getter_Copies(previous));
}
static NS_METHOD
UnregisterBasicAuth(nsIComponentManager *aCompMgr, nsIFile *aPath,
const char *registryLocation)
{
nsresult rv;
nsCOMPtr<nsICategoryManager> catman =
do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
nsXPIDLCString basicAuth;
rv = catman->GetCategoryEntry("http-auth", "basic",
getter_Copies(basicAuth));
if (NS_FAILED(rv)) return rv;
// only unregister if we're the current Basic-auth handler
if (!strcmp(basicAuth, NS_BASICAUTH_CONTRACTID))
return catman->DeleteCategoryEntry("http-auth", "basic", PR_TRUE,
getter_Copies(basicAuth));
return NS_OK;
}
///////////////////////////////////////////////////////////////////////////////
#include "nsFileChannel.h"
#include "nsFileProtocolHandler.h"
#include "nsDataHandler.h"
#include "nsJARProtocolHandler.h"
#include "nsResProtocolHandler.h"
#include "nsAboutProtocolHandler.h"
#include "nsAboutBlank.h"
#include "nsAboutBloat.h"
#include "nsAboutCache.h"
#include "nsAboutCredits.h"
#include "nsAboutPlugins.h"
#include "mzAboutMozilla.h"
#include "nsKeywordProtocolHandler.h"
///////////////////////////////////////////////////////////////////////////////
#include "nsFTPDirListingConv.h"
#include "nsMultiMixedConv.h"
#include "nsHTTPChunkConv.h"
#include "nsHTTPCompressConv.h"
#include "mozTXTToHTMLConv.h"
#include "nsUnknownDecoder.h"
#include "nsTXTToHTMLConv.h"
nsresult NS_NewFTPDirListingConv(nsFTPDirListingConv** result);
nsresult NS_NewMultiMixedConv (nsMultiMixedConv** result);
nsresult MOZ_NewTXTToHTMLConv (mozTXTToHTMLConv** result);
nsresult NS_NewHTTPChunkConv (nsHTTPChunkConv ** result);
nsresult NS_NewHTTPCompressConv (nsHTTPCompressConv ** result);
nsresult NS_NewNSTXTToHTMLConv(nsTXTToHTMLConv** result);
nsresult NS_NewStreamConv(nsStreamConverterService **aStreamConv);
#define FTP_UNIX_TO_INDEX "?from=text/ftp-dir-unix&to=application/http-index-format"
#define FTP_NT_TO_INDEX "?from=text/ftp-dir-nt&to=application/http-index-format"
#define MULTI_MIXED_X "?from=multipart/x-mixed-replace&to=*/*"
#define MULTI_MIXED "?from=multipart/mixed&to=*/*"
#define UNKNOWN_CONTENT "?from=application/x-unknown-content-type&to=*/*"
#define CHUNKED_TO_UNCHUNKED "?from=chunked&to=unchunked"
#define UNCHUNKED_TO_CHUNKED "?from=unchunked&to=chunked"
#define GZIP_TO_UNCOMPRESSED "?from=gzip&to=uncompressed"
#define XGZIP_TO_UNCOMPRESSED "?from=x-gzip&to=uncompressed"
#define COMPRESS_TO_UNCOMPRESSED "?from=compress&to=uncompressed"
#define XCOMPRESS_TO_UNCOMPRESSED "?from=x-compress&to=uncompressed"
#define DEFLATE_TO_UNCOMPRESSED "?from=deflate&to=uncompressed"
#define PLAIN_TO_HTML "?from=text/plain&to=text/html"
static PRUint32 g_StreamConverterCount = 13;
static char *g_StreamConverterArray[] = {
FTP_UNIX_TO_INDEX,
FTP_NT_TO_INDEX,
MULTI_MIXED_X,
MULTI_MIXED,
UNKNOWN_CONTENT,
CHUNKED_TO_UNCHUNKED,
UNCHUNKED_TO_CHUNKED,
GZIP_TO_UNCOMPRESSED,
XGZIP_TO_UNCOMPRESSED,
COMPRESS_TO_UNCOMPRESSED,
XCOMPRESS_TO_UNCOMPRESSED,
DEFLATE_TO_UNCOMPRESSED,
PLAIN_TO_HTML
};
// each stream converter must add its from/to key to the category manager
// in RegisterStreamConverters(). This provides a string representation
// of each registered converter, rooted in the NS_ISTREAMCONVERTER_KEY
// category. These keys are then (when the stream converter service
// needs to chain converters together) enumerated and parsed to build
// a graph of converters for potential chaining.
static NS_METHOD
RegisterStreamConverters(nsIComponentManager *aCompMgr, nsIFile *aPath,
const char *registryLocation, const char *componentType) {
nsresult rv;
nsCOMPtr<nsICategoryManager> catmgr =
do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
nsXPIDLCString previous;
PRUint32 count = 0;
while (count++ < g_StreamConverterCount) {
rv = catmgr->AddCategoryEntry(NS_ISTREAMCONVERTER_KEY, g_StreamConverterArray[count],
nsnull, PR_TRUE, PR_TRUE, getter_Copies(previous));
if (NS_FAILED(rv)) return rv;
NS_ASSERTION(!previous, "someone already registered this converter at startup");
}
return rv;
}
// same as RegisterStreamConverters except the reverse.
static NS_METHOD
UnregisterStreamConverters(nsIComponentManager *aCompMgr, nsIFile *aPath,
const char *registryLocation) {
nsresult rv;
nsCOMPtr<nsICategoryManager> catmgr =
do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
nsXPIDLCString entry;
PRUint32 count = 0;
while (count++ < g_StreamConverterCount) {
rv = catmgr->DeleteCategoryEntry(NS_ISTREAMCONVERTER_KEY, g_StreamConverterArray[count],
PR_TRUE, getter_Copies(entry));
if (NS_FAILED(rv)) return rv;
NS_ASSERTION(entry, "deleting an entry that doesn't exist");
}
return rv;
}
static NS_IMETHODIMP
CreateNewStreamConvServiceFactory(nsISupports* aOuter, REFNSIID aIID, void **aResult)
{
if (!aResult) {
return NS_ERROR_INVALID_POINTER;
}
if (aOuter) {
*aResult = nsnull;
return NS_ERROR_NO_AGGREGATION;
}
nsStreamConverterService* inst = nsnull;
nsresult rv = NS_NewStreamConv(&inst);
if (NS_FAILED(rv)) {
*aResult = nsnull;
return rv;
}
rv = inst->QueryInterface(aIID, aResult);
if (NS_FAILED(rv)) {
*aResult = nsnull;
}
NS_RELEASE(inst); /* get rid of extra refcnt */
return rv;
}
static NS_IMETHODIMP
CreateNewFTPDirListingConv(nsISupports* aOuter, REFNSIID aIID, void **aResult)
{
if (!aResult) {
return NS_ERROR_INVALID_POINTER;
}
if (aOuter) {
*aResult = nsnull;
return NS_ERROR_NO_AGGREGATION;
}
nsFTPDirListingConv* inst = nsnull;
nsresult rv = NS_NewFTPDirListingConv(&inst);
if (NS_FAILED(rv)) {
*aResult = nsnull;
return rv;
}
rv = inst->QueryInterface(aIID, aResult);
if (NS_FAILED(rv)) {
*aResult = nsnull;
}
NS_RELEASE(inst); /* get rid of extra refcnt */
return rv;
}
static NS_IMETHODIMP
CreateNewMultiMixedConvFactory(nsISupports* aOuter, REFNSIID aIID, void **aResult)
{
if (!aResult) {
return NS_ERROR_INVALID_POINTER;
}
if (aOuter) {
*aResult = nsnull;
return NS_ERROR_NO_AGGREGATION;
}
nsMultiMixedConv* inst = nsnull;
nsresult rv = NS_NewMultiMixedConv(&inst);
if (NS_FAILED(rv)) {
*aResult = nsnull;
return rv;
}
rv = inst->QueryInterface(aIID, aResult);
if (NS_FAILED(rv)) {
*aResult = nsnull;
}
NS_RELEASE(inst); /* get rid of extra refcnt */
return rv;
}
static NS_IMETHODIMP
CreateNewTXTToHTMLConvFactory(nsISupports* aOuter, REFNSIID aIID, void **aResult)
{
if (!aResult) {
return NS_ERROR_INVALID_POINTER;
}
if (aOuter) {
*aResult = nsnull;
return NS_ERROR_NO_AGGREGATION;
}
mozTXTToHTMLConv* inst = nsnull;
nsresult rv = MOZ_NewTXTToHTMLConv(&inst);
if (NS_FAILED(rv)) {
*aResult = nsnull;
return rv;
}
rv = inst->QueryInterface(aIID, aResult);
if (NS_FAILED(rv)) {
*aResult = nsnull;
}
NS_RELEASE(inst); /* get rid of extra refcnt */
return rv;
}
static NS_IMETHODIMP
CreateNewHTTPChunkConvFactory (nsISupports* aOuter, REFNSIID aIID, void **aResult)
{
if (!aResult) {
return NS_ERROR_INVALID_POINTER;
}
if (aOuter) {
*aResult = nsnull;
return NS_ERROR_NO_AGGREGATION;
}
nsHTTPChunkConv* inst = nsnull;
nsresult rv = NS_NewHTTPChunkConv (&inst);
if (NS_FAILED(rv)) {
*aResult = nsnull;
return rv;
}
rv = inst->QueryInterface(aIID, aResult);
if (NS_FAILED(rv)) {
*aResult = nsnull;
}
NS_RELEASE(inst); /* get rid of extra refcnt */
return rv;
}
static NS_IMETHODIMP
CreateNewHTTPCompressConvFactory (nsISupports* aOuter, REFNSIID aIID, void **aResult)
{
if (!aResult) {
return NS_ERROR_INVALID_POINTER;
}
if (aOuter) {
*aResult = nsnull;
return NS_ERROR_NO_AGGREGATION;
}
nsHTTPCompressConv* inst = nsnull;
nsresult rv = NS_NewHTTPCompressConv (&inst);
if (NS_FAILED(rv)) {
*aResult = nsnull;
return rv;
}
rv = inst->QueryInterface(aIID, aResult);
if (NS_FAILED(rv)) {
*aResult = nsnull;
}
NS_RELEASE(inst); /* get rid of extra refcnt */
return rv;
}
static NS_IMETHODIMP
CreateNewUnknownDecoderFactory(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
nsresult rv;
if (!aResult) {
return NS_ERROR_NULL_POINTER;
}
*aResult = nsnull;
if (aOuter) {
return NS_ERROR_NO_AGGREGATION;
}
nsUnknownDecoder *inst;
inst = new nsUnknownDecoder();
if (!inst) {
return NS_ERROR_OUT_OF_MEMORY;
}
NS_ADDREF(inst);
rv = inst->QueryInterface(aIID, aResult);
NS_RELEASE(inst);
return rv;
}
static NS_IMETHODIMP
CreateNewNSTXTToHTMLConvFactory(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
nsresult rv;
if (!aResult) {
return NS_ERROR_NULL_POINTER;
}
*aResult = nsnull;
if (aOuter) {
return NS_ERROR_NO_AGGREGATION;
}
nsTXTToHTMLConv *inst;
inst = new nsTXTToHTMLConv();
if (!inst) return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(inst);
rv = inst->Init();
if (NS_FAILED(rv)) {
delete inst;
return rv;
}
rv = inst->QueryInterface(aIID, aResult);
NS_RELEASE(inst);
return rv;
}
///////////////////////////////////////////////////////////////////////////////
// Module implementation for the net library
// Necko module shutdown hook
static void PR_CALLBACK nsNeckoShutdown(nsIModule *neckoModule)
{
// Release the url parser that the stdurl is holding.
nsStdURL::ShutdownGlobalObjects();
}
static nsModuleComponentInfo gNetModuleInfo[] = {
{ "I/O Service",
NS_IOSERVICE_CID,
"@mozilla.org/network/io-service;1",
nsIOService::Create },
{ "File Transport Service",
NS_FILETRANSPORTSERVICE_CID,
"@mozilla.org/network/file-transport-service;1",
nsFileTransportService::Create },
{ "Socket Transport Service",
NS_SOCKETTRANSPORTSERVICE_CID,
"@mozilla.org/network/socket-transport-service;1",
nsSocketTransportService::Create },
{ "Socket Provider Service",
NS_SOCKETPROVIDERSERVICE_CID,
"@mozilla.org/network/socket-provider-service;1",
nsSocketProviderService::Create },
{ "DNS Service",
NS_DNSSERVICE_CID,
"@mozilla.org/network/dns-service;1",
nsDNSService::Create },
{ "Standard URL Implementation",
NS_STANDARDURL_CID,
"@mozilla.org/network/standard-url;1",
nsStdURL::Create },
{ "Simple URI Implementation",
NS_SIMPLEURI_CID,
"@mozilla.org/network/simple-uri;1",
nsSimpleURI::Create },
{ "External Module Manager",
NS_NETMODULEMGR_CID,
"@mozilla.org/network/net-extern-mod;1",
nsNetModuleMgr::Create },
{ NS_FILEIO_CLASSNAME,
NS_FILEIO_CID,
NS_FILEIO_CONTRACTID,
nsFileIO::Create },
{ NS_INPUTSTREAMIO_CLASSNAME,
NS_INPUTSTREAMIO_CID,
NS_INPUTSTREAMIO_CONTRACTID,
nsInputStreamIO::Create },
{ NS_STREAMIOCHANNEL_CLASSNAME,
NS_STREAMIOCHANNEL_CID,
NS_STREAMIOCHANNEL_CONTRACTID,
nsStreamIOChannel::Create },
{ "Unichar Stream Loader",
NS_STREAMLOADER_CID,
"@mozilla.org/network/stream-loader;1",
nsStreamLoader::Create },
{ "Stream-As-File Downloader",
NS_DOWNLOADER_CID,
"@mozilla.org/network/downloader;1",
nsDownloader::Create },
{ NS_STREAMOBSERVERPROXY_CLASSNAME,
NS_STREAMOBSERVERPROXY_CID,
NS_STREAMOBSERVERPROXY_CONTRACTID,
nsStreamObserverProxyConstructor },
{ NS_STREAMLISTENERPROXY_CLASSNAME,
NS_STREAMLISTENERPROXY_CID,
NS_STREAMLISTENERPROXY_CONTRACTID,
nsStreamListenerProxyConstructor },
{ NS_STREAMPROVIDERPROXY_CLASSNAME,
NS_STREAMPROVIDERPROXY_CID,
NS_STREAMPROVIDERPROXY_CONTRACTID,
nsStreamProviderProxyConstructor },
{ NS_SIMPLESTREAMLISTENER_CLASSNAME,
NS_SIMPLESTREAMLISTENER_CID,
NS_SIMPLESTREAMLISTENER_CONTRACTID,
nsSimpleStreamListenerConstructor },
{ NS_SIMPLESTREAMPROVIDER_CLASSNAME,
NS_SIMPLESTREAMPROVIDER_CID,
NS_SIMPLESTREAMPROVIDER_CONTRACTID,
nsSimpleStreamProviderConstructor },
{ "Async Stream Observer",
NS_ASYNCSTREAMOBSERVER_CID,
"@mozilla.org/network/async-stream-observer;1",
nsAsyncStreamObserver::Create },
{ "Async Stream Listener",
NS_ASYNCSTREAMLISTENER_CID,
"@mozilla.org/network/async-stream-listener;1",
nsAsyncStreamListener::Create },
{ NS_STORAGETRANSPORT_CLASSNAME,
NS_STORAGETRANSPORT_CID,
NS_STORAGETRANSPORT_CONTRACTID,
nsStorageTransportConstructor },
/*
{ "Sync Stream Listener",
NS_SYNCSTREAMLISTENER_CID,
"@mozilla.org/network/sync-stream-listener;1",
nsSyncStreamListener::Create },
*/
{ "Load Group",
NS_LOADGROUP_CID,
"@mozilla.org/network/load-group;1",
nsLoadGroup::Create },
{ NS_LOCALFILEINPUTSTREAM_CLASSNAME,
NS_LOCALFILEINPUTSTREAM_CID,
NS_LOCALFILEINPUTSTREAM_CONTRACTID,
nsFileInputStream::Create },
{ NS_LOCALFILEOUTPUTSTREAM_CLASSNAME,
NS_LOCALFILEOUTPUTSTREAM_CID,
NS_LOCALFILEOUTPUTSTREAM_CONTRACTID,
nsFileOutputStream::Create },
{ "StdURLParser",
NS_STANDARDURLPARSER_CID,
"@mozilla.org/network/standard-urlparser;1",
nsStdURLParser::Create },
{ "AuthURLParser",
NS_AUTHORITYURLPARSER_CID,
"@mozilla.org/network/authority-urlparser;1",
nsAuthURLParser::Create },
{ "NoAuthURLParser",
NS_NOAUTHORITYURLPARSER_CID,
"@mozilla.org/network/no-authority-urlparser;1",
nsNoAuthURLParser::Create },
{ NS_BUFFEREDINPUTSTREAM_CLASSNAME,
NS_BUFFEREDINPUTSTREAM_CID,
NS_BUFFEREDINPUTSTREAM_CONTRACTID,
nsBufferedInputStream::Create },
{ NS_BUFFEREDOUTPUTSTREAM_CLASSNAME,
NS_BUFFEREDOUTPUTSTREAM_CID,
NS_BUFFEREDOUTPUTSTREAM_CONTRACTID,
nsBufferedOutputStream::Create },
{ "Protocol Proxy Service",
NS_PROTOCOLPROXYSERVICE_CID,
"@mozilla.org/network/protocol-proxy-service;1",
nsProtocolProxyService::Create },
// from netwerk/streamconv:
// this converter is "always" part of a build.
// HACK-ALERT, register *all* converters
// in this converters component manager
// registration. just piggy backing here until
// you can add registration functions to
// the generic module macro.
{ "Stream Converter Service",
NS_STREAMCONVERTERSERVICE_CID,
"@mozilla.org/streamConverters;1",
CreateNewStreamConvServiceFactory,
RegisterStreamConverters, // registers *all* converters
UnregisterStreamConverters // unregisters *all* converters
},
// from netwerk/streamconv/converters:
{ "FTPDirListingConverter",
NS_FTPDIRLISTINGCONVERTER_CID,
NS_ISTREAMCONVERTER_KEY FTP_UNIX_TO_INDEX,
CreateNewFTPDirListingConv
},
{ "FTPDirListingConverter",
NS_FTPDIRLISTINGCONVERTER_CID,
NS_ISTREAMCONVERTER_KEY FTP_NT_TO_INDEX,
CreateNewFTPDirListingConv
},
{ "MultiMixedConverter",
NS_MULTIMIXEDCONVERTER_CID,
NS_ISTREAMCONVERTER_KEY MULTI_MIXED_X,
CreateNewMultiMixedConvFactory
},
{ "MultiMixedConverter2",
NS_MULTIMIXEDCONVERTER_CID,
NS_ISTREAMCONVERTER_KEY MULTI_MIXED,
CreateNewMultiMixedConvFactory
},
{ "Unknown Content-Type Decoder",
NS_UNKNOWNDECODER_CID,
NS_ISTREAMCONVERTER_KEY UNKNOWN_CONTENT,
CreateNewUnknownDecoderFactory
},
{ "HttpChunkConverter",
NS_HTTPCHUNKCONVERTER_CID,
NS_ISTREAMCONVERTER_KEY CHUNKED_TO_UNCHUNKED,
CreateNewHTTPChunkConvFactory
},
{ "HttpChunkConverter",
NS_HTTPCHUNKCONVERTER_CID,
NS_ISTREAMCONVERTER_KEY UNCHUNKED_TO_CHUNKED,
CreateNewHTTPChunkConvFactory
},
{ "HttpCompressConverter",
NS_HTTPCOMPRESSCONVERTER_CID,
NS_ISTREAMCONVERTER_KEY GZIP_TO_UNCOMPRESSED,
CreateNewHTTPCompressConvFactory
},
{ "HttpCompressConverter",
NS_HTTPCOMPRESSCONVERTER_CID,
NS_ISTREAMCONVERTER_KEY XGZIP_TO_UNCOMPRESSED,
CreateNewHTTPCompressConvFactory
},
{ "HttpCompressConverter",
NS_HTTPCOMPRESSCONVERTER_CID,
NS_ISTREAMCONVERTER_KEY COMPRESS_TO_UNCOMPRESSED,
CreateNewHTTPCompressConvFactory
},
{ "HttpCompressConverter",
NS_HTTPCOMPRESSCONVERTER_CID,
NS_ISTREAMCONVERTER_KEY XCOMPRESS_TO_UNCOMPRESSED,
CreateNewHTTPCompressConvFactory
},
{ "HttpCompressConverter",
NS_HTTPCOMPRESSCONVERTER_CID,
NS_ISTREAMCONVERTER_KEY DEFLATE_TO_UNCOMPRESSED,
CreateNewHTTPCompressConvFactory
},
{ "NSTXTToHTMLConverter",
NS_NSTXTTOHTMLCONVERTER_CID,
NS_ISTREAMCONVERTER_KEY PLAIN_TO_HTML,
CreateNewNSTXTToHTMLConvFactory
},
// This is not a real stream converter, it's just
// registering it's cid factory here.
{ "HACK-TXTToHTMLConverter",
MOZITXTTOHTMLCONV_CID,
NS_ISTREAMCONVERTER_KEY,
CreateNewTXTToHTMLConvFactory
},
// from netwerk/cache:
{ "Memory Cache", NS_MEM_CACHE_FACTORY_CID, NS_NETWORK_MEMORY_CACHE_CONTRACTID, nsMemCacheConstructor },
{ "File Cache", NS_NETDISKCACHE_CID, NS_NETWORK_FILE_CACHE_CONTRACTID, nsNetDiskCacheConstructor },
{ "Cache Manager",NS_CACHE_MANAGER_CID, NS_NETWORK_CACHE_MANAGER_CONTRACTID,nsCacheManagerConstructor },
// from netwerk/mime:
{ "The MIME mapping service",
NS_MIMESERVICE_CID,
"@mozilla.org/mimeold;1",
nsMIMEService::Create
},
{ "xml mime datasource",
NS_XMLMIMEDATASOURCE_CID,
NS_XMLMIMEDATASOURCE_CONTRACTID,
nsXMLMIMEDataSource::Create
},
{ "xml mime INFO",
NS_MIMEINFO_CID,
NS_MIMEINFO_CONTRACTID,
nsMIMEInfoImplConstructor
},
// from netwerk/protocol/file:
{ "File Protocol Handler",
NS_FILEPROTOCOLHANDLER_CID,
NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "file",
nsFileProtocolHandler::Create
},
{ NS_LOCALFILECHANNEL_CLASSNAME,
NS_LOCALFILECHANNEL_CID,
NS_LOCALFILECHANNEL_CONTRACTID,
nsFileChannel::Create
},
// from netwerk/protocol/http:
{ "HTTP Handler",
NS_IHTTPHANDLER_CID,
NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "http",
nsHTTPHandlerConstructor },
{ "HTTPS Handler",
NS_HTTPS_HANDLER_FACTORY_CID,
NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "https",
nsHTTPSHandler::Create },
{ "Basic Auth Encoder",
NS_BASICAUTH_CID,
NS_BASICAUTH_CONTRACTID,
nsBasicAuthConstructor,
RegisterBasicAuth,
UnregisterBasicAuth
},
// from netwerk/protocol/data:
{ "Data Protocol Handler",
NS_DATAHANDLER_CID,
NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "data",
nsDataHandler::Create},
// from netwerk/protocol/jar:
{ "JAR Protocol Handler",
NS_JARPROTOCOLHANDLER_CID,
NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "jar",
nsJARProtocolHandler::Create
},
// from netwerk/protocol/res:
{ "The Resource Protocol Handler",
NS_RESPROTOCOLHANDLER_CID,
NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "resource",
nsResProtocolHandler::Create
},
// from netwerk/protocol/about:
{ "About Protocol Handler",
NS_ABOUTPROTOCOLHANDLER_CID,
NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "about",
nsAboutProtocolHandler::Create
},
{ "about:blank",
NS_ABOUT_BLANK_MODULE_CID,
NS_ABOUT_MODULE_CONTRACTID_PREFIX "blank",
nsAboutBlank::Create
},
{ "about:bloat",
NS_ABOUT_BLOAT_MODULE_CID,
NS_ABOUT_MODULE_CONTRACTID_PREFIX "bloat",
nsAboutBloat::Create
},
{ "about:credits",
NS_ABOUT_CREDITS_MODULE_CID,
NS_ABOUT_MODULE_CONTRACTID_PREFIX "credits",
nsAboutCredits::Create
},
{ "about:plugins",
NS_ABOUT_PLUGINS_MODULE_CID,
NS_ABOUT_MODULE_CONTRACTID_PREFIX "plugins",
nsAboutPlugins::Create
},
{ "about:mozilla",
MZ_ABOUT_MOZILLA_MODULE_CID,
NS_ABOUT_MODULE_CONTRACTID_PREFIX "mozilla",
mzAboutMozilla::Create
},
{ "about:cache",
NS_ABOUT_CACHE_MODULE_CID,
NS_ABOUT_MODULE_CONTRACTID_PREFIX "cache",
nsAboutCache::Create
},
// from netwerk/protocol/keyword:
{ "The Keyword Protocol Handler",
NS_KEYWORDPROTOCOLHANDLER_CID,
NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "keyword",
nsKeywordProtocolHandler::Create
},
{ NS_ISOCKSSOCKETPROVIDER_CLASSNAME,
NS_SOCKSSOCKETPROVIDER_CID,
NS_ISOCKSSOCKETPROVIDER_CONTRACTID,
nsSOCKSSocketProvider::Create
}
};
NS_IMPL_NSGETMODULE_WITH_DTOR("necko core and primary protocols", gNetModuleInfo,
nsNeckoShutdown)

View File

@@ -1,36 +0,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):
#
DEPTH = ../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
DIRS = public src converters
ifdef ENABLE_TESTS
DIRS += test
endif
include $(topsrcdir)/config/rules.mk

View File

@@ -1,53 +0,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):
#
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = necko
LIBRARY_NAME = nkcnvts_s
REQUIRES = xpcom string mime locale util pref js
EXPORTS = \
nsHTTPChunkConv.h \
$(NULL)
CPPSRCS = \
nsMultiMixedConv.cpp \
nsFTPDirListingConv.cpp \
mozTXTToHTMLConv.cpp \
nsUnknownDecoder.cpp \
nsHTTPChunkConv.cpp \
nsHTTPCompressConv.cpp \
nsTXTToHTMLConv.cpp \
$(NULL)
# we don't want the shared lib, but we want to force the creation of a
# static lib.
override NO_SHARED_LIB=1
override NO_STATIC_LIB=
include $(topsrcdir)/config/rules.mk

View File

@@ -1,50 +0,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):
DEPTH = ..\..\..
include <$(DEPTH)/config/config.mak>
MODULE = necko
LIBRARY_NAME=nkcnvts_s
LCFLAGS = -DWIN32_LEAN_AND_MEAN -D_IMPL_NS_NET
# Add this for performance TXT-HTML performance #'s: -DMOZ_PERF_METRICS
EXPORTS = \
nsHTTPChunkConv.h \
$(NULL)
CPP_OBJS = \
.\$(OBJDIR)\nsMultiMixedConv.obj \
.\$(OBJDIR)\nsFTPDirListingConv.obj \
.\$(OBJDIR)\mozTXTToHTMLConv.obj \
.\$(OBJDIR)\nsHTTPChunkConv.obj \
.\$(OBJDIR)\nsHTTPCompressConv.obj \
.\$(OBJDIR)\nsUnknownDecoder.obj \
.\$(OBJDIR)\nsTXTToHTMLConv.obj \
$(NULL)
include <$(DEPTH)\config\rules.mak>
install:: $(LIBRARY)
$(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib
clobber::
$(RM) $(DIST)\lib\$(LIBRARY_NAME).lib

File diff suppressed because it is too large Load Diff

View File

@@ -1,325 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The "License" shall be the Mozilla Public License Version 1.1, except
* Sections 6.2 and 11, but with the addition of the below defined Section 14.
* You may obtain a copy of the Mozilla Public License Version 1.1 at
* <http://www.mozilla.org/MPL/>. The contents of this file are subject to the
* License; you may not use this file except in compliance with the License.
*
* Section 14: MISCELLANEOUS.
* This License represents the complete agreement concerning subject matter
* hereof. If any provision of this License is held to be unenforceable, such
* provision shall be reformed only to the extent necessary to make it
* enforceable. This License shall be governed by German law provisions. Any
* litigation relating to this License shall be subject to German jurisdiction.
*
* Once Covered Code has been published under a particular version of the
* License, You may always continue to use it under the terms of that version.
+ The Initial Developer and no one else has the right to modify the terms
* applicable to Covered Code created under this License.
* (End of Section 14)
*
* 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 the Mozilla Text to HTML converter code.
*
* The Initial Developer of the Original Code is Ben Bucksch
* <http://www.bucksch.org>. Portions created by Ben Bucksch are Copyright
* (C) 1999, 2000 Ben Bucksch. All Rights Reserved.
*
* Contributor(s):
*/
/**
Description: Currently only functions to enhance plain text with HTML tags. See mozITXTToHTMLConv. Stream conversion is defunct.
*/
#ifndef _mozTXTToHTMLConv_h__
#define _mozTXTToHTMLConv_h__
#include "mozITXTToHTMLConv.h"
#include "nsIIOService.h"
#include "nsString.h"
#include "nsTimer.h"
#include "nsCOMPtr.h"
static NS_DEFINE_CID(kTXTToHTMLConvCID, MOZITXTTOHTMLCONV_CID);
class mozTXTToHTMLConv : public mozITXTToHTMLConv
{
//////////////////////////////////////////////////////////
public:
//////////////////////////////////////////////////////////
mozTXTToHTMLConv();
virtual ~mozTXTToHTMLConv();
NS_DECL_ISUPPORTS
static const nsIID& GetIID(void)
{ static nsIID iid = MOZITXTTOHTMLCONV_IID; return iid; }
NS_DECL_MOZITXTTOHTMLCONV
NS_DECL_NSISTREAMOBSERVER
NS_DECL_NSISTREAMLISTENER
NS_DECL_NSISTREAMCONVERTER
/**
see mozITXTToHTMLConv::ScanTXT
*/
void ScanTXT(const PRUnichar * aInString, PRInt32 aInStringLength, PRUint32 whattodo, nsString& aOutString);
/**
see mozITXTToHTMLConv::ScanHTML. We will modify aInString potentially...
*/
void ScanHTML(nsString& aInString, PRUint32 whattodo, nsString &aOutString);
/**
see mozITXTToHTMLConv::CiteLevelTXT
*/
PRInt32 CiteLevelTXT(const PRUnichar * line,PRUint32& logLineStart);
// Timing!
MOZ_TIMER_DECLARE(mScanTXTTimer)
MOZ_TIMER_DECLARE(mGlyphHitTimer)
MOZ_TIMER_DECLARE(mTotalMimeTime)
//////////////////////////////////////////////////////////
protected:
//////////////////////////////////////////////////////////
nsCOMPtr<nsIIOService> mIOService; // for performance reasons, cache the netwerk service...
/**
Completes<ul>
<li>Case 1: mailto: "mozilla@bucksch.org" -> "mailto:mozilla@bucksch.org"
<li>Case 2: http: "www.mozilla.org" -> "http://www.mozilla.org"
<li>Case 3: ftp: "ftp.mozilla.org" -> "ftp://www.mozilla.org"
</ul>
It does no check, if the resulting URL is valid.
@param text (in): abbreviated URL
@param pos (in): position of "@" (case 1) or first "." (case 2 and 3)
@return Completed URL at success and empty string at failure
*/
void CompleteAbbreviatedURL(const PRUnichar * aInString, PRInt32 aInLength,
const PRUint32 pos, nsString& aOutString);
//////////////////////////////////////////////////////////
private:
//////////////////////////////////////////////////////////
enum LIMTYPE
{
LT_IGNORE, // limitation not checked
LT_DELIMITER, // not alphanumeric and not rep[0]. End of text is also ok.
LT_ALPHA, // alpha char
LT_DIGIT
};
/**
@param text (in): the string to search through.<p>
If before = IGNORE,<br>
rep is compared starting at 1. char of text (text[0]),<br>
else starting at 2. char of text (text[1]).
Chars after "after"-delimiter are ignored.
@param rep (in): the string to look for
@param aRepLen (in): the number of bytes in the string to look for
@param before (in): limitation before rep
@param after (in): limitation after rep
@return true, if rep is found and limitation spec is met or rep is empty
*/
PRBool ItMatchesDelimited(const PRUnichar * aInString, PRInt32 aInLength,
const char* rep, PRInt32 aRepLen, LIMTYPE before, LIMTYPE after);
/**
@param see ItMatchesDelimited
@return Number of ItMatchesDelimited in text
*/
PRUint32 NumberOfMatches(const PRUnichar * aInString, PRInt32 aInStringLength,
const char* rep, PRInt32 aRepLen, LIMTYPE before, LIMTYPE after);
/**
Currently only changes "<", ">" and "&". All others stay as they are.<p>
"Char" in function name to avoid side effects with nsString(ch)
constructors.
@param ch (in)
@param aStringToAppendto (out) - the string to append the escaped
string to.
*/
void EscapeChar(const PRUnichar ch, nsString& aStringToAppendto);
/**
See EscapeChar. Escapes the string in place.
*/
void EscapeStr(nsString& aInString);
/**
Currently only reverts "<", ">" and "&". All others stay as they are.<p>
@param aInString (in) HTML string
@param aStartPos (in) start index into the buffer
@param aLength (in) length of the buffer
@param aOutString (out) unescaped buffer
*/
void UnescapeStr(const PRUnichar * aInString, PRInt32 aStartPos, PRInt32 aLength, nsString& aOutString);
/**
<em>Note</em>: I use different strategies to pass context between the
functions (full text and pos vs. cutted text and col0, glphyTextLen vs.
replaceBefore/-After). It makes some sense, but is hard to understand
(maintain) :-(.
*/
/**
<p><em>Note:</em> replaceBefore + replaceAfter + 1 (for char at pos) chars
in text should be replaced by outputHTML.</p>
<p><em>Note:</em> This function should be able to process a URL on multiple
lines, but currently, ScanForURLs is called for every line, so it can't.</p>
@param text (in): includes possibly a URL
@param pos (in): position in text, where either ":", "." or "@" are found
@param whathasbeendone (in): What the calling ScanTXT did/has to do with the
(not-linkified) text, i.e. usually the "whattodo" parameter.
(Needed to calculate replaceBefore.) NOT what will be done with
the content of the link.
@param outputHTML (out): URL with HTML-a tag
@param replaceBefore (out): Number of chars of URL before pos
@param replaceAfter (out): Number of chars of URL after pos
@return URL found
*/
PRBool FindURL(const PRUnichar * aInString, PRInt32 aInLength, const PRUint32 pos,
const PRUint32 whathasbeendone,
nsString& outputHTML, PRInt32& replaceBefore, PRInt32& replaceAfter);
enum modetype {
unknown,
RFC1738, /* Check, if RFC1738, APPENDIX compliant,
like "<URL:http://www.mozilla.org>". */
RFC2396E, /* RFC2396, APPENDIX E allows anglebrackets (like
"<http://www.mozilla.org>") (without "URL:") or
quotation marks(like ""http://www.mozilla.org"").
Also allow email addresses without scheme,
e.g. "<mozilla@bucksch.org>" */
freetext, /* assume heading scheme
with "[a-zA-Z][a-zA-Z0-9+\-\.]*:" like "news:"
(see RFC2396, Section 3.1).
Certain characters (see code) or any whitespace
(including linebreaks) end the URL.
Other certain (punctation) characters (see code)
at the end are stripped off. */
abbreviated /* Similar to freetext, but without scheme, e.g.
"www.mozilla.org", "ftp.mozilla.org" and
"mozilla@bucksch.org". */
/* RFC1738 and RFC2396E type URLs may use multiple lines,
whitespace is stripped. Special characters like ")" stay intact.*/
};
/**
* @param text (in), pos (in): see FindURL
* @param check (in): Start must be conform with this mode
* @param start (out): Position in text, where URL (including brackets or
* similar) starts
* @return |check|-conform start has been found
*/
PRBool FindURLStart(const PRUnichar * aInString, PRInt32 aInLength, const PRUint32 pos,
const modetype check, PRUint32& start);
/**
* @param text (in), pos (in): see FindURL
* @param check (in): End must be conform with this mode
* @param start (in): see FindURLStart
* @param end (out): Similar to |start| param of FindURLStart
* @return |check|-conform end has been found
*/
PRBool FindURLEnd(const PRUnichar * aInString, PRInt32 aInStringLength, const PRUint32 pos,
const modetype check, const PRUint32 start, PRUint32& end);
/**
* @param text (in), pos (in), whathasbeendone (in): see FindURL
* @param check (in): Current mode
* @param start (in), end (in): see FindURLEnd
* @param txtURL (out): Guessed (raw) URL.
* Without whitespace, but not completed.
* @param desc (out): Link as shown to the user, but already escaped.
* Should be placed between the <a> and </a> tags.
* @param replaceBefore(out), replaceAfter (out): see FindURL
*/
void CalculateURLBoundaries(const PRUnichar * aInString, PRInt32 aInStringLength,
const PRUint32 pos, const PRUint32 whathasbeendone,
const modetype check, const PRUint32 start, const PRUint32 end,
nsString& txtURL, nsString& desc,
PRInt32& replaceBefore, PRInt32& replaceAfter);
/**
* @param txtURL (in), desc (in): see CalculateURLBoundaries
* @param outputHTML (out): see FindURL
* @return A valid URL could be found (and creation of HTML successful)
*/
PRBool CheckURLAndCreateHTML(
const nsString& txtURL, const nsString& desc, const modetype mode,
nsString& outputHTML);
/**
@param text (in): line of text possibly with tagTXT.<p>
if col0 is true,
starting with tagTXT<br>
else
starting one char before tagTXT
@param col0 (in): tagTXT is on the beginning of the line (or paragraph).
open must be 0 then.
@param tagTXT (in): Tag in plaintext to search for, e.g. "*"
@param aTagTxtLen (in): length of tagTXT.
@param tagHTML (in): HTML-Tag to replace tagTXT with,
without "<" and ">", e.g. "strong"
@param attributeHTML (in): HTML-attribute to add to opening tagHTML,
e.g. "class=txt_star"
@param aOutString: string to APPEND the converted html into
@param open (in/out): Number of currently open tags of type tagHTML
@return Conversion succeeded
*/
PRBool StructPhraseHit(const PRUnichar * aInString, PRInt32 aInStringLength, PRBool col0,
const char* tagTXT,
PRInt32 aTagTxtLen,
const char* tagHTML, const char* attributeHTML,
nsString& aOutputString, PRUint32& openTags);
/**
@param text (in), col0 (in): see GlyphHit
@param tagTXT (in): Smily, see also StructPhraseHit
@param aTagTxtLen (in): length of tagTXT
@param tagHTML (in): see StructPhraseHit
@param outputHTML (out): new string containing the html for the smily
@param glyphTextLen (out): see GlyphHit
*/
PRBool SmilyHit(const PRUnichar * aInString, PRInt32 aLength, PRBool col0,
const char* tagTXT, PRInt32 aTagTxtLen, const char* tagHTML,
nsString& outputHTML, PRInt32& glyphTextLen);
/**
Checks, if we can replace some chars at the start of line with prettier HTML
code.<p>
If success is reported, replace the first glyphTextLen chars with outputHTML
@param text (in): line of text possibly with Glyph.<p>
If col0 is true,
starting with Glyph <br><!-- (br not part of text) -->
else
starting one char before Glyph
@param col0 (in): text starts at the beginning of the line (or paragraph)
@param aOutString (out): APPENDS html for the glyph to this string
@param glyphTextLen (out): Length of original text to replace
@return see StructPhraseHit
*/
PRBool GlyphHit(const PRUnichar * aInString, PRInt32 aInLength, PRBool col0,
nsString& aOutString, PRInt32& glyphTextLen);
};
// It's said, that Win32 and Mac don't like static const members
const PRInt32 mozTXTToHTMLConv_lastMode = 4;
// Needed (only) by mozTXTToHTMLConv::FindURL
const PRInt32 mozTXTToHTMLConv_numberOfModes = 4; // dito; unknown not counted
#endif

View File

@@ -1,237 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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):
*/
#include "nsCOMPtr.h"
#include "nsIModule.h"
#include "nsIGenericFactory.h"
#include "nsICategoryManager.h"
#include "nsFTPDirListingConv.h"
#include "nsMultiMixedConv.h"
#include "nsHTTPChunkConv.h"
#include "nsHTTPCompressConv.h"
#include "mozTXTToHTMLConv.h"
#include "nsUnknownDecoder.h"
#include "nsTXTToHTMLConv.h"
nsresult NS_NewFTPDirListingConv(nsFTPDirListingConv** result);
nsresult NS_NewMultiMixedConv (nsMultiMixedConv** result);
nsresult MOZ_NewTXTToHTMLConv (mozTXTToHTMLConv** result);
nsresult NS_NewHTTPChunkConv (nsHTTPChunkConv ** result);
nsresult NS_NewHTTPCompressConv (nsHTTPCompressConv ** result);
nsresult NS_NewNSTXTToHTMLConv(nsTXTToHTMLConv** result);
static NS_IMETHODIMP
CreateNewFTPDirListingConv(nsISupports* aOuter, REFNSIID aIID, void **aResult)
{
if (!aResult) {
return NS_ERROR_INVALID_POINTER;
}
if (aOuter) {
*aResult = nsnull;
return NS_ERROR_NO_AGGREGATION;
}
nsFTPDirListingConv* inst = nsnull;
nsresult rv = NS_NewFTPDirListingConv(&inst);
if (NS_FAILED(rv)) {
*aResult = nsnull;
return rv;
}
rv = inst->QueryInterface(aIID, aResult);
if (NS_FAILED(rv)) {
*aResult = nsnull;
}
NS_RELEASE(inst); /* get rid of extra refcnt */
return rv;
}
static NS_IMETHODIMP
CreateNewMultiMixedConvFactory(nsISupports* aOuter, REFNSIID aIID, void **aResult)
{
if (!aResult) {
return NS_ERROR_INVALID_POINTER;
}
if (aOuter) {
*aResult = nsnull;
return NS_ERROR_NO_AGGREGATION;
}
nsMultiMixedConv* inst = nsnull;
nsresult rv = NS_NewMultiMixedConv(&inst);
if (NS_FAILED(rv)) {
*aResult = nsnull;
return rv;
}
rv = inst->QueryInterface(aIID, aResult);
if (NS_FAILED(rv)) {
*aResult = nsnull;
}
NS_RELEASE(inst); /* get rid of extra refcnt */
return rv;
}
static NS_IMETHODIMP
CreateNewTXTToHTMLConvFactory(nsISupports* aOuter, REFNSIID aIID, void **aResult)
{
if (!aResult) {
return NS_ERROR_INVALID_POINTER;
}
if (aOuter) {
*aResult = nsnull;
return NS_ERROR_NO_AGGREGATION;
}
mozTXTToHTMLConv* inst = nsnull;
nsresult rv = MOZ_NewTXTToHTMLConv(&inst);
if (NS_FAILED(rv)) {
*aResult = nsnull;
return rv;
}
rv = inst->QueryInterface(aIID, aResult);
if (NS_FAILED(rv)) {
*aResult = nsnull;
}
NS_RELEASE(inst); /* get rid of extra refcnt */
return rv;
}
static NS_IMETHODIMP
CreateNewHTTPChunkConvFactory (nsISupports* aOuter, REFNSIID aIID, void **aResult)
{
if (!aResult) {
return NS_ERROR_INVALID_POINTER;
}
if (aOuter) {
*aResult = nsnull;
return NS_ERROR_NO_AGGREGATION;
}
nsHTTPChunkConv* inst = nsnull;
nsresult rv = NS_NewHTTPChunkConv (&inst);
if (NS_FAILED(rv)) {
*aResult = nsnull;
return rv;
}
rv = inst->QueryInterface(aIID, aResult);
if (NS_FAILED(rv)) {
*aResult = nsnull;
}
NS_RELEASE(inst); /* get rid of extra refcnt */
return rv;
}
static NS_IMETHODIMP
CreateNewHTTPCompressConvFactory (nsISupports* aOuter, REFNSIID aIID, void **aResult)
{
if (!aResult) {
return NS_ERROR_INVALID_POINTER;
}
if (aOuter) {
*aResult = nsnull;
return NS_ERROR_NO_AGGREGATION;
}
nsHTTPCompressConv* inst = nsnull;
nsresult rv = NS_NewHTTPCompressConv (&inst);
if (NS_FAILED(rv)) {
*aResult = nsnull;
return rv;
}
rv = inst->QueryInterface(aIID, aResult);
if (NS_FAILED(rv)) {
*aResult = nsnull;
}
NS_RELEASE(inst); /* get rid of extra refcnt */
return rv;
}
static NS_IMETHODIMP
CreateNewUnknownDecoderFactory(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
nsresult rv;
if (!aResult) {
return NS_ERROR_NULL_POINTER;
}
*aResult = nsnull;
if (aOuter) {
return NS_ERROR_NO_AGGREGATION;
}
nsUnknownDecoder *inst;
inst = new nsUnknownDecoder();
if (!inst) {
return NS_ERROR_OUT_OF_MEMORY;
}
NS_ADDREF(inst);
rv = inst->QueryInterface(aIID, aResult);
NS_RELEASE(inst);
return rv;
}
static NS_IMETHODIMP
CreateNewNSTXTToHTMLConvFactory(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
nsresult rv;
if (!aResult) {
return NS_ERROR_NULL_POINTER;
}
*aResult = nsnull;
if (aOuter) {
return NS_ERROR_NO_AGGREGATION;
}
nsTXTToHTMLConv *inst;
inst = new nsTXTToHTMLConv();
if (!inst) return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(inst);
rv = inst->Init();
if (NS_FAILED(rv)) {
delete inst;
return rv;
}
rv = inst->QueryInterface(aIID, aResult);
NS_RELEASE(inst);
return rv;
}
// The list of components we register
static nsModuleComponentInfo components[] =
{
// This is not a real stream converter, it's just
// registering it's cid factory here.
{ "HACK-TXTToHTMLConverter",
MOZITXTTOHTMLCONV_CID,
NS_ISTREAMCONVERTER_KEY,
CreateNewTXTToHTMLConvFactory
}
};
NS_IMPL_NSGETMODULE("nsConvModule", components);

File diff suppressed because it is too large Load Diff

View File

@@ -1,166 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#ifndef __nsftpdirlistingdconv__h__
#define __nsftpdirlistingdconv__h__
#include "nsIStreamConverter.h"
#include "nsIChannel.h"
#include "nsIURI.h"
#include "nsString.h"
#include "nsILocale.h"
#include "nsIDateTimeFormat.h"
#include "nsIFactory.h"
#define NS_FTPDIRLISTINGCONVERTER_CID \
{ /* 14C0E880-623E-11d3-A178-0050041CAF44 */ \
0x14c0e880, \
0x623e, \
0x11d3, \
{0xa1, 0x78, 0x00, 0x50, 0x04, 0x1c, 0xaf, 0x44} \
}
static NS_DEFINE_CID(kFTPDirListingConverterCID, NS_FTPDIRLISTINGCONVERTER_CID);
// The nsFTPDirListingConv stream converter converts a stream of type "text/ftp-dir-SERVER_TYPE"
// (where SERVER_TYPE is one of the following):
//
// SERVER TYPES:
// generic
// unix
// dcts
// ncsa
// peter_lewis
// machten
// cms
// tcpc
// vms
// nt
// eplf
//
// nsFTPDirListingConv converts the raw ascii text directory generated via a FTP
// LIST or NLST command, to the application/http-index-format MIME-type.
// For more info see: http://www.area.com/~roeber/file_format.html
typedef enum _FTP_Server_Type {
GENERIC,
UNIX,
DCTS,
NCSA,
PETER_LEWIS,
MACHTEN,
CMS,
TCPC,
VMS,
NT,
EPLF
} FTP_Server_Type;
typedef enum _FTPentryType {
Dir,
File,
Link
} FTPentryType;
// indexEntry is the data structure used to maintain directory entry information.
class indexEntry {
public:
indexEntry() { mContentLen = 0; mType = File; mSupressSize = PR_FALSE; };
nsCString mName; // the file or dir name
FTPentryType mType;
PRInt32 mContentLen; // length of the file
nsCString mContentType; // type of the file
PRExplodedTime mMDTM; // modified time
PRBool mSupressSize; // supress the size info from display
};
class nsFTPDirListingConv : public nsIStreamConverter {
public:
// nsISupports methods
NS_DECL_ISUPPORTS
// nsIStreamConverter methods
NS_DECL_NSISTREAMCONVERTER
// nsIStreamListener methods
NS_DECL_NSISTREAMLISTENER
// nsIStreamObserver methods
NS_DECL_NSISTREAMOBSERVER
// nsFTPDirListingConv methods
nsFTPDirListingConv();
virtual ~nsFTPDirListingConv();
nsresult Init();
// For factory creation.
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult) {
nsresult rv;
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsFTPDirListingConv* _s = new nsFTPDirListingConv();
if (_s == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(_s);
rv = _s->Init();
if (NS_FAILED(rv)) {
delete _s;
return rv;
}
rv = _s->QueryInterface(aIID, aResult);
NS_RELEASE(_s);
return rv;
}
private:
// util parsing methods
PRInt8 MonthNumber(const char *aCStr);
PRBool IsLSDate(char *aCStr);
// date conversion/parsing methods
PRBool ConvertUNIXDate(char *aCStr, PRExplodedTime& outDate);
PRBool ConvertDOSDate(char *aCStr, PRExplodedTime& outDate);
// line parsing methods
nsresult ParseLSLine(char *aLine, indexEntry *aEntry);
nsresult ParseVMSLine(char *aLine, indexEntry *aEntry);
void InitPRExplodedTime(PRExplodedTime& aTime);
char* DigestBufferLines(char *aBuffer, nsCAutoString &aString);
// member data
FTP_Server_Type mServerType; // what kind of server is the data coming from?
nsCAutoString mBuffer; // buffered data.
PRBool mSentHeading; // have we sent 100, 101, 200, and 300 lines yet?
nsIStreamListener *mFinalListener; // this guy gets the converted data via his OnDataAvailable()
nsIChannel *mPartChannel; // the channel for the given part we're processing.
// one channel per part.
nsILocale *mLocale; // the application locale for date formating
nsIDateTimeFormat *mDateTimeFormat; // for the actual date time formatting.
};
#endif /* __nsftpdirlistingdconv__h__ */

View File

@@ -1,442 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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): ruslan
*/
#include "nsHTTPChunkConv.h"
#include "nsMemory.h"
#include "plstr.h"
#include "prlog.h"
#include "nsIChannel.h"
#include "nsCOMPtr.h"
#include "nsIByteArrayInputStream.h"
#include "nsIStringStream.h"
#include <ctype.h>
// nsISupports implementation
NS_IMPL_THREADSAFE_ISUPPORTS2 (nsHTTPChunkConv, nsIStreamConverter, nsIStreamListener);
// nsFTPDirListingConv methods
nsHTTPChunkConv::nsHTTPChunkConv()
{
NS_INIT_ISUPPORTS ();
mListener = nsnull;
mChunkBuffer = NULL;
mState = CHUNK_STATE_INIT;
mValueBufLen = 0;
mHeaderBufLen= 0;
mHeadersCount= mHeadersExpected = 0;
mChunkContext= NULL;
}
nsHTTPChunkConv::~nsHTTPChunkConv ()
{
NS_IF_RELEASE(mListener);
if (mChunkBuffer != NULL)
nsMemory::Free (mChunkBuffer);
}
NS_IMETHODIMP
nsHTTPChunkConv::AsyncConvertData (
const PRUnichar *aFromType,
const PRUnichar *aToType,
nsIStreamListener *aListener,
nsISupports *aCtxt)
{
nsString from (aFromType);
nsString to ( aToType );
char * fromStr = from.ToNewCString ();
char * toStr = to.ToNewCString ();
if (!PL_strncasecmp (fromStr, HTTP_CHUNK_TYPE, strlen (HTTP_CHUNK_TYPE ) )
&&
!PL_strncasecmp (toStr, HTTP_UNCHUNK_TYPE, strlen (HTTP_UNCHUNK_TYPE)))
mMode = DO_UNCHUNKING;
else
mMode = DO_CHUNKING;
nsMemory::Free (fromStr);
nsMemory::Free ( toStr);
// hook ourself up with the receiving listener.
mListener = aListener;
NS_ADDREF (mListener);
mAsyncConvContext = (nsISupportsVoid *) aCtxt;
if (mAsyncConvContext)
{
const void *p;
mAsyncConvContext -> GetData (&p);
mChunkContext = (nsHTTPChunkConvContext *)p;
}
return NS_OK;
}
NS_IMETHODIMP
nsHTTPChunkConv::OnStartRequest (nsIRequest* request, nsISupports *aContext)
{
return mListener->OnStartRequest (request, aContext);
}
NS_IMETHODIMP
nsHTTPChunkConv::OnStopRequest(nsIRequest* request, nsISupports *aContext,
nsresult aStatus, const PRUnichar* aStatusArg)
{
return mListener->OnStopRequest(request, aContext, aStatus, aStatusArg);
}
NS_IMETHODIMP
nsHTTPChunkConv::OnDataAvailable (
nsIRequest* request,
nsISupports *aContext,
nsIInputStream *iStr,
PRUint32 aSourceOffset,
PRUint32 aCount)
{
nsresult rv = NS_ERROR_FAILURE;
PRUint32 rl;
PRUint32 streamLen;
char c = 0;
rv = iStr -> Available (&streamLen);
if (NS_FAILED (rv))
return rv;
if (streamLen == 0)
return NS_OK;
if (mMode == DO_CHUNKING)
{
mChunkBuffer = (char * )nsMemory::Alloc (streamLen + 20);
mChunkBufferPos = sprintf (mChunkBuffer, "%x%c%c", streamLen, '\r', '\n');
rv = iStr -> Read (&mChunkBuffer[mChunkBufferPos], streamLen, &rl);
if (NS_FAILED (rv) || rl != streamLen)
return rv;
mChunkBufferPos += streamLen;
mChunkBuffer[mChunkBufferPos++] = '\r';
mChunkBuffer[mChunkBufferPos++] = '\n';
mChunkBuffer[mChunkBufferPos ] = 0;
mChunkBufferLength = mChunkBufferPos;
nsIInputStream * convertedStream = nsnull;
nsIByteArrayInputStream * convertedStreamSup = nsnull;
rv = NS_NewByteArrayInputStream (&convertedStreamSup, mChunkBuffer, mChunkBufferPos);
if (NS_FAILED (rv))
return rv;
mChunkBuffer = NULL;
mChunkBufferPos = 0;
rv = convertedStreamSup -> QueryInterface (NS_GET_IID (nsIInputStream), (void**)&convertedStream);
NS_RELEASE (convertedStreamSup);
if (NS_FAILED (rv))
return rv;
rv = mListener -> OnDataAvailable (request, aContext, convertedStream, aSourceOffset, mChunkBufferLength);
if (NS_FAILED (rv))
return rv;
}
else
{
// DO_UNCHUNKING
while (mState != CHUNK_STATE_DONE)
{
switch (mState)
{
case CHUNK_STATE_INIT:
if (mChunkBuffer != NULL)
{
nsMemory::Free (mChunkBuffer);
mChunkBuffer = NULL;
}
mChunkBufferPos = mChunkBufferLength = 0;
mLenBufCnt = 0;
c = 0;
mState = CHUNK_STATE_LENGTH;
break;
case CHUNK_STATE_FINAL:
// send data upstream
{
if (mChunkBufferLength > 0)
{
mState = CHUNK_STATE_INIT;
nsCOMPtr<nsIByteArrayInputStream> convertedStreamSup;
rv = NS_NewByteArrayInputStream (getter_AddRefs(convertedStreamSup), mChunkBuffer, mChunkBufferLength);
if (NS_FAILED (rv))
return rv;
mChunkBuffer = NULL;
nsCOMPtr<nsIInputStream> convertedStream = do_QueryInterface (convertedStreamSup, &rv);
if (NS_FAILED (rv))
return rv;
rv = mListener -> OnDataAvailable (request, aContext, convertedStream, aSourceOffset, mChunkBufferLength);
if (NS_FAILED (rv))
return rv;
}
else
{
if (mChunkContext)
mChunkContext -> SetEOF (PR_TRUE);
mState = CHUNK_STATE_DONE;
}
if (mChunkBuffer != NULL)
{
nsMemory::Free (mChunkBuffer);
mChunkBuffer = NULL;
}
}
break;
case CHUNK_STATE_CR:
case CHUNK_STATE_CR_FINAL:
if (!streamLen)
return NS_OK;
rv = iStr -> Read (&c, 1, &rl);
if (NS_FAILED (rv))
return rv;
if (c != '\r' && c != '\n') // be really relaxed here cuz of numerous spec violations
return NS_ERROR_FAILURE;
streamLen--;
mState = mState == CHUNK_STATE_CR ? CHUNK_STATE_LF : CHUNK_STATE_LF_FINAL;
break;
case CHUNK_STATE_LF:
case CHUNK_STATE_LF_FINAL:
if (c != '\n')
{
if (!streamLen)
return NS_OK;
rv = iStr -> Read (&c, 1, &rl);
if (NS_FAILED (rv))
return rv;
}
if (c != '\n')
return NS_ERROR_FAILURE;
streamLen--;
if (mState == CHUNK_STATE_LF)
{
if (mChunkBufferLength > 0)
{
mChunkBuffer = (char * )nsMemory::Alloc (mChunkBufferLength + 1);
mState = CHUNK_STATE_DATA;
}
else
mState = CHUNK_STATE_CR_FINAL;
}
else
mState = CHUNK_STATE_TRAILER;
c = 0;
break;
case CHUNK_STATE_LENGTH:
if (mLenBufCnt >= sizeof (mLenBuf) - 1)
return NS_ERROR_FAILURE;
if (!streamLen)
return NS_OK;
rv = iStr -> Read (&c, 1, &rl);
if (NS_FAILED (rv))
return rv;
streamLen--;
if (isxdigit (c))
{
mLenBuf[mLenBufCnt++] = c;
c = 0;
}
else
if (c == '\r' || c == '\n')
{
if (mLenBufCnt > 0)
{
// ruslan: have to add this due to a lot of spec violations
// similating what IE does here
mLenBuf[mLenBufCnt] = 0;
sscanf (mLenBuf, "%x", &mChunkBufferLength);
mState = CHUNK_STATE_LF;
}
}
break;
case CHUNK_STATE_DATA:
if (mChunkBufferLength - mChunkBufferPos <= streamLen)
{
// entire chunk
if (!streamLen)
return NS_OK;
rv = iStr -> Read (&mChunkBuffer[mChunkBufferPos], mChunkBufferLength - mChunkBufferPos, &rl);
if (NS_FAILED (rv))
return rv;
mChunkBufferPos += rl;
mChunkBuffer[mChunkBufferPos++] = 0;
streamLen -= rl;
mState = CHUNK_STATE_CR_FINAL;
}
else
{
if (!streamLen)
return NS_OK;
rv = iStr -> Read (&mChunkBuffer[mChunkBufferPos], streamLen, &rl);
if (NS_FAILED (rv))
return rv;
mChunkBufferPos += rl;
streamLen -= rl;
}
break;
case CHUNK_STATE_TRAILER:
if (!mChunkContext || mHeadersCount == mChunkContext -> GetTrailerHeaderCount ())
mState = CHUNK_STATE_FINAL;
else
mState = CHUNK_STATE_TRAILER_HEADER;
break;
case CHUNK_STATE_TRAILER_HEADER:
if (!streamLen)
return NS_OK;
rv = iStr -> Read (&c, 1, &rl);
if (NS_FAILED (rv))
return rv;
streamLen--;
if (isalnum (c) && mHeaderBufLen < sizeof (mHeaderBuf) - 1)
mHeaderBuf[mHeaderBufLen++] = c;
else
if (c == ':')
{
mHeaderBuf[mHeaderBufLen] = 0;
mState = CHUNK_STATE_TRAILER_VALUE;
}
break;
case CHUNK_STATE_TRAILER_VALUE:
if (!streamLen)
return NS_OK;
rv = iStr -> Read (&c, 1, &rl);
if (NS_FAILED (rv))
return rv;
streamLen--;
if (isspace (c) && mValueBufLen == 0 || c == '\r')
break;
else
if (c == '\n')
{
mValueBuf[mValueBufLen] = 0;
mHeadersCount++;
mChunkContext -> SetResponseHeader (mHeaderBuf, mValueBuf);
mHeaderBufLen = mValueBufLen = 0;
mState = CHUNK_STATE_TRAILER;
}
else
if (mValueBufLen < sizeof (mValueBuf) - 1)
mValueBuf[mValueBufLen++] = c;
break;
} /* switch */
} /* while */
} /* DO_UNCHUNKING */
return NS_OK;
} /* OnDataAvailable */
// XXX/ruslan: need to implement this too
NS_IMETHODIMP
nsHTTPChunkConv::Convert (
nsIInputStream *aFromStream,
const PRUnichar *aFromType,
const PRUnichar *aToType,
nsISupports *aCtxt,
nsIInputStream **_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
nsresult
NS_NewHTTPChunkConv (nsHTTPChunkConv ** aHTTPChunkConv)
{
NS_PRECONDITION(aHTTPChunkConv != nsnull, "null ptr");
if (! aHTTPChunkConv)
return NS_ERROR_NULL_POINTER;
*aHTTPChunkConv = new nsHTTPChunkConv ();
if (! *aHTTPChunkConv)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(*aHTTPChunkConv);
return NS_OK;
}

View File

@@ -1,190 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#if !defined (__nsHTTPChunkConv__h__)
#define __nsHTTPChunkConv__h__ 1
#include "nsIStreamConverter.h"
#include "nsIFactory.h"
#include "nsCOMPtr.h"
#include "nsVoidArray.h"
#include "nsHashtable.h"
#include "nsString.h"
#include "nsISupportsPrimitives.h"
#define NS_HTTPCHUNKCONVERTER_CID \
{ \
/* 95ca98d9-2a96-48d6-a014-0dffa84834a1 */ \
0x95ca98d9, \
0x2a96, \
0x48d6, \
{0xa0, 0x14, 0x0d, 0xff, 0xa8, 0x48, 0x34, 0xa1}\
}
static NS_DEFINE_CID(kHTTPChunkConverterCID, NS_HTTPCHUNKCONVERTER_CID);
typedef enum emum_ChunkMode
{
DO_CHUNKING, DO_UNCHUNKING
} ChunkMode;
typedef enum enum_ChunkState
{
CHUNK_STATE_INIT,
CHUNK_STATE_CR,
CHUNK_STATE_LF,
CHUNK_STATE_LENGTH,
CHUNK_STATE_DATA,
CHUNK_STATE_CR_FINAL,
CHUNK_STATE_LF_FINAL,
CHUNK_STATE_FINAL,
CHUNK_STATE_TRAILER_HEADER,
CHUNK_STATE_TRAILER_VALUE,
CHUNK_STATE_TRAILER,
CHUNK_STATE_DONE
} ChunkState;
#define HTTP_CHUNK_TYPE "chunked"
#define HTTP_UNCHUNK_TYPE "unchunked"
class nsHTTPChunkConvContext;
class nsHTTPChunkConv : public nsIStreamConverter {
public:
// nsISupports methods
NS_DECL_ISUPPORTS
NS_DECL_NSISTREAMOBSERVER
NS_DECL_NSISTREAMLISTENER
// nsIStreamConverter methods
NS_DECL_NSISTREAMCONVERTER
nsHTTPChunkConv ();
virtual ~nsHTTPChunkConv ();
private:
nsIStreamListener *mListener; // this guy gets the converted data via his OnDataAvailable ()
ChunkState mState;
ChunkMode mMode;
char *mChunkBuffer;
PRUint32 mChunkBufferLength;
PRUint32 mChunkBufferPos;
char mLenBuf[20];
PRUint32 mLenBufCnt;
nsCOMPtr<nsISupportsVoid> mAsyncConvContext;
char mValueBuf [4096];
PRUint32 mValueBufLen;
char mHeaderBuf [400];
PRUint32 mHeaderBufLen;
PRUint32 mHeadersCount;
PRUint32 mHeadersExpected;
nsHTTPChunkConvContext *mChunkContext;
};
class nsHTTPChunkConvHeaderEntry {
public:
nsHTTPChunkConvHeaderEntry (const char *aName, const char* aValue)
{
mName = aName;
mValue = aValue;
}
~nsHTTPChunkConvHeaderEntry()
{
}
nsCString mName;
nsCString mValue;
};
class nsHTTPChunkConvContext {
public:
nsHTTPChunkConvContext ()
: mEof (PR_FALSE), mHeadersCount (0)
{
}
~nsHTTPChunkConvContext ()
{
PRInt32 i = mHeaders.Count ();
while (i > 0)
{
nsHTTPChunkConvHeaderEntry *e = (nsHTTPChunkConvHeaderEntry *)mHeaders.RemoveElementAt (i - 1);
delete e;
}
}
void SetEOF (PRBool eof)
{
mEof = eof;
}
PRBool GetEOF () { return mEof; }
nsVoidArray * GetAllHeaders ()
{
return &mHeaders;
}
PRUint32 GetTrailerHeaderCount ()
{
return mHeadersCount;
}
void AddTrailerHeader (const char *header)
{
nsCStringKey key (header);
mTrailer.Put (&key, (void *) 1);
mHeadersCount++;
}
void SetResponseHeader (const char *header, const char *value)
{
nsHTTPChunkConvHeaderEntry *e = new nsHTTPChunkConvHeaderEntry (header, value);
mHeaders.AppendElement (e);
}
private:
PRBool mEof;
nsVoidArray mHeaders;
nsHashtable mTrailer;
PRUint32 mHeadersCount;
};
#endif

View File

@@ -1,471 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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): ruslan
*/
#include "nsHTTPCompressConv.h"
#include "nsMemory.h"
#include "plstr.h"
#include "prlog.h"
#include "nsIChannel.h"
#include "nsCOMPtr.h"
#include "nsIByteArrayInputStream.h"
#include "nsIStringStream.h"
// nsISupports implementation
NS_IMPL_THREADSAFE_ISUPPORTS2 (nsHTTPCompressConv, nsIStreamConverter, nsIStreamListener);
// nsFTPDirListingConv methods
nsHTTPCompressConv::nsHTTPCompressConv ()
: mListener (nsnull),
mMode (HTTP_COMPRESS_IDENTITY),
mOutBuffer (NULL), mInpBuffer (NULL),
mOutBufferLen (0), mInpBufferLen (0),
mCheckHeaderDone (PR_FALSE),
mGzipStreamEnded (PR_FALSE), mGzipStreamInitialized (PR_FALSE),
mLen (0), hMode (0), mSkipCount (0), mFlags (0)
{
NS_INIT_ISUPPORTS ();
}
nsHTTPCompressConv::~nsHTTPCompressConv ()
{
NS_IF_RELEASE(mListener);
if (mInpBuffer != NULL)
nsMemory::Free (mInpBuffer);
if (mOutBuffer != NULL)
nsMemory::Free (mOutBuffer);
}
NS_IMETHODIMP
nsHTTPCompressConv::AsyncConvertData (
const PRUnichar *aFromType,
const PRUnichar *aToType,
nsIStreamListener *aListener,
nsISupports *aCtxt)
{
nsString from (aFromType);
nsString to ( aToType );
char * fromStr = from.ToNewCString ();
char * toStr = to.ToNewCString ();
if (!PL_strncasecmp (fromStr, HTTP_COMPRESS_TYPE , strlen (HTTP_COMPRESS_TYPE ))
||
!PL_strncasecmp (fromStr, HTTP_X_COMPRESS_TYPE, strlen (HTTP_X_COMPRESS_TYPE)))
mMode = HTTP_COMPRESS_COMPRESS;
else
if (!PL_strncasecmp (fromStr, HTTP_GZIP_TYPE , strlen (HTTP_COMPRESS_TYPE))
||
!PL_strncasecmp (fromStr, HTTP_X_GZIP_TYPE , strlen (HTTP_X_GZIP_TYPE)))
mMode = HTTP_COMPRESS_GZIP;
else
if (!PL_strncasecmp (fromStr, HTTP_DEFLATE_TYPE, strlen (HTTP_DEFLATE_TYPE)))
mMode = HTTP_COMPRESS_DEFLATE;
nsMemory::Free (fromStr);
nsMemory::Free ( toStr);
// hook ourself up with the receiving listener.
mListener = aListener;
NS_ADDREF (mListener);
mAsyncConvContext = aCtxt;
return NS_OK;
}
NS_IMETHODIMP
nsHTTPCompressConv::OnStartRequest (nsIRequest* request, nsISupports *aContext)
{
return mListener->OnStartRequest (request, aContext);
}
NS_IMETHODIMP
nsHTTPCompressConv::OnStopRequest(nsIRequest* request, nsISupports *aContext,
nsresult aStatus, const PRUnichar* aStatusArg)
{
return mListener->OnStopRequest(request, aContext, aStatus, aStatusArg);
}
NS_IMETHODIMP
nsHTTPCompressConv::OnDataAvailable (
nsIRequest* request,
nsISupports *aContext,
nsIInputStream *iStr,
PRUint32 aSourceOffset,
PRUint32 aCount)
{
nsresult rv = NS_ERROR_FAILURE;
PRUint32 streamLen;
rv = iStr->Available (&streamLen);
if (NS_FAILED (rv))
return rv;
if (streamLen == 0 || mGzipStreamEnded)
return NS_OK;
switch (mMode)
{
case HTTP_COMPRESS_GZIP :
streamLen = check_header (iStr, streamLen, &rv);
if (rv != NS_OK)
return rv;
if (streamLen == 0)
return NS_OK;
case HTTP_COMPRESS_COMPRESS:
case HTTP_COMPRESS_DEFLATE :
if (mInpBuffer != NULL && streamLen > mInpBufferLen)
{
mInpBuffer = (unsigned char *) nsMemory::Realloc (mInpBuffer, mInpBufferLen = streamLen);
if (mOutBufferLen < streamLen * 2)
mOutBuffer = (unsigned char *) nsMemory::Realloc (mOutBuffer, mOutBufferLen = streamLen * 3);
if (mInpBuffer == NULL || mOutBuffer == NULL)
return NS_ERROR_OUT_OF_MEMORY;
}
if (mInpBuffer == NULL)
mInpBuffer = (unsigned char *) nsMemory::Alloc (mInpBufferLen = streamLen);
if (mOutBuffer == NULL)
mOutBuffer = (unsigned char *) nsMemory::Alloc (mOutBufferLen = streamLen * 3);
if (mInpBuffer == NULL || mOutBuffer == NULL)
return NS_ERROR_OUT_OF_MEMORY;
iStr->Read ((char *)mInpBuffer, streamLen, &rv);
if (NS_FAILED (rv))
return rv;
if (mMode == HTTP_COMPRESS_COMPRESS)
{
unsigned long uLen = mOutBufferLen;
int code = uncompress (mOutBuffer, &uLen, mInpBuffer, mInpBufferLen);
if (code == Z_BUF_ERROR)
{
mOutBuffer = (unsigned char *) nsMemory::Realloc (mOutBuffer, mOutBufferLen *= 3);
if (mOutBuffer == NULL)
return NS_ERROR_OUT_OF_MEMORY;
code = uncompress (mOutBuffer, &uLen, mInpBuffer, mInpBufferLen);
}
if (code != Z_OK)
return NS_ERROR_FAILURE;
rv = do_OnDataAvailable (request, aContext, aSourceOffset, (char *)mOutBuffer, (PRUint32) uLen);
if (NS_FAILED (rv))
return rv;
}
else
{
if (!mGzipStreamInitialized)
{
memset (&d_stream, 0, sizeof (d_stream));
if (inflateInit2 (&d_stream, -MAX_WBITS) != Z_OK)
return NS_ERROR_FAILURE;
mGzipStreamInitialized = PR_TRUE;
}
d_stream.next_in = mInpBuffer;
d_stream.avail_in = (uInt)streamLen;
for ( ; ; )
{
d_stream.next_out = mOutBuffer;
d_stream.avail_out = (uInt)mOutBufferLen;
int code = inflate (&d_stream, Z_NO_FLUSH);
unsigned bytesWritten = (uInt)mOutBufferLen - d_stream.avail_out;
if (code == Z_STREAM_END)
{
if (bytesWritten)
{
rv = do_OnDataAvailable (request, aContext, aSourceOffset, (char *)mOutBuffer, bytesWritten);
if (NS_FAILED (rv))
return rv;
}
inflateEnd (&d_stream);
mGzipStreamEnded = PR_TRUE;
break;
}
else
if (code == Z_OK)
{
if (bytesWritten)
{
rv = do_OnDataAvailable (request, aContext, aSourceOffset, (char *)mOutBuffer, bytesWritten);
if (NS_FAILED (rv))
return rv;
}
}
else
if (code == Z_BUF_ERROR)
{
if (bytesWritten)
{
rv = do_OnDataAvailable (request, aContext, aSourceOffset, (char *)mOutBuffer, bytesWritten);
if (NS_FAILED (rv))
return rv;
}
break;
}
else
return NS_ERROR_FAILURE;
} /* for */
} /* gzip */
break;
default:
rv = mListener->OnDataAvailable (request, aContext, iStr, aSourceOffset, aCount);
if (NS_FAILED (rv))
return rv;
} /* switch */
return NS_OK;
} /* OnDataAvailable */
// XXX/ruslan: need to implement this too
NS_IMETHODIMP
nsHTTPCompressConv::Convert (
nsIInputStream *aFromStream,
const PRUnichar *aFromType,
const PRUnichar *aToType,
nsISupports *aCtxt,
nsIInputStream **_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
nsresult
nsHTTPCompressConv::do_OnDataAvailable (nsIRequest* request, nsISupports *aContext, PRUint32 aSourceOffset, char *buffer, PRUint32 aCount)
{
nsresult rv;
nsCOMPtr<nsIByteArrayInputStream> convertedStreamSup;
char * lBuf = (char *) nsMemory::Alloc (aCount);
if (lBuf == NULL)
return NS_ERROR_OUT_OF_MEMORY;
memcpy (lBuf, buffer, aCount);
rv = NS_NewByteArrayInputStream (getter_AddRefs(convertedStreamSup), lBuf, aCount);
if (NS_FAILED (rv))
return rv;
nsCOMPtr<nsIInputStream> convertedStream = do_QueryInterface (convertedStreamSup, &rv);
if (NS_FAILED (rv))
return rv;
rv = mListener->OnDataAvailable (request, aContext, convertedStream, aSourceOffset, aCount);
return rv;
}
#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */
#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
#define ORIG_NAME 0x08 /* bit 3 set: original file name present */
#define COMMENT 0x10 /* bit 4 set: file comment present */
#define RESERVED 0xE0 /* bits 5..7: reserved */
static unsigned gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
PRUint32
nsHTTPCompressConv::check_header (nsIInputStream *iStr, PRUint32 streamLen, nsresult *rs)
{
nsresult rv;
enum { GZIP_INIT = 0, GZIP_OS, GZIP_EXTRA0, GZIP_EXTRA1, GZIP_EXTRA2, GZIP_ORIG, GZIP_COMMENT, GZIP_CRC };
char c;
*rs = NS_OK;
if (mCheckHeaderDone)
return streamLen;
while (streamLen)
{
switch (hMode)
{
case GZIP_INIT:
iStr->Read (&c, 1, &rv);
streamLen--;
if (mSkipCount == 0 && ((unsigned)c & 0377) != gz_magic[0])
{
*rs = NS_ERROR_FAILURE;
return 0;
}
if (mSkipCount == 1 && ((unsigned)c & 0377) != gz_magic[1])
{
*rs = NS_ERROR_FAILURE;
return 0;
}
if (mSkipCount == 2 && ((unsigned)c & 0377) != Z_DEFLATED)
{
*rs = NS_ERROR_FAILURE;
return 0;
}
mSkipCount++;
if (mSkipCount == 4)
{
mFlags = (unsigned) c & 0377;
if (mFlags & RESERVED)
{
*rs = NS_ERROR_FAILURE;
return 0;
}
hMode = GZIP_OS;
mSkipCount = 0;
}
break;
case GZIP_OS :
iStr->Read (&c, 1, &rv);
streamLen--;
mSkipCount++;
if (mSkipCount == 6)
hMode = GZIP_EXTRA0;
break;
case GZIP_EXTRA0:
if (mFlags & EXTRA_FIELD)
{
iStr->Read (&c, 1, &rv);
streamLen--;
mLen = (uInt) c & 0377;
hMode = GZIP_EXTRA1;
}
else
hMode = GZIP_ORIG;
break;
case GZIP_EXTRA1:
iStr->Read (&c, 1, &rv);
streamLen--;
mLen = ((uInt) c & 0377) << 8;
mSkipCount = 0;
hMode = GZIP_EXTRA2;
break;
case GZIP_EXTRA2:
if (mSkipCount == mLen)
hMode = GZIP_ORIG;
else
{
iStr->Read (&c, 1, &rv);
streamLen--;
mSkipCount++;
}
break;
case GZIP_ORIG:
if (mFlags & ORIG_NAME)
{
iStr->Read (&c, 1, &rv);
streamLen--;
if (c == 0)
hMode = GZIP_COMMENT;
}
else
hMode = GZIP_COMMENT;
break;
case GZIP_COMMENT:
if (mFlags & GZIP_COMMENT)
{
iStr->Read (&c, 1, &rv);
streamLen--;
if (c == 0)
{
hMode = GZIP_CRC;
mSkipCount = 0;
}
}
else
{
hMode = GZIP_CRC;
mSkipCount = 0;
}
break;
case GZIP_CRC:
if (mFlags & HEAD_CRC)
{
iStr->Read (&c, 1, &rv);
streamLen--;
mSkipCount++;
if (mSkipCount == 2)
{
mCheckHeaderDone = PR_TRUE;
return streamLen;
}
}
else
{
mCheckHeaderDone = PR_TRUE;
return streamLen;
}
break;
}
}
return streamLen;
}
nsresult
NS_NewHTTPCompressConv (nsHTTPCompressConv ** aHTTPCompressConv)
{
NS_PRECONDITION(aHTTPCompressConv != nsnull, "null ptr");
if (! aHTTPCompressConv)
return NS_ERROR_NULL_POINTER;
*aHTTPCompressConv = new nsHTTPCompressConv ();
if (! *aHTTPCompressConv)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(*aHTTPCompressConv);
return NS_OK;
}

View File

@@ -1,99 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#if !defined (__nsHTTPCompressConv__h__)
#define __nsHTTPCompressConv__h__ 1
#include "nsIStreamConverter.h"
#include "nsIFactory.h"
#include "nsCOMPtr.h"
#include "zlib.h"
#define NS_HTTPCOMPRESSCONVERTER_CID \
{ \
/* 66230b2b-17fa-4bd3-abf4-07986151022d */ \
0x66230b2b, \
0x17fa, \
0x4bd3, \
{0xab, 0xf4, 0x07, 0x98, 0x61, 0x51, 0x02, 0x2d}\
}
static NS_DEFINE_CID(kHTTPCompressConverterCID, NS_HTTPCOMPRESSCONVERTER_CID);
#define HTTP_DEFLATE_TYPE "deflate"
#define HTTP_GZIP_TYPE "gzip"
#define HTTP_X_GZIP_TYPE "x-gzip"
#define HTTP_COMPRESS_TYPE "compress"
#define HTTP_X_COMPRESS_TYPE "x-compress"
#define HTTP_IDENTITY_TYPE "identity"
#define HTTP_UNCOMPRESSED_TYPE "uncompressed"
typedef enum {
HTTP_COMPRESS_GZIP,
HTTP_COMPRESS_DEFLATE,
HTTP_COMPRESS_COMPRESS,
HTTP_COMPRESS_IDENTITY
} CompressMode;
class nsHTTPCompressConv : public nsIStreamConverter {
public:
// nsISupports methods
NS_DECL_ISUPPORTS
NS_DECL_NSISTREAMOBSERVER
NS_DECL_NSISTREAMLISTENER
// nsIStreamConverter methods
NS_DECL_NSISTREAMCONVERTER
nsHTTPCompressConv ();
virtual ~nsHTTPCompressConv ();
private:
nsIStreamListener *mListener; // this guy gets the converted data via his OnDataAvailable ()
CompressMode mMode;
unsigned char *mOutBuffer;
unsigned char *mInpBuffer;
PRUint32 mOutBufferLen;
PRUint32 mInpBufferLen;
nsCOMPtr<nsISupports> mAsyncConvContext;
nsresult do_OnDataAvailable (nsIRequest *request, nsISupports *aContext, PRUint32 aSourceOffset, char *buffer, PRUint32 aCount);
PRBool mCheckHeaderDone;
PRBool mGzipStreamEnded;
PRBool mGzipStreamInitialized;
z_stream d_stream;
unsigned mLen, hMode, mSkipCount, mFlags;
PRUint32 check_header (nsIInputStream *iStr, PRUint32 streamLen, nsresult *rv);
};
#endif

View File

@@ -1,573 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsMultiMixedConv.h"
#include "nsMemory.h"
#include "plstr.h"
#include "nsIHTTPChannel.h"
#include "nsIAtom.h"
#include "nsIServiceManager.h"
#include "nsNetUtil.h"
#include "nsMimeTypes.h"
#include "nsIByteArrayInputStream.h"
// nsISupports implementation
NS_IMPL_THREADSAFE_ISUPPORTS3(nsMultiMixedConv,
nsIStreamConverter,
nsIStreamListener,
nsIStreamObserver);
// nsIStreamConverter implementation
// No syncronous conversion at this time.
NS_IMETHODIMP
nsMultiMixedConv::Convert(nsIInputStream *aFromStream,
const PRUnichar *aFromType,
const PRUnichar *aToType,
nsISupports *aCtxt, nsIInputStream **_retval) {
return NS_ERROR_NOT_IMPLEMENTED;
}
// Stream converter service calls this to initialize the actual stream converter (us).
NS_IMETHODIMP
nsMultiMixedConv::AsyncConvertData(const PRUnichar *aFromType, const PRUnichar *aToType,
nsIStreamListener *aListener, nsISupports *aCtxt) {
NS_ASSERTION(aListener && aFromType && aToType, "null pointer passed into multi mixed converter");
// hook up our final listener. this guy gets the various On*() calls we want to throw
// at him.
//
// WARNING: this listener must be able to handle multiple OnStartRequest, OnDataAvail()
// and OnStopRequest() call combinations. We call of series of these for each sub-part
// in the raw stream.
mFinalListener = aListener;
return NS_OK;
}
#define ERR_OUT { nsMemory::Free(buffer); return rv; }
// nsIStreamListener implementation
NS_IMETHODIMP
nsMultiMixedConv::OnDataAvailable(nsIRequest *request, nsISupports *context,
nsIInputStream *inStr, PRUint32 sourceOffset, PRUint32 count) {
nsresult rv = NS_OK;
char *buffer = nsnull;
PRUint32 bufLen = count, read;
NS_ASSERTION(request, "multimixed converter needs a request");
nsCOMPtr<nsIChannel> channel = do_QueryInterface(request, &rv);
if (NS_FAILED(rv)) return rv;
buffer = (char*)nsMemory::Alloc(bufLen);
if (!buffer) return NS_ERROR_OUT_OF_MEMORY;
rv = inStr->Read(buffer, bufLen, &read);
if (NS_FAILED(rv) || read == 0) return rv;
NS_ASSERTION(read == bufLen, "poor data size assumption");
if (mBufLen) {
// incorporate any buffered data into the parsing
char *tmp = (char*)nsMemory::Alloc(mBufLen + bufLen);
if (!tmp) {
nsMemory::Free(buffer);
return NS_ERROR_OUT_OF_MEMORY;
}
nsCRT::memcpy(tmp, mBuffer, mBufLen);
nsMemory::Free(mBuffer);
mBuffer = nsnull;
nsCRT::memcpy(tmp+mBufLen, buffer, bufLen);
nsMemory::Free(buffer);
buffer = tmp;
bufLen += mBufLen;
mBufLen = 0;
}
if (mFirstOnData) {
// this is the first OnData() for this request. some servers
// don't bother sending a token in the first "part." This is
// illegal, but we'll handle the case anyway by shoving the
// boundary token in for the server.
mFirstOnData = PR_FALSE;
NS_ASSERTION(!mBufLen, "this is our first time through, we can't have buffered data");
const char * token = mToken;
if (bufLen < mTokenLen+2) {
// we don't have enough data yet to make this comparison.
// skip this check, and try again the next time OnData()
// is called.
mFirstOnData = PR_TRUE;
} else if (!PL_strnstr(buffer, token, mTokenLen+2)) {
bufLen = read + mTokenLen + 1;
char *tmp = (char*)nsMemory::Alloc(bufLen);
if (!tmp) {
nsMemory::Free(buffer);
return NS_ERROR_OUT_OF_MEMORY;
}
nsCRT::memcpy(tmp, token, mTokenLen);
nsCRT::memcpy(tmp+mTokenLen, "\n", 1);
nsCRT::memcpy(tmp+mTokenLen+1, buffer, read);
nsMemory::Free(buffer);
buffer = tmp;
}
}
char *cursor = buffer, *token = nsnull;
if (mProcessingHeaders) {
// we were not able to process all the headers
// for this "part" given the previous buffer given to
// us in the previous OnDataAvailable callback.
PRBool done = PR_FALSE;
rv = ParseHeaders(channel, cursor, bufLen, &done);
if (NS_FAILED(rv)) ERR_OUT
if (done) {
mProcessingHeaders = PR_FALSE;
rv = SendStart(channel);
if (NS_FAILED(rv)) ERR_OUT
}
}
PRInt8 tokenLinefeed = 1;
while ( (token = FindToken(cursor, bufLen)) ) {
if (*(token+mTokenLen+1) == '-') {
// This was the last delimiter so we can stop processing
bufLen = token - cursor;
rv = SendData(cursor, bufLen);
nsMemory::Free(buffer);
if (NS_FAILED(rv)) return rv;
buffer = nsnull;
bufLen = 0;
return SendStop(NS_OK, nsnull);
}
if (!mNewPart && token > cursor) {
// headers are processed, we're pushing data now.
NS_ASSERTION(!mProcessingHeaders, "we should be pushing raw data");
rv = SendData(cursor, token - cursor);
bufLen -= token - cursor;
if (NS_FAILED(rv)) ERR_OUT
}
token += mTokenLen;
bufLen -= mTokenLen;
tokenLinefeed = PushOverLine(token, bufLen);
if (mNewPart) {
// parse headers
mNewPart = PR_FALSE;
cursor = token;
PRBool done = PR_FALSE;
rv = ParseHeaders(channel, cursor, bufLen, &done);
if (NS_FAILED(rv)) ERR_OUT
if (done) {
rv = SendStart(channel);
if (NS_FAILED(rv)) ERR_OUT
} else {
// we haven't finished processing header info.
// we'll break out and try to process later.
mProcessingHeaders = PR_TRUE;
break;
}
} else {
mNewPart = PR_TRUE;
rv = SendStop(NS_OK, nsnull);
if (NS_FAILED(rv)) ERR_OUT
// reset to the token to front.
// this allows us to treat the token
// as a starting token.
token -= mTokenLen + tokenLinefeed;
bufLen += mTokenLen + tokenLinefeed;
cursor = token;
}
}
// at this point, we want to buffer up whatever amount (bufLen)
// we have leftover. However, we *always* want to ensure that
// we buffer enough data to handle a broken token.
// carry over
PRUint32 bufAmt = 0;
if (mProcessingHeaders) {
bufAmt = bufLen;
} else {
// if the data ends in a linefeed, we
// know the token can't cross it, thus
// we know there's no token left - don't buffer
if (!(cursor[bufLen-1] == LF))
bufAmt = PR_MIN(mTokenLen - 1, bufLen);
}
if (bufAmt) {
rv = BufferData(cursor + (bufLen - bufAmt), bufAmt);
if (NS_FAILED(rv)) ERR_OUT
bufLen -= bufAmt;
}
if (bufLen) {
rv = SendData(cursor, bufLen);
if (NS_FAILED(rv)) ERR_OUT
}
nsMemory::Free(buffer);
return rv;
}
// nsIStreamObserver implementation
NS_IMETHODIMP
nsMultiMixedConv::OnStartRequest(nsIRequest *request, nsISupports *ctxt) {
// we're assuming the content-type is available at this stage
NS_ASSERTION(!mToken, "a second on start???");
char *bndry = nsnull;
nsXPIDLCString delimiter;
nsresult rv = NS_OK;
mContext = ctxt;
mFirstOnData = PR_TRUE;
nsCOMPtr<nsIChannel> channel = do_QueryInterface(request, &rv);
if (NS_FAILED(rv)) return rv;
// ask the HTTP channel for the content-type and extract the boundary from it.
nsCOMPtr<nsIHTTPChannel> httpChannel = do_QueryInterface(channel, &rv);
if (NS_SUCCEEDED(rv)) {
nsCOMPtr<nsIAtom> header = NS_NewAtom("content-type");
if (!header) return NS_ERROR_OUT_OF_MEMORY;
rv = httpChannel->GetResponseHeader(header, getter_Copies(delimiter));
if (NS_FAILED(rv)) return rv;
} else {
// try asking the channel directly
rv = channel->GetContentType(getter_Copies(delimiter));
if (!delimiter || NS_FAILED(rv)) return NS_ERROR_FAILURE;
}
if (!delimiter) return NS_ERROR_FAILURE;
bndry = PL_strstr(delimiter, "boundary");
if (!bndry) return NS_ERROR_FAILURE;
bndry = PL_strchr(bndry, '=');
if (!bndry) return NS_ERROR_FAILURE;
bndry++; // move past the equals sign
char *attrib = PL_strchr(bndry, ';');
if (attrib) *attrib = '\0';
nsCAutoString boundaryString(bndry);
if (attrib) *attrib = ';';
boundaryString.Trim(" \"");
mToken = boundaryString.get();
if (!mToken) return NS_ERROR_OUT_OF_MEMORY;
mTokenLen = boundaryString.Length();
return NS_OK;
}
NS_IMETHODIMP
nsMultiMixedConv::OnStopRequest(nsIRequest *request, nsISupports *ctxt,
nsresult aStatus, const PRUnichar* aStatusArg) {
if (mPartChannel) {
// we've already called SendStart() (which sets up the mPartChannel,
// and fires an OnStart()) send any data left over, and then fire the stop.
if (mBufLen > 0 && mBuffer) {
(void) SendData(mBuffer, mBufLen);
// don't bother checking the return value here, if the send failed
// we're done anyway as we're in the OnStop() callback.
nsMemory::Free(mBuffer);
mBuffer = nsnull;
mBufLen = 0;
}
(void) SendStop(aStatus, aStatusArg);
} else if (NS_FAILED(aStatus)) {
// underlying data production problem. we should not be in
// the middle of sending data. if we were, mPartChannel,
// above, would have been true.
(void) mFinalListener->OnStartRequest(request, ctxt);
(void) mFinalListener->OnStopRequest(request, ctxt, aStatus, aStatusArg);
}
return NS_OK;
}
// nsMultiMixedConv methods
nsMultiMixedConv::nsMultiMixedConv() {
NS_INIT_ISUPPORTS();
mTokenLen = 0;
mNewPart = PR_TRUE;
mContentLength = -1;
mBuffer = nsnull;
mBufLen = 0;
mProcessingHeaders = PR_FALSE;
}
nsMultiMixedConv::~nsMultiMixedConv() {
NS_ASSERTION(!mBuffer, "all buffered data should be gone");
}
nsresult
nsMultiMixedConv::BufferData(char *aData, PRUint32 aLen) {
NS_ASSERTION(!mBuffer, "trying to over-write buffer");
char *buffer = (char*)nsMemory::Alloc(aLen);
if (!buffer) return NS_ERROR_OUT_OF_MEMORY;
nsCRT::memcpy(buffer, aData, aLen);
mBuffer = buffer;
mBufLen = aLen;
return NS_OK;
}
nsresult
nsMultiMixedConv::SendStart(nsIChannel *aChannel) {
nsresult rv = NS_OK;
// First build up a dummy uri.
nsCOMPtr<nsIURI> partURI;
rv = aChannel->GetURI(getter_AddRefs(partURI));
if (NS_FAILED(rv)) return rv;
if (mContentType.IsEmpty())
mContentType = UNKNOWN_CONTENT_TYPE;
// if we already have an mPartChannel, that means we never sent a Stop()
// before starting up another "part." that would be bad.
NS_ASSERTION(!mPartChannel, "tisk tisk, shouldn't be overwriting a channel");
rv = NS_NewInputStreamChannel(getter_AddRefs(mPartChannel),
partURI,
nsnull, // inStr
mContentType.get(),
mContentLength);
if (NS_FAILED(rv)) return rv;
nsLoadFlags loadFlags = 0;
mPartChannel->GetLoadAttributes(&loadFlags);
loadFlags |= nsIChannel::LOAD_REPLACE;
mPartChannel->SetLoadAttributes(loadFlags);
nsCOMPtr<nsILoadGroup> loadGroup;
(void)aChannel->GetLoadGroup(getter_AddRefs(loadGroup));
// Add the new channel to the load group (if any)
if (loadGroup) {
rv = mPartChannel->SetLoadGroup(loadGroup);
if (NS_FAILED(rv)) return rv;
rv = loadGroup->AddRequest(mPartChannel, nsnull);
if (NS_FAILED(rv)) return rv;
}
// Let's start off the load. NOTE: we don't forward on the channel passed
// into our OnDataAvailable() as it's the root channel for the raw stream.
return mFinalListener->OnStartRequest(mPartChannel, mContext);
}
nsresult
nsMultiMixedConv::SendStop(nsresult aStatus, const PRUnichar* aStatusArg) {
nsresult rv = NS_OK;
if (mPartChannel) {
rv = mFinalListener->OnStopRequest(mPartChannel, mContext, aStatus, aStatusArg);
// don't check for failure here, we need to remove the channel from
// the loadgroup.
// Remove the channel from its load group (if any)
nsCOMPtr<nsILoadGroup> loadGroup;
(void) mPartChannel->GetLoadGroup(getter_AddRefs(loadGroup));
if (loadGroup)
(void) loadGroup->RemoveRequest(mPartChannel, mContext, aStatus, aStatusArg);
}
mPartChannel = 0;
return rv;
}
nsresult
nsMultiMixedConv::SendData(char *aBuffer, PRUint32 aLen) {
nsresult rv = NS_OK;
if (!mPartChannel) return NS_ERROR_FAILURE; // something went wrong w/ processing
char *tmp = (char*)nsMemory::Alloc(aLen); // byteArray stream owns this mem
if (!tmp) return NS_ERROR_OUT_OF_MEMORY;
nsCRT::memcpy(tmp, aBuffer, aLen);
nsCOMPtr<nsIByteArrayInputStream> byteArrayStream;
rv = NS_NewByteArrayInputStream(getter_AddRefs(byteArrayStream), tmp, aLen);
if (NS_FAILED(rv)) {
nsMemory::Free(tmp);
return rv;
}
nsCOMPtr<nsIInputStream> inStream = do_QueryInterface(byteArrayStream, &rv);
if (NS_FAILED(rv)) return rv;
PRUint32 len;
rv = inStream->Available(&len);
if (NS_FAILED(rv)) return rv;
return mFinalListener->OnDataAvailable(mPartChannel, mContext, inStream, 0, len);
}
PRInt8
nsMultiMixedConv::PushOverLine(char *&aPtr, PRUint32 &aLen) {
PRInt8 chars = 0;
if (*aPtr == CR || *aPtr == LF) {
if (aPtr[1] == LF)
chars++;
chars++;
}
aPtr += chars;
aLen -= chars;
return chars;
}
nsresult
nsMultiMixedConv::ParseHeaders(nsIChannel *aChannel, char *&aPtr,
PRUint32 &aLen, PRBool *_retval) {
// NOTE: this data must be ascii.
nsresult rv = NS_OK;
char *cursor = aPtr, *newLine = nsnull;
PRUint32 cursorLen = aLen;
PRBool done = PR_FALSE;
PRUint8 lineFeedIncrement = 1;
while ( (cursorLen > 0)
&& (newLine = PL_strchr(cursor, LF)) ) {
// adjust for linefeeds
if ( (newLine > cursor) && (newLine[-1] == CR) ) { // CRLF
lineFeedIncrement = 2;
newLine--;
}
if (newLine == cursor) {
// move the newLine beyond the double linefeed marker
if ( (newLine - cursor) < ((PRInt32)cursorLen - lineFeedIncrement) ) {
newLine += lineFeedIncrement;
}
cursorLen -= (newLine - cursor);
cursor = newLine;
done = PR_TRUE;
break;
}
char tmpChar = *newLine;
*newLine = '\0';
char *colon = PL_strchr(cursor, ':');
if (colon) {
*colon = '\0';
nsCAutoString headerStr(cursor);
headerStr.CompressWhitespace();
headerStr.ToLowerCase();
nsCOMPtr<nsIAtom> header = NS_NewAtom(headerStr.get());
if (!header) return NS_ERROR_OUT_OF_MEMORY;
*colon = ':';
nsCAutoString headerVal(colon + 1);
headerVal.CompressWhitespace();
// examine header
if (headerStr.Equals("content-type")) {
mContentType = headerVal;
} else if (headerStr.Equals("content-length")) {
mContentLength = atoi(headerVal.get());
} else if (headerStr.Equals("set-cookie")) {
// setting headers on the HTTP channel
// causes HTTP to notify, again if necessary,
// it's header observers.
nsCOMPtr<nsIHTTPChannel> httpChannel = do_QueryInterface(aChannel);
if (httpChannel) {
rv = httpChannel->SetResponseHeader(header, headerVal);
if (NS_FAILED(rv)) return rv;
}
}
}
*newLine = tmpChar;
newLine += lineFeedIncrement;
cursorLen -= (newLine - cursor);
cursor = newLine;
} // end while (newLine)
aPtr = cursor;
aLen = cursorLen;
*_retval = done;
return rv;
}
char *
nsMultiMixedConv::FindToken(char *aCursor, PRUint32 aLen) {
// strnstr without looking for null termination
const char *token = mToken;
char *cur = aCursor;
NS_ASSERTION(token && aCursor && *token, "bad data");
if( mTokenLen > aLen ) return nsnull;
for( ; aLen >= mTokenLen; aCursor++, aLen-- )
if( *token == *aCursor)
if(!memcmp(aCursor, token, mTokenLen) ) {
if ( (aCursor - cur) >= 2) {
// back the cursor up over a double dash for backwards compat.
if ( (*(aCursor-1) == '-') && (*(aCursor-2) == '-') ) {
aCursor -= 2;
aLen += 2;
// we're playing w/ double dash tokens, adjust.
nsCString newToken("--");
newToken.Append(mToken);
mToken = newToken.get();
mTokenLen += 2;
}
}
return aCursor;
}
return nsnull;
}
nsresult
NS_NewMultiMixedConv(nsMultiMixedConv** aMultiMixedConv)
{
NS_PRECONDITION(aMultiMixedConv != nsnull, "null ptr");
if (! aMultiMixedConv)
return NS_ERROR_NULL_POINTER;
*aMultiMixedConv = new nsMultiMixedConv();
if (! *aMultiMixedConv)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(*aMultiMixedConv);
return NS_OK;
}

View File

@@ -1,117 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#ifndef __nsmultimixedconv__h__
#define __nsmultimixedconv__h__
#include "nsIStreamConverter.h"
#include "nsIChannel.h"
#include "nsIURI.h"
#include "nsString.h"
#include "nsXPIDLString.h"
#include "nsCOMPtr.h"
#define NS_MULTIMIXEDCONVERTER_CID \
{ /* 7584CE90-5B25-11d3-A175-0050041CAF44 */ \
0x7584ce90, \
0x5b25, \
0x11d3, \
{0xa1, 0x75, 0x0, 0x50, 0x4, 0x1c, 0xaf, 0x44} \
}
static NS_DEFINE_CID(kMultiMixedConverterCID, NS_MULTIMIXEDCONVERTER_CID);
// The nsMultiMixedConv stream converter converts a stream of type "multipart/x-mixed-replace"
// to it's subparts. There was some debate as to whether or not the functionality desired
// when HTTP confronted this type required a stream converter. After all, this type really
// prompts various viewer related actions rather than stream conversion. There simply needs
// to be a piece in place that can strip out the multiple parts of a stream of this type, and
// "display" them accordingly.
//
// With that said, this "stream converter" spends more time packaging up the sub parts of the
// main stream and sending them off the destination stream listener, than doing any real
// stream parsing/converting.
//
// WARNING: This converter requires that it's destination stream listener be able to handle
// multiple OnStartRequest(), OnDataAvailable(), and OnStopRequest() call combinations.
// Each series represents the beginning, data production, and ending phase of each sub-
// part of the original stream.
//
// NOTE: this MIME-type is used by HTTP, *not* SMTP, or IMAP.
//
// NOTE: For reference, a general description of how this MIME type should be handled via
// HTTP, see http://home.netscape.com/assist/net_sites/pushpull.html . Note that
// real world server content deviates considerably from this overview.
//
// Implementation assumptions:
// Assumed structue:
// --BoundaryToken[\r]\n
// content-type: foo/bar[\r]\n
// ... (other headers if any)
// [\r]\n (second line feed to delimit end of headers)
// data
// --BoundaryToken-- (end delimited by final "--")
//
// linebreaks can be either CRLF or LFLF. linebreaks preceeding
// boundary tokens are considered part of the data. BoundaryToken
// is any opaque string.
//
//
class nsMultiMixedConv : public nsIStreamConverter {
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISTREAMCONVERTER
NS_DECL_NSISTREAMLISTENER
NS_DECL_NSISTREAMOBSERVER
nsMultiMixedConv();
virtual ~nsMultiMixedConv();
protected:
nsresult SendStart(nsIChannel *aChannel);
nsresult SendStop(nsresult aStatus, const PRUnichar *aStatusMsg);
nsresult SendData(char *aBuffer, PRUint32 aLen);
nsresult ParseHeaders(nsIChannel *aChannel, char *&aPtr,
PRUint32 &aLen, PRBool *_retval);
PRInt8 PushOverLine(char *&aPtr, PRUint32 &aLen);
char *FindToken(char *aCursor, PRUint32 aLen);
nsresult BufferData(char *aData, PRUint32 aLen);
// member data
PRBool mNewPart; // Are we processing the beginning of a part?
PRBool mProcessingHeaders;
nsCOMPtr<nsIStreamListener> mFinalListener; // this guy gets the converted data via his OnDataAvailable()
nsXPIDLCString mToken;
PRUint32 mTokenLen;
nsCOMPtr<nsIChannel>mPartChannel; // the channel for the given part we're processing.
// one channel per part.
nsCOMPtr<nsISupports> mContext;
nsCString mContentType;
PRInt32 mContentLength;
char *mBuffer;
PRUint32 mBufLen;
PRBool mFirstOnData; // used to determine if we're in our first OnData callback.
};
#endif /* __nsmultimixedconv__h__ */

View File

@@ -1,279 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsTXTToHTMLConv.h"
#include "nsNetUtil.h"
#include "nsIStringStream.h"
#define TOKEN_DELIMITERS "\t\r\n "
// nsISupports methods
NS_IMPL_THREADSAFE_ISUPPORTS4(nsTXTToHTMLConv,
nsIStreamConverter,
nsITXTToHTMLConv,
nsIStreamObserver,
nsIStreamListener);
// nsIStreamConverter methods
NS_IMETHODIMP
nsTXTToHTMLConv::Convert(nsIInputStream *aFromStream,
const PRUnichar *aFromType, const PRUnichar *aToType,
nsISupports *aCtxt, nsIInputStream * *_retval) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsTXTToHTMLConv::AsyncConvertData(const PRUnichar *aFromType,
const PRUnichar *aToType,
nsIStreamListener *aListener,
nsISupports *aCtxt) {
NS_ASSERTION(aListener, "null pointer");
mListener = aListener;
return NS_OK;
}
// nsIStreamObserver methods
NS_IMETHODIMP
nsTXTToHTMLConv::OnStartRequest(nsIRequest* request, nsISupports *aContext) {
mBuffer.AssignWithConversion("<html>\n<head><title>");
mBuffer.Append(mPageTitle);
mBuffer.AppendWithConversion("</title></head>\n<body>\n");
if (mPreFormatHTML) { // Use <pre> tags
mBuffer.AppendWithConversion("<pre>\n");
}
// Push mBuffer to the listener now, so the initial HTML will not
// be parsed in OnDataAvailable().
nsresult rv = mListener->OnStartRequest(request, aContext);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIInputStream> inputData;
nsCOMPtr<nsISupports> inputDataSup;
rv = NS_NewStringInputStream(getter_AddRefs(inputDataSup), mBuffer);
if (NS_FAILED(rv)) return rv;
inputData = do_QueryInterface(inputDataSup);
rv = mListener->OnDataAvailable(request, aContext,
inputData, 0, mBuffer.Length());
if (NS_FAILED(rv)) return rv;
mBuffer.AssignWithConversion("");
return rv;
}
NS_IMETHODIMP
nsTXTToHTMLConv::OnStopRequest(nsIRequest* request, nsISupports *aContext,
nsresult aStatus, const PRUnichar* aStatusArg) {
nsresult rv = NS_OK;
if (mToken) {
// we still have an outstanding token
PRInt32 back = mBuffer.FindCharInSet(TOKEN_DELIMITERS);
if (back == -1) back = mBuffer.Length();
(void)CatHTML(0, mBuffer.Length());
}
if (mPreFormatHTML) {
mBuffer.AppendWithConversion("</pre>\n");
}
mBuffer.AppendWithConversion("\n</body></html>");
nsCOMPtr<nsIInputStream> inputData;
nsCOMPtr<nsISupports> inputDataSup;
rv = NS_NewStringInputStream(getter_AddRefs(inputDataSup), mBuffer);
if (NS_FAILED(rv)) return rv;
inputData = do_QueryInterface(inputDataSup);
rv = mListener->OnDataAvailable(request, aContext,
inputData, 0, mBuffer.Length());
if (NS_FAILED(rv)) return rv;
return mListener->OnStopRequest(request, aContext, aStatus, aStatusArg);
}
// nsITXTToHTMLConv methods
NS_IMETHODIMP
nsTXTToHTMLConv::SetTitle(const PRUnichar *aTitle) {
mPageTitle.Assign(aTitle);
return NS_OK;
}
NS_IMETHODIMP
nsTXTToHTMLConv::PreFormatHTML(PRBool value) {
mPreFormatHTML = value;
return NS_OK;
}
// nsIStreamListener method
NS_IMETHODIMP
nsTXTToHTMLConv::OnDataAvailable(nsIRequest* request, nsISupports *aContext,
nsIInputStream *aInStream,
PRUint32 aOffset, PRUint32 aCount) {
nsresult rv = NS_OK;
nsString pushBuffer;
PRUint32 amtRead = 0;
char *buffer = (char*)nsMemory::Alloc(aCount+1);
if (!buffer) return NS_ERROR_OUT_OF_MEMORY;
do {
PRUint32 read = 0;
rv = aInStream->Read(buffer, aCount-amtRead, &read);
if (NS_FAILED(rv)) return rv;
buffer[read] = '\0';
mBuffer.AppendWithConversion(buffer);
amtRead += read;
PRInt32 front = -1, back = -1, tokenLoc = -1, cursor = 0;
while ( (tokenLoc = FindToken(cursor, &mToken)) > -1) {
front = mBuffer.RFindCharInSet(TOKEN_DELIMITERS, tokenLoc);
front++;
back = mBuffer.FindCharInSet(TOKEN_DELIMITERS, tokenLoc);
if (back == -1) {
// didn't find an ending, buffer up.
mBuffer.Left(pushBuffer, front);
cursor = front;
break;
} else {
// found the end of the token.
cursor = CatHTML(front, back);
}
}
PRInt32 end = mBuffer.RFind(TOKEN_DELIMITERS,
PR_FALSE, mBuffer.Length());
mBuffer.Left(pushBuffer, PR_MAX(cursor, end));
mBuffer.Cut(0, PR_MAX(cursor, end));
cursor = 0;
if (!pushBuffer.IsEmpty()) {
nsCOMPtr<nsIInputStream> inputData;
nsCOMPtr<nsISupports> inputDataSup;
rv = NS_NewStringInputStream(getter_AddRefs(inputDataSup), pushBuffer);
if (NS_FAILED(rv)) {
nsMemory::Free(buffer);
return rv;
}
inputData = do_QueryInterface(inputDataSup);
rv = mListener->OnDataAvailable(request, aContext,
inputData, 0, pushBuffer.Length());
if (NS_FAILED(rv)) {
nsMemory::Free(buffer);
return rv;
}
}
} while (amtRead < aCount);
nsMemory::Free(buffer);
return rv;
}
// nsTXTToHTMLConv methods
nsTXTToHTMLConv::nsTXTToHTMLConv() {
NS_INIT_REFCNT();
mToken = nsnull;
mPreFormatHTML = PR_FALSE;
}
static PRBool CleanupTokens(void *aElement, void *aData) {
if (aElement) delete (convToken*)aElement;
return PR_TRUE;
}
nsTXTToHTMLConv::~nsTXTToHTMLConv() {
mTokens.EnumerateForwards((nsVoidArrayEnumFunc)CleanupTokens, nsnull);
}
nsresult
nsTXTToHTMLConv::Init() {
nsresult rv = NS_OK;
// build up the list of tokens to handle
convToken *token = new convToken;
if (!token) return NS_ERROR_OUT_OF_MEMORY;
token->prepend = PR_TRUE;
token->token.AssignWithConversion("http://"); // XXX need to iterate through all protos
mTokens.AppendElement(token);
token = new convToken;
if (!token) return NS_ERROR_OUT_OF_MEMORY;
token->prepend = PR_TRUE;
token->token.AssignWithConversion('@');
token->modText.AssignWithConversion("mailto:");
mTokens.AppendElement(token);
return rv;
}
PRInt32
nsTXTToHTMLConv::FindToken(PRInt32 cursor, convToken* *_retval) {
PRInt32 loc = -1, firstToken = mBuffer.Length();
PRInt8 token = -1;
for (PRInt8 i=0; i < mTokens.Count(); i++) {
loc = mBuffer.Find(((convToken*)mTokens[i])->token, PR_FALSE, cursor);
if (loc != -1)
if (loc < firstToken) {
firstToken = loc;
token = i;
}
}
if (token != -1) {
*_retval = (convToken*)mTokens[token];
return firstToken;
} else {
return -1;
}
}
PRInt32
nsTXTToHTMLConv::CatHTML(PRInt32 front, PRInt32 back) {
PRInt32 cursor = 0;
if (!mToken->prepend) {
// replace the entire token (from delimiter to delimiter)
mBuffer.Cut(front, back);
mBuffer.Insert(mToken->modText, front);
} else {
nsString linkText;
// href is implied
PRInt32 modLen = mToken->modText.Length();
mBuffer.Mid(linkText, front, back-front);
mBuffer.InsertWithConversion("<a href=\"", front);
cursor += front+9;
if (modLen)
mBuffer.Insert(mToken->modText, cursor);
cursor += modLen-front+back;
mBuffer.InsertWithConversion("\">", cursor);
cursor += 2;
mBuffer.Insert(linkText, cursor);
cursor += linkText.Length();
mBuffer.InsertWithConversion("</a>", cursor);
cursor += 4;
}
mToken = nsnull; // indicates completeness
return cursor;
}

View File

@@ -1,98 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#ifndef ____nstxttohtmlconv___h___
#define ____nstxttohtmlconv___h___
#include "nsITXTToHTMLConv.h"
#include "nsCOMPtr.h"
#include "nsVoidArray.h"
#include "nsIFactory.h"
#include "nsString.h"
#define NS_NSTXTTOHTMLCONVERTER_CID \
{ /* 9ef9fa14-1dd1-11b2-9d65-d72d6d1f025e */ \
0x9ef9fa14, \
0x1dd1, \
0x11b2, \
{0x9d, 0x65, 0xd7, 0x2d, 0x6d, 0x1f, 0x02, 0x5e} \
}
// Internal representation of a "token"
typedef struct convToken {
nsString token; // the actual string (i.e. "http://")
nsString modText; // replacement text or href prepend text.
PRBool prepend; // flag indicating how the modText should be used.
} convToken;
class nsTXTToHTMLConv : public nsITXTToHTMLConv {
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISTREAMCONVERTER
NS_DECL_NSITXTTOHTMLCONV
NS_DECL_NSISTREAMOBSERVER
NS_DECL_NSISTREAMLISTENER
nsTXTToHTMLConv();
virtual ~nsTXTToHTMLConv();
nsresult Init();
// For factory creation.
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult) {
nsresult rv;
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsTXTToHTMLConv* _s = new nsTXTToHTMLConv();
if (_s == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(_s);
rv = _s->Init();
if (NS_FAILED(rv)) {
delete _s;
return rv;
}
rv = _s->QueryInterface(aIID, aResult);
NS_RELEASE(_s);
return rv;
}
protected:
// return the token and it's location in the underlying buffer.
PRInt32 FindToken(PRInt32 cursor, convToken* *_retval);
// return the cursor location after munging HTML into the
// underlying buffer.
PRInt32 CatHTML(PRInt32 front, PRInt32 back);
nsCOMPtr<nsIStreamListener> mListener; // final listener (consumer)
nsString mBuffer; // any carry over data
nsVoidArray mTokens; // list of tokens to search for
convToken *mToken; // current token (if any)
nsString mPageTitle; // Page title
PRBool mPreFormatHTML; // Whether to use <pre> tags
};
#endif // ____nstxttohtmlconv___h___

View File

@@ -1,376 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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) 1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsUnknownDecoder.h"
#include "nsIServiceManager.h"
#include "nsIStreamConverterService.h"
#include "nsIPipe.h"
#include "nsIInputStream.h"
#include "nsIOutputStream.h"
#include "nsMimeTypes.h"
#include "netCore.h"
#include "nsXPIDLString.h"
#include "nsIPref.h"
#define MAX_BUFFER_SIZE 1024
static NS_DEFINE_CID(kStreamConverterServiceCID, NS_STREAMCONVERTERSERVICE_CID);
static NS_DEFINE_IID(kPrefServiceCID, NS_PREF_CID);
nsUnknownDecoder::nsUnknownDecoder()
{
NS_INIT_ISUPPORTS();
mBuffer = nsnull;
mBufferLen = 0;
mRequireHTMLsuffix = PR_FALSE;
nsresult rv;
nsCOMPtr<nsIPref> pPrefService = do_GetService(kPrefServiceCID, &rv);
if (NS_SUCCEEDED(rv)) {
rv = pPrefService->GetBoolPref("security.requireHTMLsuffix", &mRequireHTMLsuffix);
}
}
nsUnknownDecoder::~nsUnknownDecoder()
{
if (mBuffer) {
delete [] mBuffer;
mBuffer = nsnull;
}
}
// ----
//
// nsISupports implementation...
//
// ----
NS_IMPL_ADDREF(nsUnknownDecoder);
NS_IMPL_RELEASE(nsUnknownDecoder);
NS_INTERFACE_MAP_BEGIN(nsUnknownDecoder)
NS_INTERFACE_MAP_ENTRY(nsIStreamConverter)
NS_INTERFACE_MAP_ENTRY(nsIStreamListener)
NS_INTERFACE_MAP_ENTRY(nsIStreamObserver)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
// ----
//
// nsIStreamConverter methods...
//
// ----
NS_IMETHODIMP
nsUnknownDecoder::Convert(nsIInputStream *aFromStream,
const PRUnichar *aFromType,
const PRUnichar *aToType,
nsISupports *aCtxt,
nsIInputStream **aResultStream)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsUnknownDecoder::AsyncConvertData(const PRUnichar *aFromType,
const PRUnichar *aToType,
nsIStreamListener *aListener,
nsISupports *aCtxt)
{
NS_ASSERTION(aListener && aFromType && aToType,
"null pointer passed into multi mixed converter");
// hook up our final listener. this guy gets the various On*() calls we want to throw
// at him.
//
mNextListener = aListener;
return (aListener) ? NS_OK : NS_ERROR_FAILURE;
}
// ----
//
// nsIStreamListener methods...
//
// ----
NS_IMETHODIMP
nsUnknownDecoder::OnDataAvailable(nsIRequest* request,
nsISupports *aCtxt,
nsIInputStream *aStream,
PRUint32 aSourceOffset,
PRUint32 aCount)
{
nsresult rv = NS_OK;
if (!mNextListener) return NS_ERROR_FAILURE;
if (mContentType.IsEmpty()) {
PRUint32 count, len;
// If the buffer has not been allocated by now, just fail...
if (!mBuffer) return NS_ERROR_OUT_OF_MEMORY;
//
// Determine how much of the stream should be read to fill up the
// sniffer buffer...
//
if (mBufferLen + aCount >= MAX_BUFFER_SIZE) {
count = MAX_BUFFER_SIZE-mBufferLen;
} else {
count = aCount;
}
// Read the data into the buffer...
rv = aStream->Read((mBuffer+mBufferLen), count, &len);
if (NS_FAILED(rv)) return rv;
mBufferLen += len;
aCount -= len;
if (aCount) {
//
// Adjust the source offset... The call to FireListenerNotifications(...)
// will make the first OnDataAvailable(...) call with an offset of 0.
// So, this offset needs to be adjusted to reflect that...
//
aSourceOffset += mBufferLen;
DetermineContentType(request);
NS_ASSERTION(!mContentType.IsEmpty(),
"Content type should be known by now.");
rv = FireListenerNotifications(request, aCtxt);
}
}
if (aCount) {
NS_ASSERTION(!mContentType.IsEmpty(),
"Content type should be known by now.");
rv = mNextListener->OnDataAvailable(request, aCtxt, aStream,
aSourceOffset, aCount);
}
return rv;
}
// ----
//
// nsIStreamObserver methods...
//
// ----
NS_IMETHODIMP
nsUnknownDecoder::OnStartRequest(nsIRequest* request, nsISupports *aCtxt)
{
nsresult rv = NS_OK;
if (!mNextListener) return NS_ERROR_FAILURE;
// Allocate the sniffer buffer...
if (NS_SUCCEEDED(rv) && !mBuffer) {
mBuffer = new char[MAX_BUFFER_SIZE];
if (!mBuffer) {
rv = NS_ERROR_OUT_OF_MEMORY;
}
}
// Do not pass the OnStartRequest on to the next listener (yet)...
return rv;
}
NS_IMETHODIMP
nsUnknownDecoder::OnStopRequest(nsIRequest* request, nsISupports *aCtxt,
nsresult aStatus, const PRUnichar* aStatusArg)
{
nsresult rv = NS_OK;
if (!mNextListener) return NS_ERROR_FAILURE;
//
// The total amount of data is less than the size of the sniffer buffer.
// Analyze the buffer now...
//
if (mContentType.IsEmpty()) {
DetermineContentType(request);
NS_ASSERTION(!mContentType.IsEmpty(),
"Content type should be known by now.");
rv = FireListenerNotifications(request, aCtxt);
if (NS_FAILED(rv)) {
aStatus = rv;
}
}
rv = mNextListener->OnStopRequest(request, aCtxt, aStatus, aStatusArg);
mNextListener = 0;
return rv;
}
void nsUnknownDecoder::DetermineContentType(nsIRequest* request)
{
PRUint32 i;
NS_ASSERTION(mContentType.IsEmpty(), "Content type is already known.");
if (!mContentType.IsEmpty()) return;
CBufDescriptor bufDesc((const char*)mBuffer, PR_TRUE, mBufferLen, mBufferLen);
nsCAutoString str(bufDesc);
//
// If the buffer begins with "#!" or "%!" then it is a script of some
// sort...
//
// This false match happened all the time... For example, CGI scripts
// written in sh or perl that emit HTML.
//
if (str.EqualsWithConversion("#!", PR_FALSE, 2) ||
str.EqualsWithConversion("%!", PR_FALSE, 2)) {
mContentType = TEXT_PLAIN;
}
//
// If the buffer begins with a mailbox delimiter then it is not HTML
//
else if (str.EqualsWithConversion("From ", PR_TRUE, 5) ||
str.EqualsWithConversion(">From ", PR_TRUE, 6)) {
mContentType = TEXT_PLAIN;
}
//
// If the buffer contains "common" HTML tags then lets call it HTML :-)
//
else {
/*
* To prevent a possible attack, we will not consider this to be html
* content if it comes from the local file system
*/
PRBool isLocalFile = PR_FALSE;
if (request) {
nsCOMPtr<nsIChannel> aChannel = do_QueryInterface(request);
if (!request) { NS_WARNING("QI failed"); return; }
nsCOMPtr<nsIURI> pURL;
if (NS_SUCCEEDED(aChannel->GetURI(getter_AddRefs(pURL))))
pURL->SchemeIs(nsIURI::FILE, &isLocalFile);
}
if (!mRequireHTMLsuffix || !isLocalFile) {
PRInt32 offset;
offset = str.Find("<HTML", PR_TRUE);
if (offset < 0) {
offset = str.Find("<TITLE", PR_TRUE);
if (offset < 0) {
offset = str.Find("<FRAMESET", PR_TRUE);
if (offset < 0) {
offset = str.Find("<SCRIPT", PR_TRUE);
if (offset < 0) {
offset = str.Find("<BODY", PR_TRUE);
}
}
}
}
if (offset >= 0) {
mContentType = TEXT_HTML;
}
}
}
//
// See if the buffer has any embedded nulls. If not, then lets just
// call it text/plain...
//
if (mContentType.IsEmpty()) {
for (i=0; i<mBufferLen && mBuffer[i]; i++);
if (i == mBufferLen) {
mContentType = TEXT_PLAIN;
}
}
//
// If the buffer is not text, then just call it application/octet-stream
//
if (mContentType.IsEmpty()) {
mContentType = APPLICATION_OCTET_STREAM;
}
}
nsresult nsUnknownDecoder::FireListenerNotifications(nsIRequest* request,
nsISupports *aCtxt)
{
nsresult rv = NS_OK;
if (!mNextListener) return NS_ERROR_FAILURE;
if (!mBuffer) return NS_ERROR_OUT_OF_MEMORY;
nsCOMPtr<nsIChannel> channel = do_QueryInterface(request, &rv);
if (NS_FAILED(rv)) return rv;
// Set the new content type on the channel...
channel->SetContentType(mContentType);
// Fire the OnStartRequest(...)
rv = mNextListener->OnStartRequest(request, aCtxt);
// Fire the first OnDataAvailable for the data that was read from the
// stream into the sniffer buffer...
if (NS_SUCCEEDED(rv)) {
PRUint32 len = 0;
nsCOMPtr<nsIInputStream> in;
nsCOMPtr<nsIOutputStream> out;
// Create a pipe and fill it with the data from the sniffer buffer.
rv = NS_NewPipe(getter_AddRefs(in), getter_AddRefs(out),
MAX_BUFFER_SIZE, MAX_BUFFER_SIZE);
if (NS_SUCCEEDED(rv)) {
rv = out->Write(mBuffer, mBufferLen, &len);
if (NS_SUCCEEDED(rv)) {
if (len == mBufferLen) {
rv = mNextListener->OnDataAvailable(request, aCtxt, in, 0, len);
} else {
NS_ASSERTION(0, "Unable to write all the data into the pipe.");
rv = NS_ERROR_FAILURE;
}
}
}
}
delete [] mBuffer;
mBuffer = nsnull;
mBufferLen = 0;
return rv;
}

View File

@@ -1,76 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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) 1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsUnknownDecoder_h__
#define nsUnknownDecoder_h__
#include "nsIStreamConverter.h"
#include "nsIChannel.h"
#include "nsCOMPtr.h"
#include "nsString.h"
#define NS_UNKNOWNDECODER_CID \
{ /* 7d7008a0-c49a-11d3-9b22-0080c7cb1080 */ \
0x7d7008a0, \
0xc49a, \
0x11d3, \
{0x9b, 0x22, 0x00, 0x80, 0xc7, 0xcb, 0x10, 0x80} \
}
class nsUnknownDecoder : public nsIStreamConverter
{
public:
// nsISupports methods
NS_DECL_ISUPPORTS
// nsIStreamConverter methods
NS_DECL_NSISTREAMCONVERTER
// nsIStreamListener methods
NS_DECL_NSISTREAMLISTENER
// nsIStreamObserver methods
NS_DECL_NSISTREAMOBSERVER
nsUnknownDecoder();
protected:
virtual ~nsUnknownDecoder();
void DetermineContentType(nsIRequest* request);
nsresult FireListenerNotifications(nsIRequest* request, nsISupports *aCtxt);
protected:
nsCOMPtr<nsIStreamListener> mNextListener;
char *mBuffer;
PRUint32 mBufferLen;
PRBool mRequireHTMLsuffix;
nsCString mContentType;
};
#endif /* nsUnknownDecoder_h__ */

View File

@@ -1,35 +0,0 @@
#!gmake
#
# 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 = ..\..
MODULE = streamconv
DIRS= \
public \
src \
converters \
!if !defined(DISABLE_TESTS)
test \
!endif
$(NULL)
include <$(DEPTH)\config\rules.mak>

View File

@@ -1,40 +0,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):
#
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = necko
XPIDL_MODULE = necko_strconv
XPIDLSRCS = \
nsIStreamConverter.idl \
nsIStreamConverterService.idl \
mozITXTToHTMLConv.idl \
nsITXTToHTMLConv.idl \
$(NULL)
include $(topsrcdir)/config/rules.mk

View File

@@ -1,40 +0,0 @@
#!gmake
#
# 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):
MODULE = necko
XPIDL_MODULE = necko_strconv
DEPTH = ..\..\..
XPIDLSRCS = \
.\nsIStreamConverter.idl \
.\nsIStreamConverterService.idl \
.\mozITXTToHTMLConv.idl \
.\nsITXTToHTMLConv.idl \
$(NULL)
include <$(DEPTH)/config/rules.mak>
$(DEPTH)\netwerk\dist\include:
-mkdir $(DEPTH)\netwerk\dist
-mkdir $(DEPTH)\netwerk\dist\include

View File

@@ -1,104 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The "License" shall be the Mozilla Public License Version 1.1, except
* Sections 6.2 and 11, but with the addition of the below defined Section 14.
* You may obtain a copy of the Mozilla Public License Version 1.1 at
* <http://www.mozilla.org/MPL/>. The contents of this file are subject to the
* License; you may not use this file except in compliance with the License.
*
* Section 14: MISCELLANEOUS.
* This License represents the complete agreement concerning subject matter
* hereof. If any provision of this License is held to be unenforceable, such
* provision shall be reformed only to the extent necessary to make it
* enforceable. This License shall be governed by German law provisions. Any
* litigation relating to this License shall be subject to German jurisdiction.
*
* Once Covered Code has been published under a particular version of the
* License, You may always continue to use it under the terms of that version.
+ The Initial Developer and no one else has the right to modify the terms
* applicable to Covered Code created under this License.
* (End of Section 14)
*
* 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 the Text to HTML converter code.
*
* The Initial Developer of the Original Code is Ben Bucksch
* <http://www.bucksch.org>. Portions created by Ben Bucksch are Copyright
* (C) 1999, 2000 Ben Bucksch. All Rights Reserved.
*
* Contributor(s):
*/
/**
Description: Currently only functions to enhance plain text with HTML tags.
<p>
Wrapper class for various parsing routines, that convert plain text to HTML.
They try to recognize cites, URLs, plain text formattting like *bold* etc.
See <http://www.bucksch.org/1/projects/mozilla/16507/> for a description.
*/
#include "nsIStreamConverter.idl"
#include "nsrootidl.idl"
%{C++
// {77c0e42a-1dd2-11b2-8ebf-edc6606f2f4b}
#define MOZITXTTOHTMLCONV_CID \
{ 0x77c0e42a, 0x1dd2, 0x11b2, \
{ 0x8e, 0xbf, 0xed, 0xc6, 0x60, 0x6f, 0x2f, 0x4b } }
%}
[scriptable, uuid(77c0e42a-1dd2-11b2-8ebf-edc6606f2f4b)]
interface mozITXTToHTMLConv : nsIStreamConverter {
const unsigned long kURLs = 1 << 1;
const unsigned long kGlyphSubstitution = 1 << 2; // Smilies, &reg; etc.
const unsigned long kStructPhrase = 1 << 3; // E.g. *bold* -> <strong>
/**
@param text: plain text to scan. May be a line, paragraph (recommended)
or just a substring.<p>
Must be non-escaped, pure unicode.<p>
<em>Note:</em> ScanTXT(a, o) + ScanTXT(b, o) may be !=
Scan(a + b, o)
@param whattodo: Bitfield describing the modes of operation
@result "<", ">" and "&" are escaped and HTML tags are inserted where
appropriate.
*/
wstring scanTXT([const] in wstring text, in unsigned long whattodo);
/**
Adds additional formatting to user edited text, that the user was too lazy
or "unknowledged" (DELETEME: is that a word?) to make.
<p>
<em>Note:</em> Don't use kGlyphSubstitution with this function. This option
generates tags, that are unuseable for UAs other than Mozilla. This would
be a data loss bug.
@param text: HTML source to scan. May be a line, paragraph (recommended)
or just a substring.<p>
Must be correct HTML. "<", ">" and "&" must be escaped,
other chars must be pure unicode.<p>
<em>Note:</em> ScanTXT(a, o) + ScanTXT(b, o) may be !=
Scan(a + b, o)
@param whattodo: Bitfield describing the modes of operation
@result Additional HTML tags are inserted where appropriate.
*/
wstring scanHTML([const] in wstring text, in unsigned long whattodo);
/**
@param line: line in original msg, possibly starting starting with
txt quote tags like ">"
@param logLineStart: pos in line, where the real content (logical line)
begins, i.e. pos after all txt quote tags.
E.g. position of "t" in "> > text".
Initial value must be 0, unless line is not real line.
@return Cite Level, i.e. number of txt quote tags found, i.e. number of
nested quotes.
*/
unsigned long citeLevelTXT([const] in wstring line,
out unsigned long logLineStart);
};

View File

@@ -1,118 +0,0 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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): Jud Valeski
*/
#include "nsIStreamListener.idl"
#include "nsIInputStream.idl"
#include "nsIURI.idl"
/**
* nsIStreamConverter provides an interface to implement when you have code
* that converts data from one type to another.
*
* Suppose you had code that converted plain text into HTML. You could implement
* this interface to allow everyone else to use your conversion logic using a
* standard api.
* <p>
* <b>STREAM CONVERTER USERS</b>
*
* There are currently two ways to use a stream converter:
* <ol>
* <li> <b>SYNCHRONOUS</b> Stream to Stream
* You can supply the service with a stream of type X
* and it will convert it to your desired output type and return
* a converted (blocking) stream to you.</li>
*
* <li> <b>ASYNCHRONOUS</b> nsIStreamListener to nsIStreamListener
* You can supply data directly to the converter by calling it's
* nsIStreamListener::OnDataAvailable() method. It will then
* convert that data from type X to your desired output type and
* return converted data to you via the nsIStreamListener you passed
* in by calling its OnDataAvailable() method.</li>
* </ol>
* <p>
*
* <b>STREAM CONVERTER SUPPLIERS</b>
*
* Registering a stream converter:
* Stream converter registration is a two step process. First of all the stream
* converter implementation must register itself with the component manager using
* a contractid in the format below. Second, the stream converter must add the contractid
* to the registry.
*
* Stream converter contractid format (the stream converter root key is defined in this
* file):
*
* <pre>Software/Netscape/streamconv/?from=FROM_MIME_TYPE&to=TO_MIME_TYPE</pre>
*
* @author Jud Valeski
* @see nsIStreamConverterService
*/
[scriptable, uuid(46484B30-3BD2-11d3-A16C-0050041CAF44)]
interface nsIStreamConverter : nsIStreamListener {
/**
* <b>SYNCRONOUS VERSION</b>
* Converts a stream of one type, to a stream of another type.
*
* Use this method when you have a stream you want to convert.
*
* @param aFromStream The stream representing the original/raw data.
* @param aFromType The MIME type of aFromStream.
* @param aToType The MIME type of the returned stream.
* @param aCtxt Either an opaque context, or a converter specific context
* (implementation specific).
* @return The converted stream. NOTE: The returned stream may not
* already be converted. An efficient stream converter
* implementation will converter data on demand rather than
* buffering the converted data until it is used.
*/
nsIInputStream Convert(in nsIInputStream aFromStream,
in wstring aFromType,
in wstring aToType,
in nsISupports aCtxt);
/**
* <b>ASYNCRONOUS VERSION</b>
* Converts data arriving via the converter's nsIStreamListener::OnDataAvailable()
* method from one type to another, pushing the converted data out to the caller
* via aListener::OnDataAvailable().
*
* Use this method when you want to proxy (and convert) nsIStreamListener callbacks
* asynchronously.
*
* @param aFromType The MIME type of the original/raw data.
* @param aToType The MIME type of the converted data.
* @param aListener The listener who receives the converted data.
* @param aCtxt Either an opaque context, or a converter specific context
* (implementation specific).
*/
void AsyncConvertData(in wstring aFromType,
in wstring aToType,
in nsIStreamListener aListener,
in nsISupports aCtxt);
};
%{C++
#define NS_ISTREAMCONVERTER_KEY "@mozilla.org/streamconv;1"
%}

View File

@@ -1,94 +0,0 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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): Jud Valeski
*/
#include "nsIInputStream.idl"
#include "nsIStreamListener.idl"
/**
* The nsIStreamConverterService is a higher level stream converter factory
* responsible for locating and creating stream converters (nsIStreamConverter).
*
* This service retrieves an interface that can convert data from a particular MIME
* type, to a particular MIME type. It is responsible for any intermediary
* conversion required in order to get from X to Z, assuming direct conversion is not
* possible.
*
* @author Jud Valeski
* @see nsIStreamConverter
*/
%{C++
#define NS_STREAMCONVERTERSERVICE_CID \
{ /* 892FFEB0-3F80-11d3-A16C-0050041CAF44 */ \
0x892ffeb0, \
0x3f80, \
0x11d3, \
{0xa1, 0x6c, 0x00, 0x50, 0x04, 0x1c, 0xaf, 0x44} \
}
#define NS_ISTREAMCONVERTER_KEY "@mozilla.org/streamconv;1"
%}
[scriptable, uuid(00362090-3B97-11d3-A16C-0050041CAF44)]
interface nsIStreamConverterService : nsISupports {
/**
* <b>SYNCRONOUS VERSION</b>
* Converts a stream of one type, to a stream of another type.
*
* Use this method when you have a stream you want to convert.
*
* @param aFromStream The stream representing the original/raw data.
* @param aFromType The MIME type of aFromStream.
* @param aToType The MIME type of the returned stream.
* @param aContext Either an opaque context, or a converter specific context
* (implementation specific).
* @return The converted stream. NOTE: The returned stream may not
* already be converted. An efficient stream converter
* implementation will converter data on demand rather than
* buffering the converted data until it is used.
*/
nsIInputStream Convert(in nsIInputStream aFromStream,
in wstring aFromType,
in wstring aToType,
in nsISupports aContext);
/**
* <b>ASYNCRONOUS VERSION</b>
* Retrieves a nsIStreamListener that receives the original/raw data via its
* nsIStreamListener::OnDataAvailable() callback, then converts and pushes
* the data to aListener.
*
* Use this method when you want to proxy (and convert) nsIStreamListener callbacks
* asynchronously.
*
* @param aFromType The MIME type of the original/raw data.
* @param aToType The MIME type of the converted data.
* @param aListener The listener who receives the converted data.
* @param aCtxt Either an opaque context, or a converter specific context
* (implementation specific).
* @return A nsIStreamListener that receives data via its OnDataAvailable() method.
*/
nsIStreamListener AsyncConvertData(in wstring aFromType,
in wstring aToType,
in nsIStreamListener aListener,
in nsISupports aContext);
};

View File

@@ -1,42 +0,0 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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): Brian Ryner
*/
#include "nsIStreamConverter.idl"
#include "nsrootidl.idl"
[scriptable, uuid(933355f6-1dd2-11b2-a9b0-d335b9e35983)]
interface nsITXTToHTMLConv : nsIStreamConverter {
/**
@param text: Title to set for the HTML document. Only applicable if PreFormatHTML(true)
is called.
@result The given title will be used to form an HTML document from the plain text document.
*/
void SetTitle([const] in wstring text);
/**
@param value: true to use an HTML header and footer on the document, false to omit it.
@result The document will use a header and footer if vale = true.
*/
void PreFormatHTML(in boolean value);
};

View File

@@ -1,43 +0,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):
#
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = necko
LIBRARY_NAME = nkconv_s
REQUIRES = xpcom string
CPPSRCS = \
nsStreamConverterService.cpp \
$(NULL)
# we don't want the shared lib, but we want to force the creation of a
# static lib.
override NO_SHARED_LIB=1
override NO_STATIC_LIB=
include $(topsrcdir)/config/rules.mk

View File

@@ -1,40 +0,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):
DEPTH = ..\..\..
include <$(DEPTH)/config/config.mak>
MODULE = necko
LIBRARY_NAME=nkconv_s
LCFLAGS = -DWIN32_LEAN_AND_MEAN -D_IMPL_NS_NET
CPP_OBJS = \
.\$(OBJDIR)\nsStreamConverterService.obj \
$(NULL)
include <$(DEPTH)\config\rules.mak>
install:: $(LIBRARY)
$(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib
clobber::
rm -f $(DIST)\lib\$(LIBRARY_NAME).lib

View File

@@ -1,92 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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):
*/
#include "nsCOMPtr.h"
#include "nsIModule.h"
#include "nsIGenericFactory.h"
#include "nsIStreamConverterService.h"
#include "nsStreamConverterService.h"
static NS_DEFINE_CID(kStreamConvServiceCID, NS_STREAMCONVERTERSERVICE_CID);
nsresult NS_NewStreamConv(nsStreamConverterService** aStreamConv);
// Module implementation
class nsStreamConvModule : public nsIModule
{
public:
nsStreamConvModule();
virtual ~nsStreamConvModule();
NS_DECL_ISUPPORTS
NS_DECL_NSIMODULE
protected:
nsresult Initialize();
void Shutdown();
PRBool mInitialized;
nsCOMPtr<nsIGenericFactory> mStreamConvFactory;
};
//----------------------------------------------------------------------
// Functions used to create new instances of a given object by the
// generic factory.
static NS_IMETHODIMP
CreateNewStreamConv(nsISupports* aOuter, REFNSIID aIID, void **aResult)
{
if (!aResult) {
return NS_ERROR_INVALID_POINTER;
}
if (aOuter) {
*aResult = nsnull;
return NS_ERROR_NO_AGGREGATION;
}
nsStreamConverterService* inst = nsnull;
nsresult rv = NS_NewStreamConv(&inst);
if (NS_FAILED(rv)) {
*aResult = nsnull;
return rv;
}
rv = inst->QueryInterface(aIID, aResult);
if (NS_FAILED(rv)) {
*aResult = nsnull;
}
NS_RELEASE(inst); /* get rid of extra refcnt */
return rv;
}
static nsModuleComponentInfo components[] =
{
{ "Stream Converter Service",
NS_STREAMCONVERTERSERVICE_CID,
"@mozilla.org/streamConverters;1",
CreateNewStreamConv
},
};
NS_IMPL_NSGETMODULE("nsStreamConvModule", components);

View File

@@ -1,655 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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):
*
*
* This Original Code has been modified by IBM Corporation.
* Modifications made by IBM described herein are
* Copyright (c) International Business Machines
* Corporation, 2000
*
* Modifications to Mozilla code or documentation
* identified per MPL Section 3.3
*
* Date Modified by Description of modification
* 03/27/2000 IBM Corp. Added PR_CALLBACK for Optlink
* use in OS2
*/
#include "nsStreamConverterService.h"
#include "nsIServiceManager.h"
#include "nsIComponentManager.h"
#include "nsString2.h"
#include "nsIAtom.h"
#include "nsDeque.h"
#include "nsIInputStream.h"
#include "nsIOutputStream.h"
#include "nsIStreamConverter.h"
#include "nsICategoryManager.h"
#include "nsISupportsPrimitives.h"
#include "nsXPIDLString.h"
#include "nsCOMPtr.h"
////////////////////////////////////////////////////////////
// nsISupports methods
NS_IMPL_THREADSAFE_ISUPPORTS1(nsStreamConverterService, nsIStreamConverterService);
////////////////////////////////////////////////////////////
// nsIStreamConverterService methods
////////////////////////////////////////////////////////////
// nsStreamConverterService methods
nsStreamConverterService::nsStreamConverterService() {
NS_INIT_ISUPPORTS();
mAdjacencyList = nsnull;
}
// Delete all the entries in the adjacency list
static PRBool PR_CALLBACK DeleteAdjacencyEntry(nsHashKey *aKey, void *aData, void* closure) {
SCTableData *entry = (SCTableData*)aData;
NS_ASSERTION(entry->key && entry->data, "malformed adjacency list entry");
delete entry->key;
// clear out the edges
nsVoidArray *edges = (nsVoidArray*)entry->data;
nsIAtom *vertex;
while ( (vertex = (nsIAtom*)edges->ElementAt(0)) ) {
NS_RELEASE(vertex);
edges->RemoveElementAt(0);
}
delete (nsVoidArray *)entry->data;
delete entry;
return PR_TRUE;
};
nsStreamConverterService::~nsStreamConverterService() {
// Clean up the adjacency list table.
mAdjacencyList->Reset(DeleteAdjacencyEntry, nsnull);
delete mAdjacencyList;
}
nsresult
nsStreamConverterService::Init() {
mAdjacencyList = new nsHashtable();
if (!mAdjacencyList) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
// Builds the graph represented as an adjacency list (and built up in
// memory using an nsHashtable and nsVoidArray combination).
//
// :BuildGraph() consults the category manager for all stream converter
// CONTRACTIDS then fills the adjacency list with edges.
// An edge in this case is comprised of a FROM and TO MIME type combination.
//
// CONTRACTID format:
// @mozilla.org/streamconv;1?from=text/html&to=text/plain
// XXX curently we only handle a single from and to combo, we should repeat the
// XXX registration process for any series of from-to combos.
// XXX can use nsTokenizer for this.
//
nsresult
nsStreamConverterService::BuildGraph() {
nsresult rv;
nsCOMPtr<nsICategoryManager> catmgr(do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsISimpleEnumerator> entries;
rv = catmgr->EnumerateCategory(NS_ISTREAMCONVERTER_KEY, getter_AddRefs(entries));
if (NS_FAILED(rv)) return rv;
// go through each entry to build the graph
nsCOMPtr<nsISupportsString> entry;
rv = entries->GetNext(getter_AddRefs(entry));
while (NS_SUCCEEDED(rv)) {
// get the entry string
nsXPIDLCString entryString;
rv = entry->GetData(getter_Copies(entryString));
if (NS_FAILED(rv)) return rv;
// cobble the entry string w/ the converter key to produce a full contractID.
nsCString contractID(NS_ISTREAMCONVERTER_KEY);
contractID.Append((const char *)entryString);
// now we've got the CONTRACTID, let's parse it up.
rv = AddAdjacency(contractID.get());
if (NS_FAILED(rv)) return rv;
rv = entries->GetNext(getter_AddRefs(entry));
}
return NS_OK;
}
// XXX currently you can not add the same adjacency (i.e. you can't have multiple
// XXX stream converters registering to handle the same from-to combination. It's
// XXX not programatically prohibited, it's just that results are un-predictable
// XXX right now.
nsresult
nsStreamConverterService::AddAdjacency(const char *aContractID) {
nsresult rv;
// first parse out the FROM and TO MIME-types.
nsCString fromStr, toStr;
rv = ParseFromTo(aContractID, fromStr, toStr);
if (NS_FAILED(rv)) return rv;
// Each MIME-type is a vertex in the graph, so first lets make sure
// each MIME-type is represented as a key in our hashtable.
nsCStringKey *fromKey = new nsCStringKey(fromStr.get(), -1, nsCStringKey::OWN);
if (!fromKey) return NS_ERROR_OUT_OF_MEMORY;
SCTableData *edges = (SCTableData*)mAdjacencyList->Get(fromKey);
if (!edges) {
// There is no fromStr vertex, create one.
SCTableData *data = new SCTableData;
if (!data) {
delete fromKey;
return NS_ERROR_OUT_OF_MEMORY;
}
data->key = fromKey;
data->data = new nsVoidArray();
if (!data->data) {
delete fromKey;
delete data;
return NS_ERROR_OUT_OF_MEMORY;
}
mAdjacencyList->Put(fromKey, data);
} else {
delete fromKey;
}
nsCStringKey *toKey = new nsCStringKey(toStr.get(), -1, nsCStringKey::OWN);
if (!toKey) return NS_ERROR_OUT_OF_MEMORY;
edges = (SCTableData*)mAdjacencyList->Get(toKey);
if (!edges) {
// There is no toStr vertex, create one.
SCTableData *data = new SCTableData;
if (!data) {
delete toKey;
return NS_ERROR_OUT_OF_MEMORY;
}
data->key = toKey;
data->data = new nsVoidArray();
if (!data->data) {
delete toKey;
delete data;
return NS_ERROR_OUT_OF_MEMORY;
}
mAdjacencyList->Put(toKey, data);
} else {
delete toKey;
}
// Now we know the FROM and TO types are represented as keys in the hashtable.
// Let's "connect" the verticies, making an edge.
edges = (SCTableData*)mAdjacencyList->Get(fromKey);
NS_ASSERTION(edges, "something wrong in adjacency list construction");
const char *toCStr = toStr.get();
nsIAtom *vertex = NS_NewAtom(toCStr);
if (!vertex) return NS_ERROR_OUT_OF_MEMORY;
nsVoidArray *adjacencyList = (nsVoidArray*)edges->data;
rv = adjacencyList->AppendElement(vertex) ? NS_OK : NS_ERROR_FAILURE; // XXX this method incorrectly returns a bool
return rv;
}
nsresult
nsStreamConverterService::ParseFromTo(const char *aContractID, nsCString &aFromRes, nsCString &aToRes) {
nsCString ContractIDStr(aContractID);
PRInt32 fromLoc = ContractIDStr.Find("from=") + 5;
PRInt32 toLoc = ContractIDStr.Find("to=") + 3;
if (-1 == fromLoc || -1 == toLoc ) return NS_ERROR_FAILURE;
nsCString fromStr, toStr;
ContractIDStr.Mid(fromStr, fromLoc, toLoc - 4 - fromLoc);
ContractIDStr.Mid(toStr, toLoc, ContractIDStr.Length() - toLoc);
aFromRes.Assign(fromStr);
aToRes.Assign(toStr);
return NS_OK;
}
// nsHashtable enumerator functions.
// Initializes the BFS state table.
static PRBool PR_CALLBACK InitBFSTable(nsHashKey *aKey, void *aData, void* closure) {
nsHashtable *BFSTable = (nsHashtable*)closure;
if (!BFSTable) return PR_FALSE;
BFSState *state = new BFSState;
if (!state) return NS_ERROR_OUT_OF_MEMORY;
state->color = white;
state->distance = -1;
state->predecessor = nsnull;
SCTableData *data = new SCTableData;
if (!data) return NS_ERROR_OUT_OF_MEMORY;
data->key = (nsCStringKey*)aKey->Clone();
SCTableData *origData = (SCTableData*)aData;
NS_ASSERTION(origData, "no data in the table enumeration");
data->data = state;
BFSTable->Put(aKey, data);
return PR_TRUE;
};
// cleans up the BFS state table
static PRBool PR_CALLBACK DeleteBFSEntry(nsHashKey *aKey, void *aData, void *closure) {
SCTableData *data = (SCTableData*)aData;
delete data->key;
BFSState *state = (BFSState*)data->data;
if (state->predecessor) // there might not be a predecessor depending on the graph
delete state->predecessor;
delete state;
delete data;
return PR_TRUE;
}
// walks the graph using a breadth-first-search algorithm which generates a discovered
// verticies tree. This tree is then walked up (from destination vertex, to origin vertex)
// and each link in the chain is added to an nsStringArray. A direct lookup for the given
// CONTRACTID should be made prior to calling this method in an attempt to find a direct
// converter rather than walking the graph.
nsresult
nsStreamConverterService::FindConverter(const char *aContractID, nsCStringArray **aEdgeList) {
nsresult rv;
if (!aEdgeList) return NS_ERROR_NULL_POINTER;
// walk the graph in search of the appropriate converter.
PRInt32 vertexCount = mAdjacencyList->Count();
if (0 >= vertexCount) return NS_ERROR_FAILURE;
// Create a corresponding color table for each vertex in the graph.
nsHashtable lBFSTable;
mAdjacencyList->Enumerate(InitBFSTable, &lBFSTable);
NS_ASSERTION(lBFSTable.Count() == vertexCount, "strmconv BFS table init problem");
// This is our source vertex; our starting point.
nsCString fromC, toC;
rv = ParseFromTo(aContractID, fromC, toC);
if (NS_FAILED(rv)) return rv;
nsCStringKey source(fromC.get());
SCTableData *data = (SCTableData*)lBFSTable.Get(&source);
if (!data) return NS_ERROR_FAILURE;
BFSState *state = (BFSState*)data->data;
state->color = gray;
state->distance = 0;
nsDeque grayQ(0);
// Now generate the shortest path tree.
grayQ.Push(&source);
while (0 < grayQ.GetSize()) {
nsHashKey *currentHead = (nsHashKey*)grayQ.PeekFront();
SCTableData *data2 = (SCTableData*)mAdjacencyList->Get(currentHead);
if (!data2) return NS_ERROR_FAILURE;
nsVoidArray *edges = (nsVoidArray*)data2->data;
NS_ASSERTION(edges, "something went wrong with BFS strmconv algorithm");
// Get the state of the current head to calculate the distance of each
// reachable vertex in the loop.
data2 = (SCTableData*)lBFSTable.Get(currentHead);
BFSState *headVertexState = (BFSState*)data2->data;
NS_ASSERTION(headVertexState, "problem with the BFS strmconv algorithm");
PRInt32 edgeCount = edges->Count();
for (int i = 0; i < edgeCount; i++) {
nsIAtom *curVertexAtom = (nsIAtom*)edges->ElementAt(i);
nsAutoString curVertexStr;
curVertexAtom->ToString(curVertexStr);
nsCStringKey *curVertex = new nsCStringKey(curVertexStr.GetBuffer(), -1, nsCStringKey::OWN);
SCTableData *data3 = (SCTableData*)lBFSTable.Get(curVertex);
BFSState *curVertexState = (BFSState*)data3->data;
NS_ASSERTION(curVertexState, "something went wrong with the BFS strmconv algorithm");
if (white == curVertexState->color) {
curVertexState->color = gray;
curVertexState->distance = headVertexState->distance + 1;
curVertexState->predecessor = currentHead->Clone();
grayQ.Push(curVertex);
} else {
delete curVertex; // if this vertex has already been discovered, we don't want
// to leak it. (non-discovered vertex's get cleaned up when
// they're popped).
}
}
headVertexState->color = black;
nsCStringKey *cur = (nsCStringKey*)grayQ.PopFront();
delete cur;
cur = nsnull;
}
// The shortest path (if any) has been generated and is represetned by the chain of
// BFSState->predecessor keys. Start at the bottom and work our way up.
// first parse out the FROM and TO MIME-types being registered.
nsCString fromStr, toStr;
rv = ParseFromTo(aContractID, fromStr, toStr);
if (NS_FAILED(rv)) return rv;
// get the root CONTRACTID
nsCString ContractIDPrefix(NS_ISTREAMCONVERTER_KEY);
nsCStringArray *shortestPath = new nsCStringArray();
nsCStringKey toMIMEType(toStr);
data = (SCTableData*)lBFSTable.Get(&toMIMEType);
if (!data) {
// If this vertex isn't in the BFSTable, then no-one has registered for it,
// therefore we can't do the conversion.
*aEdgeList = nsnull;
return NS_ERROR_FAILURE;
}
while (data) {
BFSState *curState = (BFSState*)data->data;
nsCStringKey *key = (nsCStringKey*)data->key;
if (fromStr.Equals(key->GetString())) {
// found it. We're done here.
*aEdgeList = shortestPath;
lBFSTable.Reset(DeleteBFSEntry, nsnull);
return NS_OK;
}
// reconstruct the CONTRACTID.
// Get the predecessor.
SCTableData *predecessorData = (SCTableData*)lBFSTable.Get(curState->predecessor);
if (!predecessorData) break; // no predecessor, chain doesn't exist.
// build out the CONTRACTID.
nsCString *newContractID = new nsCString(ContractIDPrefix);
newContractID->Append("?from=");
nsCStringKey *predecessoryKey = (nsCStringKey*)predecessorData->key;
newContractID->Append(key->GetString());
newContractID->Append("&to=");
newContractID->Append(key->GetString());
// Add this CONTRACTID to the chain.
rv = shortestPath->AppendCString(*newContractID) ? NS_OK : NS_ERROR_FAILURE; // XXX this method incorrectly returns a bool
NS_ASSERTION(NS_SUCCEEDED(rv), "AppendElement failed");
// move up the tree.
data = predecessorData;
}
lBFSTable.Reset(DeleteBFSEntry, nsnull);
*aEdgeList = nsnull;
return NS_ERROR_FAILURE; // couldn't find a stream converter or chain.
}
/////////////////////////////////////////////////////
// nsIStreamConverter methods
NS_IMETHODIMP
nsStreamConverterService::Convert(nsIInputStream *aFromStream,
const PRUnichar *aFromType,
const PRUnichar *aToType,
nsISupports *aContext,
nsIInputStream **_retval) {
if (!aFromStream || !aFromType || !aToType || !_retval) return NS_ERROR_NULL_POINTER;
nsresult rv;
// first determine whether we can even handle this covnversion
// build a CONTRACTID
nsCString contractID(NS_ISTREAMCONVERTER_KEY);
contractID.Append("?from=");
contractID.AppendWithConversion(aFromType);
contractID.Append("&to=");
contractID.AppendWithConversion(aToType);
const char *cContractID = contractID.get();
nsIComponentManager *comMgr;
rv = NS_GetGlobalComponentManager(&comMgr);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIStreamConverter> converter(do_CreateInstance(cContractID, &rv));
if (NS_FAILED(rv)) {
// couldn't go direct, let's try walking the graph of converters.
rv = BuildGraph();
if (NS_FAILED(rv)) return rv;
nsCStringArray *converterChain = nsnull;
rv = FindConverter(cContractID, &converterChain);
if (NS_FAILED(rv)) {
// can't make this conversion.
// XXX should have a more descriptive error code.
return NS_ERROR_FAILURE;
}
PRInt32 edgeCount = converterChain->Count();
NS_ASSERTION(edgeCount > 0, "findConverter should have failed");
// convert the stream using each edge of the graph as a step.
// this is our stream conversion traversal.
nsCOMPtr<nsIInputStream> dataToConvert = aFromStream;
nsCOMPtr<nsIInputStream> convertedData;
for (PRInt32 i = edgeCount-1; i >= 0; i--) {
nsCString *contractIDStr = converterChain->CStringAt(i);
if (!contractIDStr) {
delete converterChain;
return NS_ERROR_FAILURE;
}
const char *lContractID = contractIDStr->get();
converter = do_CreateInstance(lContractID, &rv);
if (NS_FAILED(rv)) {
delete converterChain;
return rv;
}
nsCString fromStr, toStr;
rv = ParseFromTo(lContractID, fromStr, toStr);
if (NS_FAILED(rv)) {
delete converterChain;
return rv;
}
PRUnichar *fromUni = fromStr.ToNewUnicode();
if (!fromUni) {
delete converterChain;
return NS_ERROR_OUT_OF_MEMORY;
}
PRUnichar *toUni = toStr.ToNewUnicode();
if (!toUni) {
delete fromUni;
delete converterChain;
return NS_ERROR_OUT_OF_MEMORY;
}
rv = converter->Convert(dataToConvert, fromUni, toUni, aContext, getter_AddRefs(convertedData));
nsMemory::Free(fromUni);
nsMemory::Free(toUni);
dataToConvert = convertedData;
if (NS_FAILED(rv)) {
delete converterChain;
return rv;
}
}
delete converterChain;
*_retval = convertedData;
NS_ADDREF(*_retval);
} else {
// we're going direct.
rv = converter->Convert(aFromStream, aFromType, aToType, aContext, _retval);
}
return rv;
}
NS_IMETHODIMP
nsStreamConverterService::AsyncConvertData(const PRUnichar *aFromType,
const PRUnichar *aToType,
nsIStreamListener *aListener,
nsISupports *aContext,
nsIStreamListener **_retval) {
if (!aFromType || !aToType || !aListener || !_retval) return NS_ERROR_NULL_POINTER;
nsresult rv;
// first determine whether we can even handle this covnversion
// build a CONTRACTID
nsCString contractID(NS_ISTREAMCONVERTER_KEY);
contractID.Append("?from=");
contractID.AppendWithConversion(aFromType);
contractID.Append("&to=");
contractID.AppendWithConversion(aToType);
const char *cContractID = contractID.get();
nsIComponentManager *comMgr;
rv = NS_GetGlobalComponentManager(&comMgr);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIStreamConverter> listener(do_CreateInstance(cContractID, &rv));
if (NS_FAILED(rv)) {
// couldn't go direct, let's try walking the graph of converters.
rv = BuildGraph();
if (NS_FAILED(rv)) return rv;
nsCStringArray *converterChain = nsnull;
rv = FindConverter(cContractID, &converterChain);
if (NS_FAILED(rv)) {
// can't make this conversion.
// XXX should have a more descriptive error code.
return NS_ERROR_FAILURE;
}
PRInt32 edgeCount = converterChain->Count();
NS_ASSERTION(edgeCount > 0, "findConverter should have failed");
// convert the stream using each edge of the graph as a step.
// this is our stream conversion traversal.
nsCOMPtr<nsIStreamListener> forwardListener = aListener;
nsCOMPtr<nsIStreamListener> fromListener;
for (int i = 0; i < edgeCount; i++) {
nsCString *contractIDStr = converterChain->CStringAt(i);
if (!contractIDStr) {
delete converterChain;
return NS_ERROR_FAILURE;
}
const char *lContractID = contractIDStr->get();
nsCOMPtr<nsIStreamConverter> converter(do_CreateInstance(lContractID, &rv));
NS_ASSERTION(NS_SUCCEEDED(rv), "graph construction problem, built a contractid that wasn't registered");
nsCString fromStr, toStr;
rv = ParseFromTo(lContractID, fromStr, toStr);
if (NS_FAILED(rv)) {
delete converterChain;
return rv;
}
PRUnichar *fromStrUni = fromStr.ToNewUnicode();
if (!fromStrUni) {
delete converterChain;
return NS_ERROR_OUT_OF_MEMORY;
}
PRUnichar *toStrUni = toStr.ToNewUnicode();
if (!toStrUni) {
delete fromStrUni;
delete converterChain;
return NS_ERROR_OUT_OF_MEMORY;
}
rv = converter->AsyncConvertData(fromStrUni, toStrUni, forwardListener, aContext);
nsMemory::Free(fromStrUni);
nsMemory::Free(toStrUni);
if (NS_FAILED(rv)) {
delete converterChain;
return rv;
}
nsCOMPtr<nsIStreamListener> chainListener(do_QueryInterface(converter, &rv));
if (NS_FAILED(rv)) {
delete converterChain;
return rv;
}
// store the listener of the first converter in the chain.
if (!fromListener)
fromListener = chainListener;
forwardListener = chainListener;
}
delete converterChain;
// return the first listener in the chain.
*_retval = fromListener;
NS_ADDREF(*_retval);
} else {
// we're going direct.
*_retval = listener;
NS_ADDREF(*_retval);
rv = listener->AsyncConvertData(aFromType, aToType, aListener, aContext);
}
return rv;
}
nsresult
NS_NewStreamConv(nsStreamConverterService** aStreamConv)
{
NS_PRECONDITION(aStreamConv != nsnull, "null ptr");
if (!aStreamConv) return NS_ERROR_NULL_POINTER;
*aStreamConv = new nsStreamConverterService();
if (!*aStreamConv) return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(*aStreamConv);
return (*aStreamConv)->Init();
}

View File

@@ -1,79 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* 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):
*/
#ifndef __nsstreamconverterservice__h___
#define __nsstreamconverterservice__h___
#include "nsIStreamConverterService.h"
#include "nsIStreamListener.h"
#include "nsHashtable.h"
#include "nsVoidArray.h"
class nsStreamConverterService : public nsIStreamConverterService {
public:
/////////////////////////////////////////////////////
// nsISupports methods
NS_DECL_ISUPPORTS
/////////////////////////////////////////////////////
// nsIStreamConverterService methods
NS_DECL_NSISTREAMCONVERTERSERVICE
/////////////////////////////////////////////////////
// nsStreamConverterService methods
nsStreamConverterService();
virtual ~nsStreamConverterService();
// Initialization routine. Must be called after this object is constructed.
nsresult Init();
private:
// Responsible for finding a converter for the given MIME-type.
nsresult FindConverter(const char *aContractID, nsCStringArray **aEdgeList);
nsresult BuildGraph(void);
nsresult AddAdjacency(const char *aContractID);
nsresult ParseFromTo(const char *aContractID, nsCString &aFromRes, nsCString &aToRes);
// member variables
nsHashtable *mAdjacencyList;
};
///////////////////////////////////////////////////////////////////
// Breadth-First-Search (BFS) algorithm state classes and types.
// adjacency list and BFS hashtable data class.
typedef struct _tableData {
nsCStringKey *key;
void *data;
} SCTableData;
// used to establish discovered vertecies.
enum BFScolors {white, gray, black};
typedef struct _BFSState {
BFScolors color;
PRInt32 distance;
nsHashKey *predecessor;
} BFSState;
#endif // __nsstreamconverterservice__h___

View File

@@ -1,165 +0,0 @@
#include "Converters.h"
#include "nsIStringStream.h"
//////////////////////////////////////////////////
// TestConverter
//////////////////////////////////////////////////
NS_IMPL_ISUPPORTS2(TestConverter, nsIStreamConverter, nsIStreamListener);
TestConverter::TestConverter() {
NS_INIT_ISUPPORTS();
}
// Convert aFromStream (of type aFromType), to _retval (nsIInputStream of type aToType).
// This Convert method simply converts the stream byte-by-byte, to the first character
// in the aToType "string".
NS_IMETHODIMP
TestConverter::Convert(nsIInputStream *aFromStream,
const PRUnichar *aFromType,
const PRUnichar *aToType,
nsISupports *ctxt,
nsIInputStream **_retval) {
char buf[1024];
PRUint32 read;
nsresult rv = aFromStream->Read(buf, 1024, &read);
if (NS_FAILED(rv) || read == 0) return rv;
// Get the first character
nsString to(aToType);
char *toMIME = to.ToNewCString();
char toChar = *toMIME;
nsMemory::Free(toMIME);
for (PRUint32 i = 0; i < read; i++)
buf[i] = toChar;
nsString convDataStr;
convDataStr.AssignWithConversion(buf);
nsIInputStream *inputData = nsnull;
nsISupports *inputDataSup = nsnull;
rv = NS_NewStringInputStream(&inputDataSup, convDataStr);
if (NS_FAILED(rv)) return rv;
rv = inputDataSup->QueryInterface(NS_GET_IID(nsIInputStream), (void**)&inputData);
NS_RELEASE(inputDataSup);
*_retval = inputData;
if (NS_FAILED(rv)) return rv;
return NS_OK;
}
/* This method initializes any internal state before the stream converter
* begins asyncronous conversion */
NS_IMETHODIMP
TestConverter::AsyncConvertData(const PRUnichar *aFromType,
const PRUnichar *aToType,
nsIStreamListener *aListener,
nsISupports *ctxt) {
NS_ASSERTION(aListener, "null listener");
mListener = aListener;
NS_ADDREF(mListener);
// based on these types, setup internal state to handle the appropriate conversion.
fromType = aFromType;
toType = aToType;
return NS_OK;
};
// nsIStreamListener method
/* This method handles asyncronous conversion of data. */
NS_IMETHODIMP
TestConverter::OnDataAvailable(nsIRequest* request,
nsISupports *ctxt,
nsIInputStream *inStr,
PRUint32 sourceOffset,
PRUint32 count) {
nsresult rv;
nsIInputStream *convertedStream = nsnull;
// just make a syncronous call to the Convert() method.
// Anything can happen here, I just happen to be using the sync call to
// do the actual conversion.
rv = Convert(inStr, fromType.GetUnicode(), toType.GetUnicode(), ctxt, &convertedStream);
if (NS_FAILED(rv)) return rv;
PRUint32 len;
convertedStream->Available(&len);
return mListener->OnDataAvailable(request, ctxt, convertedStream, sourceOffset, len);
};
// nsIStreamObserver methods
/* These methods just pass through directly to the mListener */
NS_IMETHODIMP
TestConverter::OnStartRequest(nsIRequest* request, nsISupports *ctxt) {
return mListener->OnStartRequest(request, ctxt);
};
NS_IMETHODIMP
TestConverter::OnStopRequest(nsIRequest* request, nsISupports *ctxt,
nsresult aStatus, const PRUnichar* aStatusArg) {
return mListener->OnStopRequest(request, ctxt, aStatus, aStatusArg);
};
////////////////////////////////////////////////////////////////////////
// TestConverterFactory
////////////////////////////////////////////////////////////////////////
TestConverterFactory::TestConverterFactory(const nsCID &aClass,
const char* className,
const char* contractID)
: mClassID(aClass), mClassName(className), mContractID(contractID)
{
NS_INIT_ISUPPORTS();
}
TestConverterFactory::~TestConverterFactory()
{
}
NS_IMPL_ISUPPORTS1(TestConverterFactory, nsIFactory)
NS_IMETHODIMP
TestConverterFactory::CreateInstance(nsISupports *aOuter,
const nsIID &aIID,
void **aResult)
{
if (! aResult)
return NS_ERROR_NULL_POINTER;
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
*aResult = nsnull;
nsresult rv = NS_OK;
nsISupports *inst = nsnull;
if (mClassID.Equals(kTestConverterCID)) {
TestConverter *conv = new TestConverter();
if (!conv) return NS_ERROR_OUT_OF_MEMORY;
conv->QueryInterface(NS_GET_IID(nsISupports), (void**)&inst);
}
else {
return NS_ERROR_NO_INTERFACE;
}
if (!inst)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(inst);
*aResult = inst;
NS_RELEASE(inst);
return rv;
}
nsresult TestConverterFactory::LockFactory(PRBool aLock)
{
// Not implemented in simplest case.
return NS_OK;
}
////////////////////////////////////////////////////////////////////////
// TestConverterFactory END
////////////////////////////////////////////////////////////////////////

View File

@@ -1,68 +0,0 @@
#include "nsIStreamConverter.h"
#include "nsString.h"
#include "nsIFactory.h"
/* This file defines stream converter components, and their accompanying factory class.
* These converters implement the nsIStreamConverter interface and support both
* asyncronous and syncronous stream conversion.
*/
///////////////////////////////////////////////
// TestConverter
#define NS_TESTCONVERTER_CID \
{ /* B8A067B0-4450-11d3-A16E-0050041CAF44 */ \
0xb8a067b0, \
0x4450, \
0x11d3, \
{0xa1, 0x6e, 0x00, 0x50, 0x04, 0x1c, 0xaf, 0x44} \
}
static NS_DEFINE_CID(kTestConverterCID, NS_TESTCONVERTER_CID);
class TestConverter : public nsIStreamConverter {
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISTREAMOBSERVER
NS_DECL_NSISTREAMLISTENER
TestConverter();
virtual ~TestConverter() {;};
// nsIStreamConverter methods
NS_IMETHOD Convert(nsIInputStream *aFromStream, const PRUnichar *aFromType,
const PRUnichar *aToType, nsISupports *ctxt, nsIInputStream **_retval);
NS_IMETHOD AsyncConvertData(const PRUnichar *aFromType, const PRUnichar *aToType,
nsIStreamListener *aListener, nsISupports *ctxt);
// member data
nsIStreamListener *mListener;
nsString fromType;
nsString toType;
};
//////////////////////////////////////////////////
// FACTORY
class TestConverterFactory : public nsIFactory
{
public:
TestConverterFactory(const nsCID &aClass, const char* className, const char* contractID);
// nsISupports methods
NS_DECL_ISUPPORTS
// nsIFactory methods
NS_IMETHOD CreateInstance(nsISupports *aOuter,
const nsIID &aIID,
void **aResult);
NS_IMETHOD LockFactory(PRBool aLock);
protected:
virtual ~TestConverterFactory();
protected:
nsCID mClassID;
const char* mClassName;
const char* mContractID;
};

View File

@@ -1,51 +0,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):
#
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = TestStreamConv
PROGRAM = TestStreamConv$(BIN_SUFFIX)
REQUIRES = necko xpcom string
CPPSRCS = \
Converters.cpp \
TestStreamConv.cpp \
$(NULL)
ifdef NO_LD_ARCHIVE_FLAGS
LOST_SYM_LIBS = -lxpcomds_s -lxptinfo -lmozreg_s
endif
LIBS = \
$(XPCOM_LIBS) \
$(LOST_SYM_LIBS) \
$(NSPR_LIBS) \
$(NULL)
include $(topsrcdir)/config/rules.mk
DEFINES += -DUSE_NSREG

View File

@@ -1,291 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsIServiceManager.h"
#include "nsIComponentManager.h"
#include "nsIStreamConverterService.h"
#include "nsIStreamConverter.h"
#include "nsICategoryManager.h"
#include "nsIFactory.h"
#include "nsIStringStream.h"
#include "nsCOMPtr.h"
#include "nsNetUtil.h"
#include "nspr.h"
#define ASYNC_TEST // undefine this if you want to test sycnronous conversion.
/////////////////////////////////
// Event pump setup
/////////////////////////////////
#include "nsIEventQueueService.h"
#ifdef WIN32
#include <windows.h>
#endif
#ifdef XP_OS2
#include <os2.h>
#endif
static int gKeepRunning = 0;
static nsIEventQueue* gEventQ = nsnull;
/////////////////////////////////
// Event pump END
/////////////////////////////////
/////////////////////////////////
// Test converters include
/////////////////////////////////
#include "Converters.h"
// CID setup
static NS_DEFINE_CID(kEventQueueServiceCID, NS_EVENTQUEUESERVICE_CID);
static NS_DEFINE_CID(kStreamConverterServiceCID, NS_STREAMCONVERTERSERVICE_CID);
static NS_DEFINE_CID(kComponentManagerCID, NS_COMPONENTMANAGER_CID);
////////////////////////////////////////////////////////////////////////
// EndListener - This listener is the final one in the chain. It
// receives the fully converted data, although it doesn't do anything with
// the data.
////////////////////////////////////////////////////////////////////////
class EndListener : public nsIStreamListener {
public:
// nsISupports declaration
NS_DECL_ISUPPORTS
EndListener() {NS_INIT_ISUPPORTS();};
// nsIStreamListener method
NS_IMETHOD OnDataAvailable(nsIRequest* request, nsISupports *ctxt, nsIInputStream *inStr,
PRUint32 sourceOffset, PRUint32 count)
{
nsresult rv;
PRUint32 read, len;
rv = inStr->Available(&len);
if (NS_FAILED(rv)) return rv;
char *buffer = (char*)nsMemory::Alloc(len + 1);
if (!buffer) return NS_ERROR_OUT_OF_MEMORY;
rv = inStr->Read(buffer, len, &read);
buffer[len] = '\0';
if (NS_SUCCEEDED(rv)) {
printf("CONTEXT %p: Received %u bytes and the following data: \n %s\n\n", ctxt, read, buffer);
}
nsMemory::Free(buffer);
return NS_OK;
}
// nsIStreamObserver methods
NS_IMETHOD OnStartRequest(nsIRequest* request, nsISupports *ctxt) { return NS_OK; }
NS_IMETHOD OnStopRequest(nsIRequest* request, nsISupports *ctxt,
nsresult aStatus, const PRUnichar* aStatusArg) { return NS_OK; }
};
NS_IMPL_ISUPPORTS1(EndListener, nsIStreamListener);
////////////////////////////////////////////////////////////////////////
// EndListener END
////////////////////////////////////////////////////////////////////////
nsresult SendData(const char * aData, nsIStreamListener* aListener, nsIRequest* request) {
nsString data;
data.AssignWithConversion(aData);
nsCOMPtr<nsIInputStream> dataStream;
nsresult rv = NS_NewStringInputStream(getter_AddRefs(dataStream), data);
if (NS_FAILED(rv)) return rv;
return aListener->OnDataAvailable(request, nsnull, dataStream, 0, -1);
}
#define SEND_DATA(x) SendData(x, converterListener, request)
int
main(int argc, char* argv[])
{
nsresult rv;
// Create the Event Queue for this thread...
NS_WITH_SERVICE(nsIEventQueueService, eventQService, kEventQueueServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
rv = eventQService->CreateThreadEventQueue();
if (NS_FAILED(rv)) return rv;
eventQService->GetThreadEventQueue(NS_CURRENT_THREAD, &gEventQ);
rv = nsComponentManager::AutoRegister(nsIComponentManager::NS_Startup, NULL /* default */);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsICategoryManager> catman =
do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
nsXPIDLCString previous;
///////////////////////////////////////////
// BEGIN - Stream converter registration
// All stream converters must register with the ComponentManager
///////////////////////////////////////////
// these stream converters are just for testing. running this harness
// from the dist/bin dir will also pickup converters registered
// in other modules (necko converters for example).
char *converterList[] = {
"?from=a/foo&to=b/foo",
"?from=b/foo&to=c/foo",
"?from=b/foo&to=d/foo",
"?from=c/foo&to=d/foo",
"?from=d/foo&to=e/foo",
"?from=d/foo&to=f/foo",
"?from=t/foo&to=k/foo"
};
TestConverterFactory *convFactory = new TestConverterFactory(kTestConverterCID, "TestConverter", NS_ISTREAMCONVERTER_KEY);
nsCOMPtr<nsIFactory> convFactSup(do_QueryInterface(convFactory, &rv));
if (NS_FAILED(rv)) return rv;
rv = catman->AddCategoryEntry(NS_ISTREAMCONVERTER_KEY, "?from=a/foo&to=b/foo", "x",
PR_TRUE, PR_TRUE, getter_Copies(previous));
if (NS_FAILED(rv)) return rv;
PRUint32 count = 0;
while (count < sizeof(converterList)) {
// register the TestConverter with the component manager. One contractid registration
// per conversion pair (from - to pair).
nsCString contractID(NS_ISTREAMCONVERTER_KEY);
contractID.Append(converterList[count]);
rv = nsComponentManager::RegisterFactory(kTestConverterCID,
"TestConverter",
contractID.get(),
convFactSup,
PR_TRUE);
if (NS_FAILED(rv)) return rv;
rv = catman->AddCategoryEntry(NS_ISTREAMCONVERTER_KEY, converterList[count], nsnull,
PR_TRUE, PR_TRUE, getter_Copies(previous));
if (NS_FAILED(rv)) return rv;
}
NS_WITH_SERVICE(nsIStreamConverterService, StreamConvService, kStreamConverterServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
// Define the *from* content type and *to* content-type for conversion.
nsString fromStr;
fromStr.AssignWithConversion("a/foo");
nsString toStr;
toStr.AssignWithConversion("c/foo");
#ifdef ASYNC_TEST
// ASYNCRONOUS conversion
// Build up a channel that represents the content we're
// starting the transaction with.
//
// sample multipart mixed content-type string:
// "multipart/x-mixed-replacE;boundary=thisrandomstring"
nsCOMPtr<nsIChannel> channel;
nsCOMPtr<nsIURI> dummyURI;
rv = NS_NewURI(getter_AddRefs(dummyURI), "http://meaningless");
if (NS_FAILED(rv)) return rv;
rv = NS_NewInputStreamChannel(getter_AddRefs(channel),
dummyURI,
nsnull, // inStr
"text/plain", // content-type
-1); // XXX fix contentLength
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIRequest> request(do_QueryInterface(channel));
// setup a listener to receive the converted data. This guy is the end
// listener in the chain, he wants the fully converted (toType) data.
// An example of this listener in mozilla would be the DocLoader.
nsCOMPtr<nsIStreamListener> dataReceiver = new EndListener();
// setup a listener to push the data into. This listener sits inbetween the
// unconverted data of fromType, and the final listener in the chain (in this case
// the dataReceiver.
nsCOMPtr<nsIStreamListener> converterListener;
rv = StreamConvService->AsyncConvertData(fromStr.GetUnicode(), toStr.GetUnicode(),
dataReceiver, nsnull, getter_AddRefs(converterListener));
if (NS_FAILED(rv)) return rv;
// at this point we have a stream listener to push data to, and the one
// that will receive the converted data. Let's mimic On*() calls and get the conversion
// going. Typically these On*() calls would be made inside their respective wrappers On*()
// methods.
rv = converterListener->OnStartRequest(request, nsnull);
if (NS_FAILED(rv)) return rv;
rv = SEND_DATA("aaa");
if (NS_FAILED(rv)) return rv;
rv = SEND_DATA("aaa");
if (NS_FAILED(rv)) return rv;
// Finish the request.
rv = converterListener->OnStopRequest(request, nsnull, rv, nsnull);
if (NS_FAILED(rv)) return rv;
#else
// SYNCRONOUS conversion
nsCOMPtr<nsIInputStream> convertedData;
rv = StreamConvService->Convert(inputData, fromStr.GetUnicode(), toStr.GetUnicode(),
nsnull, getter_AddRefs(convertedData));
if (NS_FAILED(rv)) return rv;
#endif
// Enter the message pump to allow the URL load to proceed.
while ( gKeepRunning ) {
#ifdef WIN32
MSG msg;
if (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
} else {
gKeepRunning = 0;
}
#else
#ifdef XP_MAC
/* Mac stuff is missing here! */
#else
#ifdef XP_OS2
QMSG qmsg;
if (WinGetMsg(0, &qmsg, 0, 0, 0))
WinDispatchMsg(0, &qmsg);
else
gKeepRunning = FALSE;
#else
PLEvent *gEvent;
rv = gEventQ->GetEvent(&gEvent);
rv = gEventQ->HandleEvent(gEvent);
#endif /* XP_UNIX */
#endif /* XP_OS2 */
#endif /* !WIN32 */
}
return NS_ShutdownXPCOM(NULL);
}

View File

@@ -1,62 +0,0 @@
#!nmake
#
# 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):
INCS = $(INCS) \
-I$(DEPTH)\dist\include \
$(NULL)
LLIBS= \
$(DIST)\lib\xpcom.lib \
$(LIBNSPR) \
$(NULL)
DEPTH=..\..\..
include <$(DEPTH)/config/config.mak>
MAKE_OBJ_TYPE = EXE
PROGRAM = .\$(OBJDIR)\TestStreamConv.exe
OBJS = \
.\$(OBJDIR)\Converters.obj \
.\$(OBJDIR)\TestStreamConv.obj \
$(NULL)
LLFLAGS=-SUBSYSTEM:CONSOLE
include <$(DEPTH)\config\rules.mak>
!ifdef MOZ_NO_DEBUG_RTL
OS_CFLAGS = $(OS_CFLAGS) -DMOZ_NO_DEBUG_RTL
!endif
!if defined(NGPREFS)
OS_CFLAGS = $(OS_CFLAGS) -DNGPREFS
!endif
install:: $(PROGRAM)
$(MAKE_INSTALL) $(PROGRAM) $(DIST)\bin
clobber::
rm -f $(DIST)\bin\TestStreamConv.exe

View File

@@ -0,0 +1,39 @@
#!gmake
#
# The contents of this file are subject to the Netscape Public License
# Version 1.0 (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 Communicator client code,
# released March 31, 1998.
#
# 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.
#
# Contributors:
# Daniel Veditz <dveditz@netscape.com>
# Douglas Turner <dougt@netscape.com>
DEPTH = ..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
DIRS = public
include $(topsrcdir)/config/config.mk
include $(topsrcdir)/config/rules.mk

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,30 @@
#!nmake
#
# The contents of this file are subject to the Netscape Public License
# Version 1.0 (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 Communicator client code,
# released March 31, 1998.
#
# 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.
#
# Contributors:
# Daniel Veditz <dveditz@netscape.com>
# Douglas Turner <dougt@netscape.com>
DEPTH=..
DIRS= public res src
include <$(DEPTH)\config\rules.mak>

View File

@@ -0,0 +1,33 @@
<RDF:RDF xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:NC="http://home.netscape.com/NC-rdf#">
<RDF:Bag ID="NC:SoftwareUpdateRoot">
<RDF:li>
<RDF:Bag ID="NC:NewSoftwareToday" NC:title="New Software">
<RDF:li>
<RDF:Description ID="AimUpdate344">
<NC:type resource="http://home.netscape.com/NC-rdf#SoftwarePackage" />
<NC:title>AOL AIM</NC:title>
<NC:description>An Instant Message Client</NC:description>
<NC:version>3.4.1.12</NC:version>
<NC:registryKey>/AOL/AIM/</NC:registryKey>
<NC:url>http://home.netscape.com/index.html</NC:url>
</RDF:Description>
</RDF:li>
<RDF:li>
<RDF:Description ID="PGPPlugin345">
<NC:type resource="http://home.netscape.com/NC-rdf#SoftwarePackage" />
<NC:title>PGP Plugin For Mozilla</NC:title>
<NC:description>A high grade encryption plugin</NC:description>
<NC:version>1.1.2.0</NC:version>
<NC:registryKey>/PGP/ROCKS/</NC:registryKey>
<NC:url>http://home.netscape.com/index.html</NC:url>
</RDF:Description>
</RDF:li>
</RDF:Bag>
</RDF:li>
</RDF:Bag>
</RDF:RDF>

View File

@@ -0,0 +1,57 @@
window {
display: block;
}
tree {
display: table;
background-color: #FFFFFF;
border: none;
border-spacing: 0px;
width: 100%;
}
treecol {
display: table-column;
width: 200px;
}
treeitem {
display: table-row;
}
treehead {
display: table-header-group;
}
treebody {
display: table-row-group;
}
treecell {
display: table-cell;
font-family: Verdana, Sans-Serif;
font-size: 8pt;
}
treecell[selectedcell] {
background-color: yellow;
}
treehead treeitem treecell {
background-color: #c0c0c0;
border: outset 1px;
border-color: white #707070 #707070 white;
padding-left: 4px;
}
treeitem[type="http://home.netscape.com/NC-rdf#SoftwarePackage"] > treecell > titledbutton {
list-style-image: url("resource:/res/rdf/SoftwareUpdatePackage.gif");
}
treeitem[type="http://home.netscape.com/NC-rdf#Folder"] > treecell > titledbutton {
list-style-image: url("resource:/res/rdf/bookmark-folder-closed.gif");
treeitem[type="http://home.netscape.com/NC-rdf#Folder"][open="true"] > treecell > titledbutton {
list-style-image: url("resource:/res/rdf/bookmark-folder-open.gif");
}

View File

@@ -0,0 +1,123 @@
// the rdf service
var RDF = Components.classes['component://netscape/rdf/rdf-service'].getService();
RDF = RDF.QueryInterface(Components.interfaces.nsIRDFService);
function getAttr(registry,service,attr_name)
{
var attr = registry.GetTarget(service,
RDF.GetResource('http://home.netscape.com/NC-rdf#' + attr_name),
true);
if (attr)
attr = attr.QueryInterface(Components.interfaces.nsIRDFLiteral);
if (attr)
attr = attr.Value;
return attr;
}
function Init()
{
// this is the main rdf file.
var mainRegistry = RDF.GetDataSource('resource://res/rdf/SoftwareUpdates.rdf');
var mainContainer = Components.classes['component://netscape/rdf/container'].createInstance();
mainContainer = mainContainer.QueryInterface(Components.interfaces.nsIRDFContainer);
mainContainer.Init(mainRegistry, RDF.GetResource('NC:SoftwareUpdateDataSources'));
// Now enumerate all of the softwareupdate datasources.
var mainEnumerator = mainContainer.GetElements();
while (mainEnumerator.HasMoreElements())
{
var aDistributor = mainEnumerator.GetNext();
aDistributor = aDistributor.QueryInterface(Components.interfaces.nsIRDFResource);
var distributorContainer = Components.classes['component://netscape/rdf/container'].createInstance();
distributorContainer = distributorContainer.QueryInterface(Components.interfaces.nsIRDFContainer);
var distributorRegistry = RDF.GetDataSource(aDistributor.Value);
var distributorResource = RDF.GetResource('NC:SoftwareUpdateRoot');
distributorContainer.Init(distributorRegistry, distributorResource);
// Now enumerate all of the distributorContainer's packages.
var distributorEnumerator = distributorContainer.GetElements();
while (distributorEnumerator.HasMoreElements())
{
var aPackage = distributorEnumerator.GetNext();
aPackage = aPackage.QueryInterface(Components.interfaces.nsIRDFResource);
// remove any that we do not want.
if (getAttr(distributorRegistry, aPackage, 'title') == "AOL AIM")
{
//distributorContainer.RemoveElement(aPackage, true);
}
}
var tree = document.getElementById('tree');
// Add it to the tree control's composite datasource.
tree.database.AddDataSource(distributorRegistry);
}
// Install all of the stylesheets in the softwareupdate Registry into the
// panel.
// TODO
// XXX hack to force the tree to rebuild
var treebody = document.getElementById('NC:SoftwareUpdateRoot');
treebody.setAttribute('id', 'NC:SoftwareUpdateRoot');
}
function OpenURL(event, node)
{
if (node.getAttribute('type') == "http://home.netscape.com/NC-rdf#SoftwarePackage")
{
url = node.getAttribute('url');
/*window.open(url,'bookmarks');*/
var toolkitCore = XPAppCoresManager.Find("ToolkitCore");
if (!toolkitCore)
{
toolkitCore = new ToolkitCore();
if (toolkitCore)
{
toolkitCore.Init("ToolkitCore");
}
}
if (toolkitCore)
{
toolkitCore.ShowWindow(url,window);
}
dump("OpenURL(" + url + ")\n");
return true;
}
return false;
}
// To get around "window.onload" not working in viewer.
function Boot()
{
var tree = document.getElementById('tree');
if (tree == null) {
setTimeout(Boot, 0);
}
else {
Init();
}
}
setTimeout('Boot()', 0);

View File

@@ -0,0 +1,30 @@
<?xml version="1.0"?>
<?xml-stylesheet href="resource:/res/rdf/sidebar.css" type="text/css"?>
<?xml-stylesheet href="resource:/res/rdf/SoftwareUpdate.css" type="text/css"?>
<window
xmlns:html="http://www.w3.org/TR/REC-html40"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<html:script src="SoftwareUpdate.js"/>
<tree id="tree"
flex="100%"
datasources="rdf:softwareupdates"
ondblclick="return OpenURL(event, event.target.parentNode);">
<treecol rdf:resource="http://home.netscape.com/NC-rdf#title" />
<treecol rdf:resource="http://home.netscape.com/NC-rdf#description" />
<treecol rdf:resource="http://home.netscape.com/NC-rdf#version" />
<treehead>
<treeitem>
<treecell>Title</treecell>
<treecell>Description</treecell>
<treecell>Version</treecell>
</treeitem>
</treehead>
<treebody id="NC:SoftwareUpdateRoot" rdf:containment="http://home.netscape.com/NC-rdf#child" />
</tree>
</window>

Binary file not shown.

After

Width:  |  Height:  |  Size: 201 B

View File

@@ -0,0 +1,7 @@
<RDF:RDF xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:NC="http://home.netscape.com/softwareupdate-schema#">
<RDF:Bag ID="NC:SoftwareUpdateDataSources">
<RDF:li resource="resource:/res/rdf/SoftwareUpdate-Source-1.rdf" />
</RDF:Bag>
</RDF:RDF>

View File

@@ -0,0 +1,6 @@
#
# This is a list of local files which get copied to the mozilla:dist directory
#
nsISoftwareUpdate.h
nsSoftwareUpdateIIDs.h

View File

@@ -0,0 +1,47 @@
#!gmake
#
# The contents of this file are subject to the Netscape Public License
# Version 1.0 (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 Communicator client code,
# released March 31, 1998.
#
# 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.
#
# Contributors:
# Daniel Veditz <dveditz@netscape.com>
# Douglas Turner <dougt@netscape.com>
DEPTH = ../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = xpinstall
XPIDLSRCS = nsIXPInstallProgress.idl
EXPORTS = \
nsIDOMInstallTriggerGlobal.h \
nsIDOMInstallVersion.h \
nsSoftwareUpdateIIDs.h \
nsISoftwareUpdate.h \
$(NULL)
EXPORTS := $(addprefix $(srcdir)/, $(EXPORTS))
include $(topsrcdir)/config/config.mk
include $(topsrcdir)/config/rules.mk

View File

@@ -0,0 +1,113 @@
interface Install
{
/* IID: { 0x18c2f988, 0xb09f, 0x11d2, \
{0xbc, 0xde, 0x00, 0x80, 0x5f, 0x0e, 0x13, 0x53}} */
const int BAD_PACKAGE_NAME = -200;
const int UNEXPECTED_ERROR = -201;
const int ACCESS_DENIED = -202;
const int TOO_MANY_CERTIFICATES = -203; /* Installer file must have 1 certificate */
const int NO_INSTALLER_CERTIFICATE = -204; /* Installer file must have a certificate */
const int NO_CERTIFICATE = -205; /* Extracted file is not signed */
const int NO_MATCHING_CERTIFICATE = -206; /* Extracted file does not match installer certificate */
const int UNKNOWN_JAR_FILE = -207; /* JAR file has not been opened */
const int INVALID_ARGUMENTS = -208; /* Bad arguments to a function */
const int ILLEGAL_RELATIVE_PATH = -209; /* Illegal relative path */
const int USER_CANCELLED = -210; /* User cancelled */
const int INSTALL_NOT_STARTED = -211;
const int SILENT_MODE_DENIED = -212;
const int NO_SUCH_COMPONENT = -213; /* no such component in the registry. */
const int FILE_DOES_NOT_EXIST = -214; /* File cannot be deleted as it does not exist */
const int FILE_READ_ONLY = -215; /* File cannot be deleted as it is read only. */
const int FILE_IS_DIRECTORY = -216; /* File cannot be deleted as it is a directory */
const int NETWORK_FILE_IS_IN_USE = -217; /* File on the network is in-use */
const int APPLE_SINGLE_ERR = -218; /* error in AppleSingle unpacking */
const int INVALID_PATH_ERR = -219; /* GetFolder() did not like the folderID */
const int PATCH_BAD_DIFF = -220; /* error in GDIFF patch */
const int PATCH_BAD_CHECKSUM_TARGET = -221; /* source file doesn't checksum */
const int PATCH_BAD_CHECKSUM_RESULT = -222; /* final patched file fails checksum */
const int UNINSTALL_FAILED = -223; /* error while uninstalling a package */
const int GESTALT_UNKNOWN_ERR = -5550;
const int GESTALT_INVALID_ARGUMENT = -5551;
const int SUCCESS = 0;
const int REBOOT_NEEDED = 999;
/* install types */
const int LIMITED_INSTALL = 0;
const int FULL_INSTALL = 1;
const int NO_STATUS_DLG = 2;
const int NO_FINALIZE_DLG = 4;
// these should not be public...
/* message IDs*/
const int SU_INSTALL_FILE_UNEXPECTED_MSG_ID = 0;
const int SU_DETAILS_REPLACE_FILE_MSG_ID = 1;
const int SU_DETAILS_INSTALL_FILE_MSG_ID = 2;
//////////////////////////
readonly attribute wstring UserPackageName;
readonly attribute wstring RegPackageName;
void Install();
void AbortInstall();
long AddDirectory( in wstring regName,
in wstring version,
in wstring jarSource,
in InstallFolder folder,
in wstring subdir,
in boolean forceMode );
long AddSubcomponent( in wstring regName,
in wstring version,
in wstring jarSource,
in InstallFolder folder,
in wstring targetName,
in boolean forceMode );
long DeleteComponent( in wstring registryName);
long DeleteFile( in InstallFolder folder,
in wstring relativeFileName );
long DiskSpaceAvailable( in InstallFolder folder );
long Execute(in wstring jarSource, in wstring args);
long FinalizeInstall();
long Gestalt (in wstring selector);
InstallFolder GetComponentFolder( in wstring regName,
in wstring subdirectory);
InstallFolder GetFolder(in wstring targetFolder,
in wstring subdirectory);
long GetLastError();
long GetWinProfile(in InstallFolder folder, in wstring file);
long GetWinRegistry();
long Patch( in wstring regName,
in wstring version,
in wstring jarSource,
in InstallFolder folder,
in wstring targetName );
void ResetError();
void SetPackageFolder( in InstallFolder folder );
long StartInstall( in wstring userPackageName,
in wstring packageName,
in wstring version,
in long flags );
long Uninstall( in wstring packageName);
};

View File

@@ -0,0 +1,24 @@
interface InstallTriggerGlobal
{
/* IID: { 0x18c2f987, 0xb09f, 0x11d2, \
{0xbc, 0xde, 0x00, 0x80, 0x5f, 0x0e, 0x13, 0x53}} */
const int MAJOR_DIFF = 4;
const int MINOR_DIFF = 3;
const int REL_DIFF = 2;
const int BLD_DIFF = 1;
const int EQUAL = 0;
boolean UpdateEnabled ();
long StartSoftwareUpdate(in wstring URL);
long ConditionalSoftwareUpdate( in wstring URL,
in wstring regName,
in long diffLevel,
in wstring version,
in long mode);
long CompareVersion( in wstring regName, in wstring version );
};

View File

@@ -0,0 +1,34 @@
interface InstallVersion
{
/* IID: { 0x18c2f986, 0xb09f, 0x11d2, \
{0xbc, 0xde, 0x00, 0x80, 0x5f, 0x0e, 0x13, 0x53}} */
const int EQUAL = 0;
const int BLD_DIFF = 1;
const int BLD_DIFF_MINUS = -1;
const int REL_DIFF = 2;
const int REL_DIFF_MINUS = -2;
const int MINOR_DIFF = 3;
const int MINOR_DIFF_MINUS = -3;
const int MAJOR_DIFF = 4;
const int MAJOR_DIFF_MINUS = -4;
attribute int major;
attribute int minor;
attribute int release;
attribute int build;
void InstallVersion();
void init(in wstring versionString);
/*
void init(in int major, in int minor, in int release, in int build);
*/
wstring toString();
/* int compareTo(in wstring version);
int compareTo(in int major, in int minor, in int release, in int build);
*/
int compareTo(in InstallVersion versionObject);
};

View File

@@ -0,0 +1,36 @@
#!nmake
#
# The contents of this file are subject to the Netscape Public License
# Version 1.0 (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 Communicator client code,
# released March 31, 1998.
#
# 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.
#
# Contributors:
# Daniel Veditz <dveditz@netscape.com>
# Douglas Turner <dougt@netscape.com>
MODULE=xpinstall
DEPTH=..\..
EXPORTS= nsIDOMInstallTriggerGlobal.h \
nsIDOMInstallVersion.h \
nsSoftwareUpdateIIDs.h \
nsISoftwareUpdate.h
XPIDLSRCS = .\nsIXPInstallProgress.idl
include <$(DEPTH)\config\config.mak>
include <$(DEPTH)\config\rules.mak>

View File

@@ -0,0 +1 @@
#error

View File

@@ -0,0 +1,96 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
/* AUTO-GENERATED. DO NOT EDIT!!! */
#ifndef nsIDOMInstallTriggerGlobal_h__
#define nsIDOMInstallTriggerGlobal_h__
#include "nsISupports.h"
#include "nsString.h"
#include "nsIScriptContext.h"
#define NS_IDOMINSTALLTRIGGERGLOBAL_IID \
{ 0x18c2f987, 0xb09f, 0x11d2, \
{0xbc, 0xde, 0x00, 0x80, 0x5f, 0x0e, 0x13, 0x53}}
class nsIDOMInstallTriggerGlobal : public nsISupports {
public:
static const nsIID& IID() { static nsIID iid = NS_IDOMINSTALLTRIGGERGLOBAL_IID; return iid; }
enum {
MAJOR_DIFF = 4,
MINOR_DIFF = 3,
REL_DIFF = 2,
BLD_DIFF = 1,
EQUAL = 0
};
NS_IMETHOD UpdateEnabled(PRBool* aReturn)=0;
NS_IMETHOD StartSoftwareUpdate(const nsString& aURL, PRInt32* aReturn)=0;
NS_IMETHOD StartSoftwareUpdate(const nsString& aURL, PRInt32 aFlags, PRInt32* aReturn)=0;
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, PRInt32 aDiffLevel, const nsString& aVersion, PRInt32 aMode, PRInt32* aReturn)=0;
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, PRInt32 aDiffLevel, nsIDOMInstallVersion* aVersion, PRInt32 aMode, PRInt32* aReturn)=0;
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, nsIDOMInstallVersion* aVersion, PRInt32 aMode, PRInt32* aReturn)=0;
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, const nsString& aVersion, PRInt32 aMode, PRInt32* aReturn)=0;
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, const nsString& aVersion, PRInt32* aReturn)=0;
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, nsIDOMInstallVersion* aVersion, PRInt32* aReturn)=0;
NS_IMETHOD CompareVersion(const nsString& aRegName, PRInt32 aMajor, PRInt32 aMinor, PRInt32 aRelease, PRInt32 aBuild, PRInt32* aReturn)=0;
NS_IMETHOD CompareVersion(const nsString& aRegName, const nsString& aVersion, PRInt32* aReturn)=0;
NS_IMETHOD CompareVersion(const nsString& aRegName, nsIDOMInstallVersion* aVersion, PRInt32* aReturn)=0;
};
#define NS_DECL_IDOMINSTALLTRIGGERGLOBAL \
NS_IMETHOD UpdateEnabled(PRBool* aReturn); \
NS_IMETHOD StartSoftwareUpdate(const nsString& aURL, PRInt32 aFlags, PRInt32* aReturn); \
NS_IMETHOD StartSoftwareUpdate(const nsString& aURL, PRInt32* aReturn); \
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, PRInt32 aDiffLevel, const nsString& aVersion, PRInt32 aMode, PRInt32* aReturn); \
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, PRInt32 aDiffLevel, nsIDOMInstallVersion* aVersion, PRInt32 aMode, PRInt32* aReturn); \
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, nsIDOMInstallVersion* aVersion, PRInt32 aMode, PRInt32* aReturn); \
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, const nsString& aVersion, PRInt32 aMode, PRInt32* aReturn); \
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, const nsString& aVersion, PRInt32* aReturn); \
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, nsIDOMInstallVersion* aVersion, PRInt32* aReturn); \
NS_IMETHOD CompareVersion(const nsString& aRegName, PRInt32 aMajor, PRInt32 aMinor, PRInt32 aRelease, PRInt32 aBuild, PRInt32* aReturn); \
NS_IMETHOD CompareVersion(const nsString& aRegName, const nsString& aVersion, PRInt32* aReturn); \
NS_IMETHOD CompareVersion(const nsString& aRegName, nsIDOMInstallVersion* aVersion, PRInt32* aReturn); \
#define NS_FORWARD_IDOMINSTALLTRIGGERGLOBAL(_to) \
NS_IMETHOD UpdateEnabled(PRBool* aReturn) { return _to##UpdateEnabled(aReturn); } \
NS_IMETHOD StartSoftwareUpdate(const nsString& aURL, PRInt32 aFlags, PRInt32* aReturn) { return _to##StartSoftwareUpdate(aURL, aFlags, aReturn); } \
NS_IMETHOD StartSoftwareUpdate(const nsString& aURL, PRInt32* aReturn) { return _to##StartSoftwareUpdate(aURL, aReturn); } \
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, PRInt32 aDiffLevel, const nsString& aVersion, PRInt32 aMode, PRInt32* aReturn) { return _to##ConditionalSoftwareUpdate(aURL, aRegName, aDiffLevel, aVersion, aMode, aReturn); } \
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, PRInt32 aDiffLevel, nsIDOMInstallVersion* aVersion, PRInt32 aMode, PRInt32* aReturn) { return _to##ConditionalSoftwareUpdate(aURL, aRegName, aDiffLevel, aVersion, aMode, aReturn); } \
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, nsIDOMInstallVersion* aRegName, const nsString& aVersion, PRInt32 aMode, PRInt32* aReturn) { return _to##ConditionalSoftwareUpdate(aURL, aDiffLevel, aVersion, aMode, aReturn); } \
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, const nsString& aVersion, PRInt32 aMode, PRInt32* aReturn) { return _to##ConditionalSoftwareUpdate(aURL, aDiffLevel, aVersion, aMode, aReturn); } \
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, const nsString& aVersion, PRInt32* aReturn) { return _to##ConditionalSoftwareUpdate(aURL, aDiffLevel, aVersion, aReturn); } \
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, nsIDOMInstallVersion* aVersion, PRInt32* aReturn) { return _to##ConditionalSoftwareUpdate(aURL, aDiffLevel, aVersion, aReturn); } \
NS_IMETHOD CompareVersion(const nsString& aRegName, PRInt32 aMajor, PRInt32 aMinor, PRInt32 aRelease, PRInt32 aBuild, PRInt32* aReturn) { return _to##CompareVersion(aRegName, aMajor, aMinor, aRelease, aBuild, aReturn); } \
NS_IMETHOD CompareVersion(const nsString& aRegName, const nsString& aVersion, PRInt32* aReturn) { return _to##CompareVersion(aRegName, aVersion, aReturn); } \
NS_IMETHOD CompareVersion(const nsString& aRegName, nsIDOMInstallVersion* aVersion, PRInt32* aReturn) { return _to##CompareVersion(aRegName, aVersion, aReturn); } \
extern nsresult NS_InitInstallTriggerGlobalClass(nsIScriptContext *aContext, void **aPrototype);
extern "C" NS_DOM nsresult NS_NewScriptInstallTriggerGlobal(nsIScriptContext *aContext, nsISupports *aSupports, nsISupports *aParent, void **aReturn);
#endif // nsIDOMInstallTriggerGlobal_h__

View File

@@ -0,0 +1,107 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
/* AUTO-GENERATED. DO NOT EDIT!!! */
#ifndef nsIDOMInstallVersion_h__
#define nsIDOMInstallVersion_h__
#include "nsISupports.h"
#include "nsString.h"
#include "nsIScriptContext.h"
class nsIDOMInstallVersion;
#define NS_IDOMINSTALLVERSION_IID \
{ 0x18c2f986, 0xb09f, 0x11d2, \
{0xbc, 0xde, 0x00, 0x80, 0x5f, 0x0e, 0x13, 0x53}}
class nsIDOMInstallVersion : public nsISupports {
public:
static const nsIID& IID() { static nsIID iid = NS_IDOMINSTALLVERSION_IID; return iid; }
enum {
EQUAL = 0,
BLD_DIFF = 1,
BLD_DIFF_MINUS = -1,
REL_DIFF = 2,
REL_DIFF_MINUS = -2,
MINOR_DIFF = 3,
MINOR_DIFF_MINUS = -3,
MAJOR_DIFF = 4,
MAJOR_DIFF_MINUS = -4
};
NS_IMETHOD GetMajor(PRInt32* aMajor)=0;
NS_IMETHOD SetMajor(PRInt32 aMajor)=0;
NS_IMETHOD GetMinor(PRInt32* aMinor)=0;
NS_IMETHOD SetMinor(PRInt32 aMinor)=0;
NS_IMETHOD GetRelease(PRInt32* aRelease)=0;
NS_IMETHOD SetRelease(PRInt32 aRelease)=0;
NS_IMETHOD GetBuild(PRInt32* aBuild)=0;
NS_IMETHOD SetBuild(PRInt32 aBuild)=0;
NS_IMETHOD Init(const nsString& aVersionString)=0;
NS_IMETHOD ToString(nsString& aReturn)=0;
NS_IMETHOD CompareTo(nsIDOMInstallVersion* aVersionObject, PRInt32* aReturn)=0;
NS_IMETHOD CompareTo(const nsString& aString, PRInt32* aReturn)=0;
NS_IMETHOD CompareTo(PRInt32 aMajor, PRInt32 aMinor, PRInt32 aRelease, PRInt32 aBuild, PRInt32* aReturn)=0;
};
#define NS_DECL_IDOMINSTALLVERSION \
NS_IMETHOD GetMajor(PRInt32* aMajor); \
NS_IMETHOD SetMajor(PRInt32 aMajor); \
NS_IMETHOD GetMinor(PRInt32* aMinor); \
NS_IMETHOD SetMinor(PRInt32 aMinor); \
NS_IMETHOD GetRelease(PRInt32* aRelease); \
NS_IMETHOD SetRelease(PRInt32 aRelease); \
NS_IMETHOD GetBuild(PRInt32* aBuild); \
NS_IMETHOD SetBuild(PRInt32 aBuild); \
NS_IMETHOD Init(const nsString& aVersionString); \
NS_IMETHOD ToString(nsString& aReturn); \
NS_IMETHOD CompareTo(nsIDOMInstallVersion* aVersionObject, PRInt32* aReturn); \
NS_IMETHOD CompareTo(const nsString& aString, PRInt32* aReturn); \
NS_IMETHOD CompareTo(PRInt32 aMajor, PRInt32 aMinor, PRInt32 aRelease, PRInt32 aBuild, PRInt32* aReturn); \
#define NS_FORWARD_IDOMINSTALLVERSION(_to) \
NS_IMETHOD GetMajor(PRInt32* aMajor) { return _to##GetMajor(aMajor); } \
NS_IMETHOD SetMajor(PRInt32 aMajor) { return _to##SetMajor(aMajor); } \
NS_IMETHOD GetMinor(PRInt32* aMinor) { return _to##GetMinor(aMinor); } \
NS_IMETHOD SetMinor(PRInt32 aMinor) { return _to##SetMinor(aMinor); } \
NS_IMETHOD GetRelease(PRInt32* aRelease) { return _to##GetRelease(aRelease); } \
NS_IMETHOD SetRelease(PRInt32 aRelease) { return _to##SetRelease(aRelease); } \
NS_IMETHOD GetBuild(PRInt32* aBuild) { return _to##GetBuild(aBuild); } \
NS_IMETHOD SetBuild(PRInt32 aBuild) { return _to##SetBuild(aBuild); } \
NS_IMETHOD Init(const nsString& aVersionString) { return _to##Init(aVersionString); } \
NS_IMETHOD ToString(nsString& aReturn) { return _to##ToString(aReturn); } \
NS_IMETHOD CompareTo(nsIDOMInstallVersion* aVersionObject, PRInt32* aReturn) { return _to##CompareTo(aVersionObject, aReturn); } \
NS_IMETHOD CompareTo(const nsString& aString, PRInt32* aReturn) { return _to##CompareTo(aString, aReturn); } \
NS_IMETHOD CompareTo(PRInt32 aMajor, PRInt32 aMinor, PRInt32 aRelease, PRInt32 aBuild, PRInt32* aReturn) { return _to##CompareTo(aMajor, aMinor, aRelease, aBuild, aReturn); } \
extern nsresult NS_InitInstallVersionClass(nsIScriptContext *aContext, void **aPrototype);
extern "C" NS_DOM nsresult NS_NewScriptInstallVersion(nsIScriptContext *aContext, nsISupports *aSupports, nsISupports *aParent, void **aReturn);
#endif // nsIDOMInstallVersion_h__

View File

@@ -0,0 +1,85 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Daniel Veditz <dveditz@netscape.com>
* Douglas Turner <dougt@netscape.com>
*/
#ifndef nsISoftwareUpdate_h__
#define nsISoftwareUpdate_h__
#include "nsISupports.h"
#include "nsIFactory.h"
#include "nsString.h"
#include "nsIXPInstallProgress.h"
#define NS_IXPINSTALLCOMPONENT_PROGID NS_IAPPSHELLCOMPONENT_PROGID "/xpinstall"
#define NS_IXPINSTALLCOMPONENT_CLASSNAME "Mozilla XPInstall Component"
#define NS_ISOFTWAREUPDATE_IID \
{ 0x18c2f992, \
0xb09f, \
0x11d2, \
{0xbc, 0xde, 0x00, 0x80, 0x5f, 0x0e, 0x13, 0x53}\
}
class nsISoftwareUpdate : public nsISupports
{
public:
NS_DEFINE_STATIC_IID_ACCESSOR(NS_ISOFTWAREUPDATE_IID)
NS_IMETHOD InstallJar(const nsString& fromURL,
const nsString& localFile,
long flags) = 0;
NS_IMETHOD RegisterNotifier(nsIXPInstallProgress *notifier) = 0;
NS_IMETHOD InstallPending(void) = 0;
/* FIX: these should be in a private interface */
NS_IMETHOD InstallJarCallBack() = 0;
NS_IMETHOD GetTopLevelNotifier(nsIXPInstallProgress **notifier) = 0;
};
class nsSoftwareUpdateFactory : public nsIFactory
{
public:
nsSoftwareUpdateFactory();
virtual ~nsSoftwareUpdateFactory();
NS_DECL_ISUPPORTS
NS_IMETHOD CreateInstance(nsISupports *aOuter,
REFNSIID aIID,
void **aResult);
NS_IMETHOD LockFactory(PRBool aLock);
};
#endif // nsISoftwareUpdate_h__

View File

@@ -0,0 +1,30 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsISupports.idl"
[uuid(eea90d40-b059-11d2-915e-c12b696c9333)]
interface nsIXPInstallProgress : nsISupports
{
void BeforeJavascriptEvaluation();
void AfterJavascriptEvaluation();
void InstallStarted([const] in string UIPackageName);
void ItemScheduled([const] in string message );
void InstallFinalization([const] in string message, in long itemNum, in long totNum );
void InstallAborted();
};

View File

@@ -0,0 +1,93 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Douglas Turner <dougt@netscape.com>
*/
#ifndef nsIXPInstallProgressNotifier_h__
#define nsIXPInstallProgressNotifier_h__
class nsIXPInstallProgressNotifier
{
public:
///////////////////////////////////////////////////////////////////////////////////////////////////////
// Function name : BeforeJavascriptEvaluation
// Description : This will be called when prior to the install script being evaluate
// Return type : void
// Argument : void
///////////////////////////////////////////////////////////////////////////////////////////////////////
virtual void BeforeJavascriptEvaluation(void) = 0;
///////////////////////////////////////////////////////////////////////////////////////////////////////
// Function name : AfterJavascriptEvaluation
// Description : This will be called after the install script has being evaluated
// Return type : void
// Argument : void
///////////////////////////////////////////////////////////////////////////////////////////////////////
virtual void AfterJavascriptEvaluation(void) = 0;
///////////////////////////////////////////////////////////////////////////////////////////////////////
// Function name : InstallStarted
// Description : This will be called when StartInstall has been called
// Return type : void
// Argument : char* UIPackageName - User Package Name
///////////////////////////////////////////////////////////////////////////////////////////////////////
virtual void InstallStarted(const char* UIPackageName) = 0;
///////////////////////////////////////////////////////////////////////////////////////////////////////
// Function name : ItemScheduled
// Description : This will be called when items are being scheduled
// Return type : Any value returned other than zero, will be treated as an error and the script will be aborted
// Argument : The message that should be displayed to the user
///////////////////////////////////////////////////////////////////////////////////////////////////////
virtual long ItemScheduled( const char* message ) = 0;
///////////////////////////////////////////////////////////////////////////////////////////////////////
// Function name : InstallFinalization
// Description : This will be called when the installation is in its Finalize stage
// Return type : void
// Argument : char* message - The message that should be displayed to the user
// Argument : long itemNum - This is the current item number
// Argument : long totNum - This is the total number of items
///////////////////////////////////////////////////////////////////////////////////////////////////////
virtual void InstallFinalization( const char* message, long itemNum, long totNum ) = 0;
///////////////////////////////////////////////////////////////////////////////////////////////////////
// Function name : InstallAborted
// Description : This will be called when the install is aborted
// Return type : void
// Argument : void
///////////////////////////////////////////////////////////////////////////////////////////////////////
virtual void InstallAborted(void) = 0;
};
#endif

View File

@@ -0,0 +1,64 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Daniel Veditz <dveditz@netscape.com>
* Douglas Turner <dougt@netscape.com>
*/
#ifndef nsSoftwareUpdateIIDs_h___
#define nsSoftwareUpdateIIDs_h___
#define NS_SoftwareUpdate_CID \
{ /* 18c2f989-b09f-11d2-bcde-00805f0e1353 */ \
0x18c2f989, \
0xb09f, \
0x11d2, \
{0xbc, 0xde, 0x00, 0x80, 0x5f, 0x0e, 0x13, 0x53} \
}
#define NS_SoftwareUpdateInstall_CID \
{ /* 18c2f98b-b09f-11d2-bcde-00805f0e1353 */ \
0x18c2f98b, \
0xb09f, \
0x11d2, \
{0xbc, 0xde, 0x00, 0x80, 0x5f, 0x0e, 0x13, 0x53} \
}
#define NS_SoftwareUpdateInstallTrigger_CID \
{ /* 18c2f98d-b09f-11d2-bcde-00805f0e1353 */ \
0x18c2f98d, \
0xb09f, \
0x11d2, \
{0xbc, 0xde, 0x00, 0x80, 0x5f, 0x0e, 0x13, 0x53} \
}
#define NS_SoftwareUpdateInstallVersion_CID \
{ /* 18c2f98f-b09f-11d2-bcde-00805f0e1353 */ \
0x18c2f98f, \
0xb09f, \
0x11d2, \
{0xbc, 0xde, 0x00, 0x80, 0x5f, 0x0e, 0x13, 0x53} \
}
#endif /* nsSoftwareUpdateIIDs_h___ */

View File

@@ -0,0 +1,3 @@
progress.xul
progress.css
progress.html

View File

@@ -0,0 +1,34 @@
#!gmake
#
# The contents of this file are subject to the Netscape Public License
# Version 1.0 (the "NPL"); you may not use this file except in
# compliance with the NPL. You may obtain a copy of the NPL at
# http://www.mozilla.org/NPL/
#
# Software distributed under the NPL is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
# for the specific language governing rights and limitations under the
# NPL.
#
# The Initial Developer of this code under the NPL is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All Rights
# Reserved.
DEPTH=../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
include $(topsrcdir)/config/config.mk
include $(topsrcdir)/config/rules.mk
EXPORT_RESOURCE_XPINSTALL = \
$(srcdir)/progress.xul \
$(srcdir)/progress.html \
$(srcdir)/progress.css \
$(NULL)
install::
$(INSTALL) $(EXPORT_RESOURCE_XPINSTALL) $(DIST)/bin/res/xpinstall

View File

@@ -0,0 +1,31 @@
#!nmake
#
# The contents of this file are subject to the Netscape Public License
# Version 1.0 (the "NPL"); you may not use this file except in
# compliance with the NPL. You may obtain a copy of the NPL at
# http://www.mozilla.org/NPL/
#
# Software distributed under the NPL is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
# for the specific language governing rights and limitations under the
# NPL.
#
# The Initial Developer of this code under the NPL is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All Rights
# Reserved.
DEPTH=..\..
IGNORE_MANIFEST=1
include <$(DEPTH)\config\rules.mak>
install:: $(DLL)
$(MAKE_INSTALL) progress.xul $(DIST)\bin\res\xpinstall
$(MAKE_INSTALL) progress.css $(DIST)\bin\res\xpinstall
$(MAKE_INSTALL) progress.html $(DIST)\bin\res\xpinstall
clobber::
rm -f $(DIST)\res\xpinstall\progress.xul
rm -f $(DIST)\res\xpinstall\progress.css
rm -f $(DIST)\res\xpinstall\progress.html

View File

@@ -0,0 +1,3 @@
TD {
font: 10pt sans-serif;
}

View File

@@ -0,0 +1,16 @@
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<body bgcolor="#C0C0C0" style="overflow:visible; margin: 0px; color-background: rgb(192,192,192);">
<center>
<table BORDER COLS=5 WIDTH="99%" style="color-background:rgb(192,192,192);">
<tr>
<td WIDTH="3%" NOWRAP style="border: 1px inset rgb(192,192,192);">&nbsp</td>
<td WIDTH="3%" NOWRAP style="border: 1px inset rgb(192,192,192);">&nbsp</td>
<td WIDTH="3%" NOWRAP style="border: 1px inset rgb(192,192,192);">&nbsp</td>
<td WIDTH="10%" NOWRAP style="border: 1px inset rgb(192,192,192);">&nbsp</td>
<td WIDTH="81%" NOWRAP style="border: 1px inset rgb(192,192,192);">&nbsp</td>
</tr>
</table>
</center>
</body>
</html>

View File

@@ -0,0 +1,67 @@
<?xml version="1.0"?>
<?xml-stylesheet href="../samples/xul.css" type="text/css"?>
<?xml-stylesheet href="progress.css" type="text/css"?>
<!DOCTYPE window
[
<!ENTITY downloadWindow.title "XPInstall Progress">
<!ENTITY status "Status:">
<!ENTITY cancelButtonTitle "Cancel">
]
>
<window xmlns:html="http://www.w3.org/TR/REC-html40"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
title="XPInstall Progress"
width="425"
height="225">
<data>
<broadcaster id="data.canceled" type="string" value="false"/>
</data>
<html:script>
function cancelInstall()
{
var cancelData = document.getElementById("data.canceled");
cancelData.setAttribute( "value", "true");
}
</html:script>
<html:center>
<html:table style="width:100%;">
<html:tr>
<html:td align="center">
<html:input id="dialog.uiPackageName" readonly="" style="background-color:lightgray;width:300px;"/>
</html:td>
</html:tr>
<html:tr>
<html:td nowrap="" style="border: 1px rgb(192,192,192);" align="center">
<html:input id="dialog.currentAction" readonly="" style="background-color:lightgray;width:450px;"/>
</html:td>
</html:tr>
<html:tr>
<html:td align="center" width="15%" nowrap="" style="border: 1px rgb(192,192,192);">
<progressmeter id="dialog.progress" mode="undetermined" style="width:300px;height:16px;">
</progressmeter>
</html:td>
</html:tr>
<html:tr>
<html:td align="center" width="3%" nowrap="" style="border: 1px rgb(192,192,192);">
<html:button onclick="cancelInstall()" height="12">
&cancelButtonTitle;
</html:button>
</html:td>
</html:tr>
</html:table>
</html:center>
</window>

View File

@@ -0,0 +1,61 @@
#!gmake
#
# The contents of this file are subject to the Netscape Public License
# Version 1.0 (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 Communicator client code,
# released March 31, 1998.
#
# 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.
#
# Contributors:
# Daniel Veditz <dveditz@netscape.com>
# Douglas Turner <dougt@netscape.com>
DEPTH = ../..
topsrcdir = @top_srcdir@
VPATH = @srcdir@
srcdir = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = xpinstall
LIBRARY_NAME = xpinstall
IS_COMPONENT = 1
REQUIRES = dom js netlib raptor xpcom
CPPSRCS = \
nsSoftwareUpdate.cpp \
nsInstall.cpp \
nsInstallDelete.cpp \
nsInstallExecute.cpp \
nsInstallFile.cpp \
nsInstallFolder.cpp \
nsInstallPatch.cpp \
nsInstallUninstall.cpp \
nsInstallTrigger.cpp \
nsInstallResources.cpp \
nsJSInstall.cpp \
nsJSInstallTriggerGlobal.cpp\
nsSoftwareUpdateRun.cpp \
nsSoftwareUpdateStream.cpp \
nsTopProgressNotifier.cpp \
nsLoggingProgressNotifier \
ScheduledTasks.cpp \
nsInstallFileOpItem.cpp \
$(NULL)
INCLUDES += -I$(srcdir)/../public
include $(topsrcdir)/config/rules.mk

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,233 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Douglas Turner <dougt@netscape.com>
*/
#ifndef SU_PAS_H
#define SU_PAS_H
#include <Errors.h>
#include <Types.h>
#include <Files.h>
#include <Script.h>
#include <Resources.h>
typedef struct PASHeader /* header portion of Patchable AppleSingle */
{
UInt32 magicNum; /* internal file type tag = 0x00244200*/
UInt32 versionNum; /* format version: 1 = 0x00010000 */
UInt8 filler[16]; /* filler */
UInt16 numEntries; /* number of entries which follow */
} PASHeader ;
typedef struct PASEntry /* one Patchable AppleSingle entry descriptor */
{
UInt32 entryID; /* entry type: see list, 0 invalid */
UInt32 entryOffset; /* offset, in bytes, from beginning */
/* of file to this entry's data */
UInt32 entryLength; /* length of data in octets */
} PASEntry;
typedef struct PASMiscInfo
{
short fileHasResFork;
short fileResAttrs;
OSType fileType;
OSType fileCreator;
UInt32 fileFlags;
} PASMiscInfo;
typedef struct PASResFork
{
short NumberOfTypes;
} PASResFork;
typedef struct PASResource
{
short attr;
short attrID;
OSType attrType;
Str255 attrName;
unsigned long length;
} PASResource;
#if PRAGMA_ALIGN_SUPPORTED
#pragma options align=reset
#endif
#define kCreator 'MOSS'
#define kType 'PASf'
#define PAS_BUFFER_SIZE (1024*512)
#define PAS_MAGIC_NUM (0x00244200)
#define PAS_VERSION (0x00010000)
enum
{
ePas_Data = 1,
ePas_Misc,
ePas_Resource
};
#ifdef __cplusplus
extern "C" {
#endif
/* Prototypes */
OSErr PAS_EncodeFile(FSSpec *inSpec, FSSpec *outSpec);
OSErr PAS_DecodeFile(FSSpec *inSpec, FSSpec *outSpec);
#ifdef __cplusplus
}
#endif
#endif /* SU_PAS_H */

View File

@@ -0,0 +1,380 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Daniel Veditz <dveditz@netscape.com>
* Douglas Turner <dougt@netscape.com>
*/
#include "nscore.h"
#include "NSReg.h"
#include "nsFileSpec.h"
#include "nsFileStream.h"
#include "nsInstall.h" // for error codes
#include "prmem.h"
#include "ScheduledTasks.h"
#ifdef _WINDOWS
#include <sys/stat.h>
#include <windows.h>
BOOL WIN32_IsMoveFileExBroken()
{
/* the NT option MOVEFILE_DELAY_UNTIL_REBOOT is broken on
* Windows NT 3.51 Service Pack 4 and NT 4.0 before Service Pack 2
*/
BOOL broken = FALSE;
OSVERSIONINFO osinfo;
// they *all* appear broken--better to have one way that works.
return TRUE;
osinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (GetVersionEx(&osinfo) && osinfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
{
if ( osinfo.dwMajorVersion == 3 && osinfo.dwMinorVersion == 51 )
{
if ( 0 == stricmp(osinfo.szCSDVersion,"Service Pack 4"))
{
broken = TRUE;
}
}
else if ( osinfo.dwMajorVersion == 4 )
{
if (osinfo.szCSDVersion[0] == '\0' ||
(0 == stricmp(osinfo.szCSDVersion,"Service Pack 1")))
{
broken = TRUE;
}
}
}
return broken;
}
PRInt32 DoWindowsReplaceExistingFileStuff(const char* currentName, const char* finalName)
{
PRInt32 err = 0;
char* final = strdup(finalName);
char* current = strdup(currentName);
/* couldn't delete, probably in use. Schedule for later */
DWORD dwVersion, dwWindowsMajorVersion;
/* Get OS version info */
dwVersion = GetVersion();
dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
/* Get build numbers for Windows NT or Win32s */
if (dwVersion < 0x80000000) // Windows NT
{
/* On Windows NT */
if ( WIN32_IsMoveFileExBroken() )
{
/* the MOVEFILE_DELAY_UNTIL_REBOOT option doesn't work on
* NT 3.51 SP4 or on NT 4.0 until SP2
*/
struct stat statbuf;
PRBool nameFound = PR_FALSE;
char tmpname[_MAX_PATH];
strncpy( tmpname, finalName, _MAX_PATH );
int len = strlen(tmpname);
while (!nameFound && len < _MAX_PATH )
{
tmpname[len-1] = '~';
tmpname[len] = '\0';
if ( stat(tmpname, &statbuf) != 0 )
nameFound = TRUE;
else
len++;
}
if ( nameFound )
{
if ( MoveFile( finalName, tmpname ) )
{
if ( MoveFile( currentName, finalName ) )
{
DeleteFileNowOrSchedule(nsFileSpec(tmpname));
}
else
{
/* 2nd move failed, put old file back */
MoveFile( tmpname, finalName );
}
}
else
{
/* non-executable in use; schedule for later */
return -1; // let the start registry stuff do our work!
}
}
}
else if ( MoveFileEx(currentName, finalName, MOVEFILE_DELAY_UNTIL_REBOOT) )
{
err = 0;
}
}
else // Windows 95 or Win16
{
/*
* Place an entry in the WININIT.INI file in the Windows directory
* to delete finalName and rename currentName to be finalName at reboot
*/
int strlen;
char Src[_MAX_PATH]; // 8.3 name
char Dest[_MAX_PATH]; // 8.3 name
strlen = GetShortPathName( (LPCTSTR)currentName, (LPTSTR)Src, (DWORD)sizeof(Src) );
if ( strlen > 0 )
{
free(current);
current = strdup(Src);
}
strlen = GetShortPathName( (LPCTSTR) finalName, (LPTSTR) Dest, (DWORD) sizeof(Dest));
if ( strlen > 0 )
{
free(final);
final = strdup(Dest);
}
/* NOTE: use OEM filenames! Even though it looks like a Windows
* .INI file, WININIT.INI is processed under DOS
*/
AnsiToOem( final, final );
AnsiToOem( current, current );
if ( WritePrivateProfileString( "Rename", final, current, "WININIT.INI" ) )
err = 0;
}
free(final);
free(current);
return err;
}
#endif
REGERR DeleteFileNowOrSchedule(nsFileSpec& filename)
{
REGERR result = 0;
filename.Delete(false);
if (filename.Exists())
{
RKEY newkey;
HREG reg;
if ( REGERR_OK == NR_RegOpen("", &reg) )
{
if (REGERR_OK == NR_RegAddKey( reg, ROOTKEY_PRIVATE, REG_DELETE_LIST_KEY, &newkey) )
{
// FIX should be using nsPersistentFileDescriptor!!!
result = NR_RegSetEntry( reg, newkey, (char*)(const char*)filename.GetNativePathCString(), REGTYPE_ENTRY_FILE, nsnull, 0);
if (result == REGERR_OK)
result = nsInstall::REBOOT_NEEDED;
}
NR_RegClose(reg);
}
}
return result;
}
/* tmp file is the bad one that we want to replace with target. */
REGERR ReplaceFileNowOrSchedule(nsFileSpec& replacementFile, nsFileSpec& doomedFile )
{
REGERR result = 0;
if(replacementFile == doomedFile)
{
/* do not have to do anything */
return result;
}
doomedFile.Delete(false);
if (! doomedFile.Exists() )
{
// Now that we have move the existing file, we can move the mExtracedFile into place.
nsFileSpec parentofFinalFile;
doomedFile.GetParent(parentofFinalFile);
result = replacementFile.Move(parentofFinalFile);
if ( NS_SUCCEEDED(result) )
{
char* leafName = doomedFile.GetLeafName();
replacementFile.Rename(leafName);
nsCRT::free(leafName);
}
}
else
{
#ifdef _WINDOWS
if (DoWindowsReplaceExistingFileStuff(replacementFile.GetNativePathCString(), doomedFile.GetNativePathCString()) == 0)
return 0;
#endif
RKEY newkey;
HREG reg;
if ( REGERR_OK == NR_RegOpen("", &reg) )
{
result = NR_RegAddKey( reg, ROOTKEY_PRIVATE, REG_REPLACE_LIST_KEY, &newkey);
if ( result == REGERR_OK )
{
char* replacementFileName = (char*)(const char*)replacementFile.GetNativePathCString();
result = NR_RegSetEntry( reg, newkey, (char*)(const char*)doomedFile.GetNativePathCString(), REGTYPE_ENTRY_FILE, replacementFileName, strlen(replacementFileName));
if (result == REGERR_OK)
result = nsInstall::REBOOT_NEEDED;
}
NR_RegClose(reg);
}
}
return result;
}
void DeleteScheduledFiles(void);
void ReplaceScheduledFiles(void);
extern "C" void PerformScheduledTasks(void *data)
{
DeleteScheduledFiles();
ReplaceScheduledFiles();
}
void DeleteScheduledFiles(void)
{
HREG reg;
if (REGERR_OK == NR_RegOpen("", &reg))
{
RKEY key;
REGENUM state;
/* perform scheduled file deletions and replacements (PC only) */
if (REGERR_OK == NR_RegGetKey(reg, ROOTKEY_PRIVATE, REG_DELETE_LIST_KEY,&key))
{
char buf[MAXREGNAMELEN];
while (REGERR_OK == NR_RegEnumEntries(reg, key, &state, buf, sizeof(buf), NULL ))
{
nsFileSpec doomedFile(buf);
doomedFile.Delete(PR_FALSE);
if (! doomedFile.Exists())
{
NR_RegDeleteEntry( reg, key, buf );
}
}
/* delete list node if empty */
if (REGERR_NOMORE == NR_RegEnumEntries( reg, key, &state, buf, sizeof(buf), NULL ))
{
NR_RegDeleteKey(reg, ROOTKEY_PRIVATE, REG_DELETE_LIST_KEY);
}
}
NR_RegClose(reg);
}
}
void ReplaceScheduledFiles(void)
{
HREG reg;
if (REGERR_OK == NR_RegOpen("", &reg))
{
RKEY key;
REGENUM state;
/* replace files if any listed */
if (REGERR_OK == NR_RegGetKey(reg, ROOTKEY_PRIVATE, REG_REPLACE_LIST_KEY, &key))
{
char tmpfile[MAXREGNAMELEN];
char target[MAXREGNAMELEN];
state = 0;
while (REGERR_OK == NR_RegEnumEntries(reg, key, &state, tmpfile, sizeof(tmpfile), NULL ))
{
nsFileSpec replaceFile(tmpfile);
if (! replaceFile.Exists() )
{
NR_RegDeleteEntry( reg, key, tmpfile );
}
else if ( REGERR_OK != NR_RegGetEntryString( reg, key, tmpfile, target, sizeof(target) ) )
{
/* can't read target filename, corruption? */
NR_RegDeleteEntry( reg, key, tmpfile );
}
else
{
nsFileSpec targetFile(target);
targetFile.Delete(PR_FALSE);
if (!targetFile.Exists())
{
nsFileSpec parentofTarget;
targetFile.GetParent(parentofTarget);
nsresult result = replaceFile.Move(parentofTarget);
if ( NS_SUCCEEDED(result) )
{
char* leafName = targetFile.GetLeafName();
replaceFile.Rename(leafName);
nsCRT::free(leafName);
NR_RegDeleteEntry( reg, key, tmpfile );
}
}
}
}
/* delete list node if empty */
if (REGERR_NOMORE == NR_RegEnumEntries(reg, key, &state, tmpfile, sizeof(tmpfile), NULL ))
{
NR_RegDeleteKey(reg, ROOTKEY_PRIVATE, REG_REPLACE_LIST_KEY);
}
}
NR_RegClose(reg);
}
}

View File

@@ -0,0 +1,42 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Daniel Veditz <dveditz@netscape.com>
* Douglas Turner <dougt@netscape.com>
*/
#ifndef __SCHEDULEDTASKS_H__
#define __SCHEDULEDTASKS_H__
#include "NSReg.h"
#include "nsFileSpec.h"
REGERR DeleteFileNowOrSchedule(nsFileSpec& filename);
REGERR ReplaceFileNowOrSchedule(nsFileSpec& tmpfile, nsFileSpec& target );
extern "C" void PerformScheduledTasks(void *data);
#endif

View File

@@ -0,0 +1,135 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
/*--------------------------------------------------------------
* GDIFF.H
*
* Constants used in processing the GDIFF format
*--------------------------------------------------------------*/
#include "prio.h"
#include "nsFileSpec.h"
#define GDIFF_MAGIC "\xD1\xFF\xD1\xFF"
#define GDIFF_MAGIC_LEN 4
#define GDIFF_VER 5
#define GDIFF_EOF "\0"
#define GDIFF_VER_POS 4
#define GDIFF_CS_POS 5
#define GDIFF_CSLEN_POS 6
#define GDIFF_HEADERSIZE 7
#define GDIFF_APPDATALEN 4
#define GDIFF_CS_NONE 0
#define GDIFF_CS_MD5 1
#define GDIFF_CS_SHA 2
#define GDIFF_CS_CRC32 32
#define CRC32_LEN 4
/*--------------------------------------
* GDIFF opcodes
*------------------------------------*/
#define ENDDIFF 0
#define ADD8MAX 246
#define ADD16 247
#define ADD32 248
#define COPY16BYTE 249
#define COPY16SHORT 250
#define COPY16LONG 251
#define COPY32BYTE 252
#define COPY32SHORT 253
#define COPY32LONG 254
#define COPY64 255
/* instruction sizes */
#define ADD16SIZE 2
#define ADD32SIZE 4
#define COPY16BYTESIZE 3
#define COPY16SHORTSIZE 4
#define COPY16LONGSIZE 6
#define COPY32BYTESIZE 5
#define COPY32SHORTSIZE 6
#define COPY32LONGSIZE 8
#define COPY64SIZE 12
/*--------------------------------------
* error codes
*------------------------------------*/
#define GDIFF_OK 0
#define GDIFF_ERR_UNKNOWN -1
#define GDIFF_ERR_ARGS -2
#define GDIFF_ERR_ACCESS -3
#define GDIFF_ERR_MEM -4
#define GDIFF_ERR_HEADER -5
#define GDIFF_ERR_BADDIFF -6
#define GDIFF_ERR_OPCODE -7
#define GDIFF_ERR_OLDFILE -8
#define GDIFF_ERR_CHKSUMTYPE -9
#define GDIFF_ERR_CHECKSUM -10
#define GDIFF_ERR_CHECKSUM_TARGET -11
#define GDIFF_ERR_CHECKSUM_RESULT -12
/*--------------------------------------
* types
*------------------------------------*/
#ifndef AIX
#ifdef OSF1
#include <sys/types.h>
#else
typedef unsigned char uchar;
#endif
#endif
typedef struct _diffdata {
PRFileDesc* fSrc;
PRFileDesc* fOut;
PRFileDesc* fDiff;
uint8 checksumType;
uint8 checksumLength;
uchar* oldChecksum;
uchar* newChecksum;
PRBool bMacAppleSingle;
PRBool bWin32BoundImage;
uchar* databuf;
uint32 bufsize;
} DIFFDATA;
typedef DIFFDATA* pDIFFDATA;
/*--------------------------------------
* miscellaneous
*------------------------------------*/
#define APPFLAG_W32BOUND "autoinstall:Win32PE"
#define APPFLAG_APPLESINGLE "autoinstall:AppleSingle"
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif

View File

@@ -0,0 +1,111 @@
#!nmake
#
# The contents of this file are subject to the Netscape Public License
# Version 1.0 (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 Communicator client code,
# released March 31, 1998.
#
# 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.
#
# Contributors:
# Daniel Veditz <dveditz@netscape.com>
# Douglas Turner <dougt@netscape.com>
DEPTH=..\..
IGNORE_MANIFEST=1
MAKE_OBJ_TYPE = DLL
MODULE=xpinstall
DLL=.\$(OBJDIR)\$(MODULE).dll
DEFINES=-D_IMPL_NS_DOM -DWIN32_LEAN_AND_MEAN
LCFLAGS = \
$(LCFLAGS) \
$(DEFINES) \
$(NULL)
LINCS= \
-I$(PUBLIC)\xpinstall \
-I$(PUBLIC)\jar \
-I$(PUBLIC)\libreg \
-I$(PUBLIC)\netlib \
-I$(PUBLIC)\xpcom \
-I$(PUBLIC)\pref \
-I$(PUBLIC)\rdf \
-I$(PUBLIC)\js \
-I$(PUBLIC)\dom \
-I$(PUBLIC)\raptor \
-I$(PUBLIC)\nspr2 \
-I$(PUBLIC)\zlib \
-I$(PUBLIC)\xpfe\components \
$(NULL)
LLIBS = \
$(DIST)\lib\jar50.lib \
$(DIST)\lib\libreg32.lib \
$(DIST)\lib\netlib.lib \
$(DIST)\lib\xpcom.lib \
$(DIST)\lib\js3250.lib \
$(DIST)\lib\jsdombase_s.lib \
$(DIST)\lib\jsdomevents_s.lib \
$(DIST)\lib\zlib.lib \
$(DIST)\lib\plc3.lib \
$(LIBNSPR) \
$(NULL)
OBJS = \
.\$(OBJDIR)\nsInstall.obj \
.\$(OBJDIR)\nsInstallTrigger.obj \
.\$(OBJDIR)\nsInstallVersion.obj \
.\$(OBJDIR)\nsInstallFolder.obj \
.\$(OBJDIR)\nsJSInstall.obj \
.\$(OBJDIR)\nsJSInstallTriggerGlobal.obj \
.\$(OBJDIR)\nsJSInstallVersion.obj \
.\$(OBJDIR)\nsSoftwareUpdate.obj \
.\$(OBJDIR)\nsSoftwareUpdateRun.obj \
.\$(OBJDIR)\nsSoftwareUpdateStream.obj \
.\$(OBJDIR)\nsInstallFile.obj \
.\$(OBJDIR)\nsInstallDelete.obj \
.\$(OBJDIR)\nsInstallExecute.obj \
.\$(OBJDIR)\nsInstallPatch.obj \
.\$(OBJDIR)\nsInstallUninstall.obj \
.\$(OBJDIR)\nsInstallResources.obj \
.\$(OBJDIR)\nsTopProgressNotifier.obj \
.\$(OBJDIR)\nsLoggingProgressNotifier.obj\
.\$(OBJDIR)\ScheduledTasks.obj \
.\$(OBJDIR)\nsWinReg.obj \
.\$(OBJDIR)\nsJSWinReg.obj \
.\$(OBJDIR)\nsWinRegItem.obj \
.\$(OBJDIR)\nsWinRegValue.obj \
.\$(OBJDIR)\nsWinProfile.obj \
.\$(OBJDIR)\nsJSWinProfile.obj \
.\$(OBJDIR)\nsWinProfileItem.obj \
.\$(OBJDIR)\nsInstallProgressDialog.obj \
.\$(OBJDIR)\nsInstallFileOpItem.obj \
$(NULL)
include <$(DEPTH)\config\rules.mak>
install:: $(DLL)
$(MAKE_INSTALL) .\$(OBJDIR)\$(MODULE).lib $(DIST)\lib
$(MAKE_INSTALL) .\$(OBJDIR)\$(MODULE).dll $(DIST)\bin\components
clobber::
rm -f $(DIST)\lib\$(MODULE).lib
rm -f $(DIST)\bin\components\$(MODULE).dll

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,265 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Daniel Veditz <dveditz@netscape.com>
* Douglas Turner <dougt@netscape.com>
*/
#ifndef __NS_INSTALL_H__
#define __NS_INSTALL_H__
#include "nscore.h"
#include "nsISupports.h"
#include "jsapi.h"
#include "plevent.h"
#include "nsString.h"
#include "nsFileSpec.h"
#include "nsVector.h"
#include "nsHashtable.h"
#include "nsSoftwareUpdate.h"
#include "nsInstallObject.h"
#include "nsInstallVersion.h"
#include "nsIXPInstallProgress.h"
class nsInstallInfo
{
public:
nsInstallInfo(const nsString& fromURL, const nsString& localFile, long flags);
nsInstallInfo(nsVector* fromURL, nsVector* localFiles, long flags);
virtual ~nsInstallInfo();
nsString& GetFromURL(PRUint32 index = 0);
nsString& GetLocalFile(PRUint32 index = 0);
void GetArguments(nsString& args, PRUint32 index = 0);
long GetFlags();
PRBool IsMultipleTrigger();
static void DeleteVector(nsVector* vector);
private:
PRBool mMultipleTrigger;
nsresult mError;
long mFlags;
nsVector *mFromURLs;
nsVector *mLocalFiles;
};
class nsInstall
{
friend class nsWinReg;
friend class nsWinProfile;
public:
enum
{
BAD_PACKAGE_NAME = -200,
UNEXPECTED_ERROR = -201,
ACCESS_DENIED = -202,
TOO_MANY_CERTIFICATES = -203,
NO_INSTALLER_CERTIFICATE = -204,
NO_CERTIFICATE = -205,
NO_MATCHING_CERTIFICATE = -206,
UNKNOWN_JAR_FILE = -207,
INVALID_ARGUMENTS = -208,
ILLEGAL_RELATIVE_PATH = -209,
USER_CANCELLED = -210,
INSTALL_NOT_STARTED = -211,
SILENT_MODE_DENIED = -212,
NO_SUCH_COMPONENT = -213,
FILE_DOES_NOT_EXIST = -214,
FILE_READ_ONLY = -215,
FILE_IS_DIRECTORY = -216,
NETWORK_FILE_IS_IN_USE = -217,
APPLE_SINGLE_ERR = -218,
INVALID_PATH_ERR = -219,
PATCH_BAD_DIFF = -220,
PATCH_BAD_CHECKSUM_TARGET = -221,
PATCH_BAD_CHECKSUM_RESULT = -222,
UNINSTALL_FAILED = -223,
GESTALT_UNKNOWN_ERR = -5550,
GESTALT_INVALID_ARGUMENT = -5551,
SUCCESS = 0,
REBOOT_NEEDED = 999,
LIMITED_INSTALL = 0,
FULL_INSTALL = 1,
NO_STATUS_DLG = 2,
NO_FINALIZE_DLG = 4,
INSTALL_FILE_UNEXPECTED_MSG_ID = 0,
DETAILS_REPLACE_FILE_MSG_ID = 1,
DETAILS_INSTALL_FILE_MSG_ID = 2
};
nsInstall();
virtual ~nsInstall();
PRInt32 SetScriptObject(void* aScriptObject);
PRInt32 SaveWinRegPrototype(void* aScriptObject);
PRInt32 SaveWinProfilePrototype(void* aScriptObject);
JSObject* RetrieveWinRegPrototype(void);
JSObject* RetrieveWinProfilePrototype(void);
PRInt32 GetUserPackageName(nsString& aUserPackageName);
PRInt32 GetRegPackageName(nsString& aRegPackageName);
PRInt32 AbortInstall();
PRInt32 AddDirectory(const nsString& aRegName, const nsString& aVersion, const nsString& aJarSource, const nsString& aFolder, const nsString& aSubdir, PRBool aForceMode, PRInt32* aReturn);
PRInt32 AddDirectory(const nsString& aRegName, const nsString& aVersion, const nsString& aJarSource, const nsString& aFolder, const nsString& aSubdir, PRInt32* aReturn);
PRInt32 AddDirectory(const nsString& aRegName, const nsString& aJarSource, const nsString& aFolder, const nsString& aSubdir, PRInt32* aReturn);
PRInt32 AddDirectory(const nsString& aJarSource, PRInt32* aReturn);
PRInt32 AddSubcomponent(const nsString& aRegName, const nsString& aVersion, const nsString& aJarSource, const nsString& aFolder, const nsString& aTargetName, PRBool aForceMode, PRInt32* aReturn);
PRInt32 AddSubcomponent(const nsString& aRegName, const nsString& aVersion, const nsString& aJarSource, const nsString& aFolder, const nsString& aTargetName, PRInt32* aReturn);
PRInt32 AddSubcomponent(const nsString& aRegName, const nsString& aJarSource, const nsString& aFolder, const nsString& aTargetName, PRInt32* aReturn);
PRInt32 AddSubcomponent(const nsString& aJarSource, PRInt32* aReturn);
PRInt32 DeleteComponent(const nsString& aRegistryName, PRInt32* aReturn);
PRInt32 DeleteFile(const nsString& aFolder, const nsString& aRelativeFileName, PRInt32* aReturn);
PRInt32 DiskSpaceAvailable(const nsString& aFolder, PRInt32* aReturn);
PRInt32 Execute(const nsString& aJarSource, const nsString& aArgs, PRInt32* aReturn);
PRInt32 Execute(const nsString& aJarSource, PRInt32* aReturn);
PRInt32 FinalizeInstall(PRInt32* aReturn);
PRInt32 Gestalt(const nsString& aSelector, PRInt32* aReturn);
PRInt32 GetComponentFolder(const nsString& aComponentName, const nsString& aSubdirectory, nsString** aFolder);
PRInt32 GetComponentFolder(const nsString& aComponentName, nsString** aFolder);
PRInt32 GetFolder(const nsString& aTargetFolder, const nsString& aSubdirectory, nsString** aFolder);
PRInt32 GetFolder(const nsString& aTargetFolder, nsString** aFolder);
PRInt32 GetLastError(PRInt32* aReturn);
PRInt32 GetWinProfile(const nsString& aFolder, const nsString& aFile, JSContext* jscontext, JSClass* WinProfileClass, jsval* aReturn);
PRInt32 GetWinRegistry(JSContext* jscontext, JSClass* WinRegClass, jsval* aReturn);
PRInt32 Patch(const nsString& aRegName, const nsString& aVersion, const nsString& aJarSource, const nsString& aFolder, const nsString& aTargetName, PRInt32* aReturn);
PRInt32 Patch(const nsString& aRegName, const nsString& aJarSource, const nsString& aFolder, const nsString& aTargetName, PRInt32* aReturn);
PRInt32 ResetError();
PRInt32 SetPackageFolder(const nsString& aFolder);
PRInt32 StartInstall(const nsString& aUserPackageName, const nsString& aPackageName, const nsString& aVersion, PRInt32* aReturn);
PRInt32 Uninstall(const nsString& aPackageName, PRInt32* aReturn);
PRInt32 FileOpDirCreate(nsFileSpec& aTarget, PRInt32* aReturn);
PRInt32 FileOpDirGetParent(nsFileSpec& aTarget, nsFileSpec* aReturn);
PRInt32 FileOpDirRemove(nsFileSpec& aTarget, PRInt32 aFlags, PRInt32* aReturn);
PRInt32 FileOpDirRename(nsFileSpec& aSrc, nsFileSpec& aTarget, PRInt32* aReturn);
PRInt32 FileOpFileCopy(nsFileSpec& aSrc, nsFileSpec& aTarget, PRInt32* aReturn);
PRInt32 FileOpFileDelete(nsFileSpec& aTarget, PRInt32 aFlags, PRInt32* aReturn);
PRInt32 FileOpFileExists(nsFileSpec& aTarget, PRBool* aReturn);
PRInt32 FileOpFileExecute(nsFileSpec& aTarget, nsString& aParams, PRInt32* aReturn);
PRInt32 FileOpFileGetNativeVersion(nsFileSpec& aTarget, nsString* aReturn);
PRInt32 FileOpFileGetDiskSpaceAvailable(nsFileSpec& aTarget, PRUint32* aReturn);
PRInt32 FileOpFileGetModDate(nsFileSpec& aTarget, nsFileSpec::TimeStamp* aReturn);
PRInt32 FileOpFileGetSize(nsFileSpec& aTarget, PRUint32* aReturn);
PRInt32 FileOpFileIsDirectory(nsFileSpec& aTarget, PRBool* aReturn);
PRInt32 FileOpFileIsFile(nsFileSpec& aTarget, PRBool* aReturn);
PRInt32 FileOpFileModDateChanged(nsFileSpec& aTarget, nsFileSpec::TimeStamp& aOldStamp, PRBool* aReturn);
PRInt32 FileOpFileMove(nsFileSpec& aSrc, nsFileSpec& aTarget, PRInt32* aReturn);
PRInt32 FileOpFileRename(nsFileSpec& aSrc, nsFileSpec& aTarget, PRInt32* aReturn);
PRInt32 FileOpFileWinShortcutCreate(nsFileSpec& aTarget, PRInt32 aFlags, PRInt32* aReturn);
PRInt32 FileOpFileMacAliasCreate(nsFileSpec& aTarget, PRInt32 aFlags, PRInt32* aReturn);
PRInt32 FileOpFileUnixLinkCreate(nsFileSpec& aTarget, PRInt32 aFlags, PRInt32* aReturn);
PRInt32 ExtractFileFromJar(const nsString& aJarfile, nsFileSpec* aSuggestedName, nsFileSpec** aRealName);
void AddPatch(nsHashKey *aKey, nsFileSpec* fileName);
void GetPatch(nsHashKey *aKey, nsFileSpec* fileName);
void GetJarFileLocation(nsString& aFile);
void SetJarFileLocation(const nsString& aFile);
void GetInstallArguments(nsString& args);
void SetInstallArguments(const nsString& args);
private:
JSObject* mScriptObject;
JSObject* mWinRegObject;
JSObject* mWinProfileObject;
nsString mJarFileLocation;
void* mJarFileData;
nsString mInstallArguments;
PRBool mUserCancelled;
PRBool mUninstallPackage;
PRBool mRegisterPackage;
nsString mRegistryPackageName; /* Name of the package we are installing */
nsString mUIName; /* User-readable package name */
nsInstallVersion* mVersionInfo; /* Component version info */
nsVector* mInstalledFiles;
nsHashtable* mPatchList;
nsIXPInstallProgress *mNotifier;
PRInt32 mLastError;
void ParseFlags(int flags);
PRInt32 SanityCheck(void);
void GetTime(nsString &aString);
PRInt32 GetQualifiedRegName(const nsString& name, nsString& qualifiedRegName );
PRInt32 GetQualifiedPackageName( const nsString& name, nsString& qualifiedName );
void CurrentUserNode(nsString& userRegNode);
PRBool BadRegName(const nsString& regName);
PRInt32 SaveError(PRInt32 errcode);
void CleanUp();
PRInt32 OpenJARFile(void);
void CloseJARFile(void);
PRInt32 ExtractDirEntries(const nsString& directory, nsVector *paths);
PRInt32 ScheduleForInstall(nsInstallObject* ob);
};
#endif

View File

@@ -0,0 +1,235 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Daniel Veditz <dveditz@netscape.com>
* Douglas Turner <dougt@netscape.com>
*/
#include "prmem.h"
#include "nsFileSpec.h"
#include "VerReg.h"
#include "ScheduledTasks.h"
#include "nsInstallDelete.h"
#include "nsInstallResources.h"
#include "nsInstall.h"
#include "nsIDOMInstallVersion.h"
nsInstallDelete::nsInstallDelete( nsInstall* inInstall,
const nsString& folderSpec,
const nsString& inPartialPath,
PRInt32 *error)
: nsInstallObject(inInstall)
{
if ((folderSpec == "null") || (inInstall == NULL))
{
*error = nsInstall::INVALID_ARGUMENTS;
return;
}
mDeleteStatus = DELETE_FILE;
mFinalFile = nsnull;
mRegistryName = "";
mFinalFile = new nsFileSpec(folderSpec);
*mFinalFile += inPartialPath;
*error = ProcessInstallDelete();
}
nsInstallDelete::nsInstallDelete( nsInstall* inInstall,
const nsString& inComponentName,
PRInt32 *error)
: nsInstallObject(inInstall)
{
if (inInstall == NULL)
{
*error = nsInstall::INVALID_ARGUMENTS;
return;
}
mDeleteStatus = DELETE_COMPONENT;
mFinalFile = nsnull;
mRegistryName = inComponentName;
*error = ProcessInstallDelete();
}
nsInstallDelete::~nsInstallDelete()
{
if (mFinalFile == nsnull)
delete mFinalFile;
}
PRInt32 nsInstallDelete::Prepare()
{
// no set-up necessary
return nsInstall::SUCCESS;
}
PRInt32 nsInstallDelete::Complete()
{
PRInt32 err = nsInstall::SUCCESS;
if (mInstall == NULL)
return nsInstall::INVALID_ARGUMENTS;
if (mDeleteStatus == DELETE_COMPONENT)
{
char* temp = mRegistryName.ToNewCString();
err = VR_Remove(temp);
delete [] temp;
}
if ((mDeleteStatus == DELETE_FILE) || (err == REGERR_OK))
{
err = NativeComplete();
}
else
{
err = nsInstall::UNEXPECTED_ERROR;
}
return err;
}
void nsInstallDelete::Abort()
{
}
char* nsInstallDelete::toString()
{
char* buffer = new char[1024];
if (mDeleteStatus == DELETE_COMPONENT)
{
sprintf( buffer, nsInstallResources::GetDeleteComponentString(), nsAutoCString(mRegistryName));
}
else
{
if (mFinalFile)
sprintf( buffer, nsInstallResources::GetDeleteFileString(), mFinalFile->GetCString());
}
return buffer;
}
PRBool
nsInstallDelete::CanUninstall()
{
return PR_FALSE;
}
PRBool
nsInstallDelete::RegisterPackageNode()
{
return PR_FALSE;
}
PRInt32 nsInstallDelete::ProcessInstallDelete()
{
PRInt32 err;
char* tempCString = nsnull;
if (mDeleteStatus == DELETE_COMPONENT)
{
/* Check if the component is in the registry */
tempCString = mRegistryName.ToNewCString();
err = VR_InRegistry( tempCString );
if (err != REGERR_OK)
{
return err;
}
else
{
char* tempRegistryString;
tempRegistryString = (char*)PR_Calloc(MAXREGPATHLEN, sizeof(char));
err = VR_GetPath( tempCString , MAXREGPATHLEN, tempRegistryString);
if (err == REGERR_OK)
{
if (mFinalFile)
delete mFinalFile;
mFinalFile = new nsFileSpec(tempRegistryString);
}
PR_FREEIF(tempRegistryString);
}
}
if(tempCString)
delete [] tempCString;
if (mFinalFile->Exists())
{
if (mFinalFile->IsFile())
{
err = nsInstall::SUCCESS;
}
else
{
err = nsInstall::FILE_IS_DIRECTORY;
}
}
else
{
err = nsInstall::FILE_DOES_NOT_EXIST;
}
return err;
}
PRInt32 nsInstallDelete::NativeComplete()
{
if (mFinalFile->Exists())
{
if (mFinalFile->IsFile())
{
return DeleteFileNowOrSchedule(*mFinalFile);
}
else
{
return nsInstall::FILE_IS_DIRECTORY;
}
}
return nsInstall::FILE_DOES_NOT_EXIST;
}

View File

@@ -0,0 +1,78 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Daniel Veditz <dveditz@netscape.com>
* Douglas Turner <dougt@netscape.com>
*/
#ifndef nsInstallDelete_h__
#define nsInstallDelete_h__
#include "prtypes.h"
#include "nsString.h"
#include "nsInstallObject.h"
#include "nsInstall.h"
#define DELETE_COMPONENT 1
#define DELETE_FILE 2
class nsInstallDelete : public nsInstallObject
{
public:
nsInstallDelete( nsInstall* inInstall,
const nsString& folderSpec,
const nsString& inPartialPath,
PRInt32 *error);
nsInstallDelete( nsInstall* inInstall,
const nsString& ,
PRInt32 *error);
virtual ~nsInstallDelete();
PRInt32 Prepare();
PRInt32 Complete();
void Abort();
char* toString();
PRBool CanUninstall();
PRBool RegisterPackageNode();
private:
/* Private Fields */
nsFileSpec* mFinalFile;
nsString mRegistryName;
PRInt32 mDeleteStatus;
PRInt32 ProcessInstallDelete();
PRInt32 NativeComplete();
};
#endif /* nsInstallDelete_h__ */

View File

@@ -0,0 +1,136 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Daniel Veditz <dveditz@netscape.com>
* Douglas Turner <dougt@netscape.com>
*/
#include "prmem.h"
#include "nsFileSpec.h"
#include "VerReg.h"
#include "nsInstallExecute.h"
#include "nsInstallResources.h"
#include "ScheduledTasks.h"
#include "nsInstall.h"
#include "nsIDOMInstallVersion.h"
nsInstallExecute:: nsInstallExecute( nsInstall* inInstall,
const nsString& inJarLocation,
const nsString& inArgs,
PRInt32 *error)
: nsInstallObject(inInstall)
{
if ((inInstall == nsnull) || (inJarLocation == "null"))
{
*error = nsInstall::INVALID_ARGUMENTS;
return;
}
mJarLocation = inJarLocation;
mArgs = inArgs;
mExecutableFile = nsnull;
}
nsInstallExecute::~nsInstallExecute()
{
if (mExecutableFile)
delete mExecutableFile;
}
PRInt32 nsInstallExecute::Prepare()
{
if (mInstall == NULL || mJarLocation == "null")
return nsInstall::INVALID_ARGUMENTS;
return mInstall->ExtractFileFromJar(mJarLocation, nsnull, &mExecutableFile);
}
PRInt32 nsInstallExecute::Complete()
{
if (mExecutableFile == nsnull)
return nsInstall::INVALID_ARGUMENTS;
nsFileSpec app( *mExecutableFile);
if (!app.Exists())
{
return nsInstall::INVALID_ARGUMENTS;
}
PRInt32 result = app.Execute( mArgs );
DeleteFileNowOrSchedule( app );
return result;
}
void nsInstallExecute::Abort()
{
/* Get the names */
if (mExecutableFile == nsnull)
return;
DeleteFileNowOrSchedule(*mExecutableFile);
}
char* nsInstallExecute::toString()
{
char* buffer = new char[1024];
// if the FileSpec is NULL, just us the in jar file name.
if (mExecutableFile == nsnull)
{
char *tempString = mJarLocation.ToNewCString();
sprintf( buffer, nsInstallResources::GetExecuteString(), tempString);
delete [] tempString;
}
else
{
sprintf( buffer, nsInstallResources::GetExecuteString(), mExecutableFile->GetCString());
}
return buffer;
}
PRBool
nsInstallExecute::CanUninstall()
{
return PR_FALSE;
}
PRBool
nsInstallExecute::RegisterPackageNode()
{
return PR_FALSE;
}

View File

@@ -0,0 +1,73 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Daniel Veditz <dveditz@netscape.com>
* Douglas Turner <dougt@netscape.com>
*/
#ifndef nsInstallExecute_h__
#define nsInstallExecute_h__
#include "prtypes.h"
#include "nsString.h"
#include "nsInstallObject.h"
#include "nsInstall.h"
#include "nsIDOMInstallVersion.h"
class nsInstallExecute : public nsInstallObject
{
public:
nsInstallExecute( nsInstall* inInstall,
const nsString& inJarLocation,
const nsString& inArgs,
PRInt32 *error);
virtual ~nsInstallExecute();
PRInt32 Prepare();
PRInt32 Complete();
void Abort();
char* toString();
PRBool CanUninstall();
PRBool RegisterPackageNode();
private:
nsString mJarLocation; // Location in the JAR
nsString mArgs; // command line arguments
nsFileSpec *mExecutableFile; // temporary file location
PRInt32 NativeComplete(void);
void NativeAbort(void);
};
#endif /* nsInstallExecute_h__ */

View File

@@ -0,0 +1,366 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Daniel Veditz <dveditz@netscape.com>
* Douglas Turner <dougt@netscape.com>
*/
#include "nsInstallFile.h"
#include "nsFileSpec.h"
#include "VerReg.h"
#include "ScheduledTasks.h"
#include "nsInstall.h"
#include "nsIDOMInstallVersion.h"
#include "nsInstallResources.h"
/* Public Methods */
/* Constructor
inInstall - softUpdate object we belong to
inComponentName - full path of the registry component
inVInfo - full version info
inJarLocation - location inside the JAR file
inFinalFileSpec - final location on disk
*/
nsInstallFile::nsInstallFile(nsInstall* inInstall,
const nsString& inComponentName,
const nsString& inVInfo,
const nsString& inJarLocation,
const nsString& folderSpec,
const nsString& inPartialPath,
PRBool forceInstall,
PRInt32 *error)
: nsInstallObject(inInstall)
{
mVersionRegistryName = nsnull;
mJarLocation = nsnull;
mExtracedFile = nsnull;
mFinalFile = nsnull;
mVersionInfo = nsnull;
mUpgradeFile = PR_FALSE;
if ((folderSpec == "null") || (inInstall == NULL))
{
*error = nsInstall::INVALID_ARGUMENTS;
return;
}
/* Check for existence of the newer version */
PRBool versionNewer = PR_FALSE; // Is this a newer version
char* qualifiedRegNameString = inComponentName.ToNewCString();
if ( (forceInstall == PR_FALSE ) && (inVInfo != "") && ( VR_ValidateComponent( qualifiedRegNameString ) == 0 ) )
{
nsInstallVersion *newVersion = new nsInstallVersion();
newVersion->Init(inVInfo);
VERSION versionStruct;
VR_GetVersion( qualifiedRegNameString, &versionStruct );
nsInstallVersion* oldVersion = new nsInstallVersion();
oldVersion->Init(versionStruct.major,
versionStruct.minor,
versionStruct.release,
versionStruct.build);
PRInt32 areTheyEqual;
newVersion->CompareTo(oldVersion, &areTheyEqual);
delete oldVersion;
delete newVersion;
if (areTheyEqual == nsIDOMInstallVersion::MAJOR_DIFF_MINUS ||
areTheyEqual == nsIDOMInstallVersion::MINOR_DIFF_MINUS ||
areTheyEqual == nsIDOMInstallVersion::REL_DIFF_MINUS ||
areTheyEqual == nsIDOMInstallVersion::BLD_DIFF_MINUS )
{
// the file to be installed is OLDER than what is on disk. Return error
delete qualifiedRegNameString;
*error = areTheyEqual;
return;
}
}
delete qualifiedRegNameString;
mFinalFile = new nsFileSpec(folderSpec);
*mFinalFile += inPartialPath;
mReplaceFile = mFinalFile->Exists();
if (mReplaceFile == PR_FALSE)
{
nsFileSpec parent;
mFinalFile->GetParent(parent);
nsFileSpec makeDirs(parent.GetCString(), PR_TRUE);
}
mForceInstall = forceInstall;
mVersionRegistryName = new nsString(inComponentName);
mJarLocation = new nsString(inJarLocation);
mVersionInfo = new nsString(inVInfo);
nsString regPackageName;
mInstall->GetRegPackageName(regPackageName);
// determine Child status
if ( regPackageName == "" )
{
// in the "current communicator package" absolute pathnames (start
// with slash) indicate shared files -- all others are children
mChildFile = ( mVersionRegistryName->CharAt(0) != '/' );
}
else
{
// there is no "starts with" api in nsString. LAME!
nsString startsWith;
mVersionRegistryName->Left(startsWith, regPackageName.Length());
if (startsWith.Equals(regPackageName))
{
mChildFile = true;
}
else
{
mChildFile = false;
}
}
}
nsInstallFile::~nsInstallFile()
{
if (mVersionRegistryName)
delete mVersionRegistryName;
if (mJarLocation)
delete mJarLocation;
if (mExtracedFile)
delete mExtracedFile;
if (mFinalFile)
delete mFinalFile;
if (mVersionInfo)
delete mVersionInfo;
}
/* Prepare
* Extracts file out of the JAR archive
*/
PRInt32 nsInstallFile::Prepare()
{
if (mInstall == nsnull || mFinalFile == nsnull || mJarLocation == nsnull )
return nsInstall::INVALID_ARGUMENTS;
return mInstall->ExtractFileFromJar(*mJarLocation, mFinalFile, &mExtracedFile);
}
/* Complete
* Completes the install:
* - move the downloaded file to the final location
* - updates the registry
*/
PRInt32 nsInstallFile::Complete()
{
PRInt32 err;
if (mInstall == nsnull || mVersionRegistryName == nsnull || mFinalFile == nsnull )
{
return nsInstall::INVALID_ARGUMENTS;
}
err = CompleteFileMove();
if ( 0 == err || nsInstall::REBOOT_NEEDED == err )
{
err = RegisterInVersionRegistry();
}
return err;
}
void nsInstallFile::Abort()
{
if (mExtracedFile != nsnull)
mExtracedFile->Delete(PR_FALSE);
}
char* nsInstallFile::toString()
{
char* buffer = new char[1024];
if (mFinalFile == nsnull)
{
sprintf( buffer, nsInstallResources::GetInstallFileString(), nsnull);
}
else if (mReplaceFile)
{
// we are replacing this file.
sprintf( buffer, nsInstallResources::GetReplaceFileString(), mFinalFile->GetCString());
}
else
{
sprintf( buffer, nsInstallResources::GetInstallFileString(), mFinalFile->GetCString());
}
return buffer;
}
PRInt32 nsInstallFile::CompleteFileMove()
{
int result = 0;
if (mExtracedFile == nsnull)
{
return -1;
}
if ( *mExtracedFile == *mFinalFile )
{
/* No need to rename, they are the same */
result = 0;
}
else
{
result = ReplaceFileNowOrSchedule(*mExtracedFile, *mFinalFile );
}
return result;
}
PRInt32
nsInstallFile::RegisterInVersionRegistry()
{
int refCount;
nsString regPackageName;
mInstall->GetRegPackageName(regPackageName);
// Register file and log for Uninstall
if (!mChildFile)
{
int found;
if (regPackageName != "")
{
found = VR_UninstallFileExistsInList( (char*)(const char*)nsAutoCString(regPackageName) ,
(char*)(const char*)nsAutoCString(*mVersionRegistryName));
}
else
{
found = VR_UninstallFileExistsInList( "", (char*)(const char*)nsAutoCString(*mVersionRegistryName) );
}
if (found != REGERR_OK)
mUpgradeFile = PR_FALSE;
else
mUpgradeFile = PR_TRUE;
}
else if (REGERR_OK == VR_InRegistry( (char*)(const char*)nsAutoCString(*mVersionRegistryName)))
{
mUpgradeFile = PR_TRUE;
}
else
{
mUpgradeFile = PR_FALSE;
}
if ( REGERR_OK != VR_GetRefCount( (char*)(const char*)nsAutoCString(*mVersionRegistryName), &refCount ))
{
refCount = 0;
}
VR_Install( (char*)(const char*)nsAutoCString(*mVersionRegistryName),
(char*)(const char*)mFinalFile->GetNativePathCString(), // DO NOT CHANGE THIS.
(char*)(const char*)nsAutoCString(*mVersionInfo),
PR_FALSE );
if (mUpgradeFile)
{
if (refCount == 0)
VR_SetRefCount( (char*)(const char*)nsAutoCString(*mVersionRegistryName), 1 );
else
VR_SetRefCount( (char*)(const char*)nsAutoCString(*mVersionRegistryName), refCount ); //FIX?? what should the ref count be/
}
else
{
if (refCount != 0)
{
VR_SetRefCount( (char*)(const char*)nsAutoCString(*mVersionRegistryName), refCount + 1 );
}
else
{
if (mReplaceFile)
VR_SetRefCount( (char*)(const char*)nsAutoCString(*mVersionRegistryName), 2 );
else
VR_SetRefCount( (char*)(const char*)nsAutoCString(*mVersionRegistryName), 1 );
}
}
if ( !mChildFile && !mUpgradeFile )
{
if (regPackageName != "")
{
VR_UninstallAddFileToList( (char*)(const char*)nsAutoCString(regPackageName),
(char*)(const char*)nsAutoCString(*mVersionRegistryName));
}
else
{
VR_UninstallAddFileToList( "", (char*)(const char*)nsAutoCString(*mVersionRegistryName) );
}
}
return nsInstall::SUCCESS;
}
/* CanUninstall
* InstallFile() installs files which can be uninstalled,
* hence this function returns true.
*/
PRBool
nsInstallFile::CanUninstall()
{
return TRUE;
}
/* RegisterPackageNode
* InstallFile() installs files which need to be registered,
* hence this function returns true.
*/
PRBool
nsInstallFile::RegisterPackageNode()
{
return TRUE;
}

View File

@@ -0,0 +1,93 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Daniel Veditz <dveditz@netscape.com>
* Douglas Turner <dougt@netscape.com>
*/
#ifndef nsInstallFile_h__
#define nsInstallFile_h__
#include "prtypes.h"
#include "nsString.h"
#include "nsInstallObject.h"
#include "nsInstall.h"
#include "nsInstallVersion.h"
class nsInstallFile : public nsInstallObject
{
public:
/*************************************************************
* Public Methods
*
* Constructor
* inSoftUpdate - softUpdate object we belong to
* inComponentName - full path of the registry component
* inVInfo - full version info
* inJarLocation - location inside the JAR file
* inFinalFileSpec - final location on disk
*************************************************************/
nsInstallFile( nsInstall* inInstall,
const nsString& inVRName,
const nsString& inVInfo,
const nsString& inJarLocation,
const nsString& folderSpec,
const nsString& inPartialPath,
PRBool forceInstall,
PRInt32 *error);
virtual ~nsInstallFile();
PRInt32 Prepare();
PRInt32 Complete();
void Abort();
char* toString();
PRBool CanUninstall();
PRBool RegisterPackageNode();
private:
/* Private Fields */
nsString* mVersionInfo; /* Version info for this file*/
nsString* mJarLocation; /* Location in the JAR */
nsFileSpec* mExtracedFile; /* temporary file location */
nsFileSpec* mFinalFile; /* final file destination */
nsString* mVersionRegistryName; /* full version path */
PRBool mForceInstall; /* whether install is forced */
PRBool mReplaceFile; /* whether file exists */
PRBool mChildFile; /* whether file is a child */
PRBool mUpgradeFile; /* whether file is an upgrade */
PRInt32 CompleteFileMove();
PRInt32 RegisterInVersionRegistry();
};
#endif /* nsInstallFile_h__ */

View File

@@ -0,0 +1,38 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsInstallFileOpEnums_h__
#define nsInstallFileOpEnums_h__
typedef enum nsInstallFileOpEnums {
NS_FOP_DIR_CREATE = 0,
NS_FOP_DIR_REMOVE = 1,
NS_FOP_DIR_RENAME = 2,
NS_FOP_FILE_COPY = 3,
NS_FOP_FILE_DELETE = 4,
NS_FOP_FILE_EXECUTE = 5,
NS_FOP_FILE_MOVE = 6,
NS_FOP_FILE_RENAME = 7,
NS_FOP_WIN_SHORTCUT_CREATE = 8,
NS_FOP_MAC_ALIAS_CREATE = 9,
NS_FOP_UNIX_LINK_CREATE = 10,
NS_FOP_FILE_SET_STAT = 11
} nsInstallFileOpEnums;
#endif /* nsInstallFileOpEnums_h__ */

View File

@@ -0,0 +1,316 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nspr.h"
#include "nsInstall.h"
#include "nsInstallFileOpEnums.h"
#include "nsInstallFileOpItem.h"
/* Public Methods */
nsInstallFileOpItem::nsInstallFileOpItem(nsInstall* aInstallObj,
PRInt32 aCommand,
nsFileSpec& aTarget,
PRInt32 aFlags,
PRInt32* aReturn)
:nsInstallObject(aInstallObj)
{
mIObj = aInstallObj;
mCommand = aCommand;
mFlags = aFlags;
mSrc = nsnull;
mParams = nsnull;
mTarget = new nsFileSpec(aTarget);
*aReturn = NS_OK;
}
nsInstallFileOpItem::nsInstallFileOpItem(nsInstall* aInstallObj,
PRInt32 aCommand,
nsFileSpec& aSrc,
nsFileSpec& aTarget,
PRInt32* aReturn)
:nsInstallObject(aInstallObj)
{
mIObj = aInstallObj;
mCommand = aCommand;
mFlags = 0;
mSrc = new nsFileSpec(aSrc);
mParams = nsnull;
mTarget = new nsFileSpec(aTarget);
*aReturn = NS_OK;
}
nsInstallFileOpItem::nsInstallFileOpItem(nsInstall* aInstallObj,
PRInt32 aCommand,
nsFileSpec& aTarget,
PRInt32* aReturn)
:nsInstallObject(aInstallObj)
{
mIObj = aInstallObj;
mCommand = aCommand;
mFlags = 0;
mSrc = nsnull;
mParams = nsnull;
mTarget = new nsFileSpec(aTarget);
*aReturn = NS_OK;
}
nsInstallFileOpItem::nsInstallFileOpItem(nsInstall* aInstallObj,
PRInt32 aCommand,
nsFileSpec& aTarget,
nsString& aParams,
PRInt32* aReturn)
:nsInstallObject(aInstallObj)
{
mIObj = aInstallObj;
mCommand = aCommand;
mFlags = 0;
mSrc = nsnull;
mParams = new nsString(aParams);
mTarget = new nsFileSpec(aTarget);
*aReturn = NS_OK;
}
nsInstallFileOpItem::~nsInstallFileOpItem()
{
if(mSrc)
delete mSrc;
if(mTarget)
delete mTarget;
}
PRInt32 nsInstallFileOpItem::Complete()
{
PRInt32 aReturn = NS_OK;
switch(mCommand)
{
case NS_FOP_DIR_CREATE:
NativeFileOpDirCreate(mTarget);
break;
case NS_FOP_DIR_REMOVE:
NativeFileOpDirRemove(mTarget, mFlags);
break;
case NS_FOP_DIR_RENAME:
NativeFileOpDirRename(mSrc, mTarget);
break;
case NS_FOP_FILE_COPY:
NativeFileOpFileCopy(mSrc, mTarget);
break;
case NS_FOP_FILE_DELETE:
NativeFileOpFileDelete(mTarget, mFlags);
break;
case NS_FOP_FILE_EXECUTE:
NativeFileOpFileExecute(mTarget, mParams);
break;
case NS_FOP_FILE_MOVE:
NativeFileOpFileMove(mSrc, mTarget);
break;
case NS_FOP_FILE_RENAME:
NativeFileOpFileRename(mSrc, mTarget);
break;
case NS_FOP_WIN_SHORTCUT_CREATE:
NativeFileOpWinShortcutCreate();
break;
case NS_FOP_MAC_ALIAS_CREATE:
NativeFileOpMacAliasCreate();
break;
case NS_FOP_UNIX_LINK_CREATE:
NativeFileOpUnixLinkCreate();
break;
}
return aReturn;
}
float nsInstallFileOpItem::GetInstallOrder()
{
return 3;
}
char* nsInstallFileOpItem::toString()
{
nsString result;
char* resultCString;
switch(mCommand)
{
case NS_FOP_FILE_COPY:
result = "Copy file: ";
result.Append(mSrc->GetNativePathCString());
result.Append(" to ");
result.Append(mTarget->GetNativePathCString());
resultCString = result.ToNewCString();
break;
case NS_FOP_FILE_DELETE:
result = "Delete file: ";
result.Append(mTarget->GetNativePathCString());
resultCString = result.ToNewCString();
break;
case NS_FOP_FILE_MOVE:
result = "Move file: ";
result.Append(mSrc->GetNativePathCString());
result.Append(" to ");
result.Append(mTarget->GetNativePathCString());
resultCString = result.ToNewCString();
break;
case NS_FOP_FILE_RENAME:
result = "Rename file: ";
result.Append(mTarget->GetNativePathCString());
resultCString = result.ToNewCString();
break;
case NS_FOP_DIR_CREATE:
result = "Create Folder: ";
result.Append(mTarget->GetNativePathCString());
resultCString = result.ToNewCString();
break;
case NS_FOP_DIR_REMOVE:
result = "Remove Folder: ";
result.Append(mTarget->GetNativePathCString());
resultCString = result.ToNewCString();
break;
case NS_FOP_WIN_SHORTCUT_CREATE:
break;
case NS_FOP_MAC_ALIAS_CREATE:
break;
case NS_FOP_UNIX_LINK_CREATE:
break;
case NS_FOP_FILE_SET_STAT:
result = "Set file stat: ";
result.Append(mTarget->GetNativePathCString());
resultCString = result.ToNewCString();
break;
default:
result = "Unkown file operation command!";
resultCString = result.ToNewCString();
break;
}
return resultCString;
}
PRInt32 nsInstallFileOpItem::Prepare()
{
return NULL;
}
void nsInstallFileOpItem::Abort()
{
}
/* Private Methods */
/* CanUninstall
* InstallFileOpItem() does not install any files which can be uninstalled,
* hence this function returns false.
*/
PRBool
nsInstallFileOpItem::CanUninstall()
{
return FALSE;
}
/* RegisterPackageNode
* InstallFileOpItem() does notinstall files which need to be registered,
* hence this function returns false.
*/
PRBool
nsInstallFileOpItem::RegisterPackageNode()
{
return FALSE;
}
//
// File operation functions begin here
//
PRInt32
nsInstallFileOpItem::NativeFileOpDirCreate(nsFileSpec* aTarget)
{
aTarget->CreateDirectory();
return NS_OK;
}
PRInt32
nsInstallFileOpItem::NativeFileOpDirRemove(nsFileSpec* aTarget, PRInt32 aFlags)
{
aTarget->Delete(aFlags);
return NS_OK;
}
PRInt32
nsInstallFileOpItem::NativeFileOpDirRename(nsFileSpec* aSrc, nsFileSpec* aTarget)
{
aSrc->Rename(*aTarget);
return NS_OK;
}
PRInt32
nsInstallFileOpItem::NativeFileOpFileCopy(nsFileSpec* aSrc, nsFileSpec* aTarget)
{
aSrc->Copy(*aTarget);
return NS_OK;
}
PRInt32
nsInstallFileOpItem::NativeFileOpFileDelete(nsFileSpec* aTarget, PRInt32 aFlags)
{
aTarget->Delete(aFlags);
return NS_OK;
}
PRInt32
nsInstallFileOpItem::NativeFileOpFileExecute(nsFileSpec* aTarget, nsString* aParams)
{
aTarget->Execute(*aParams);
return NS_OK;
}
PRInt32
nsInstallFileOpItem::NativeFileOpFileMove(nsFileSpec* aSrc, nsFileSpec* aTarget)
{
aSrc->Move(*aTarget);
return NS_OK;
}
PRInt32
nsInstallFileOpItem::NativeFileOpFileRename(nsFileSpec* aSrc, nsFileSpec* aTarget)
{
aSrc->Rename(*aTarget);
return NS_OK;
}
PRInt32
nsInstallFileOpItem::NativeFileOpWinShortcutCreate()
{
return NS_OK;
}
PRInt32
nsInstallFileOpItem::NativeFileOpMacAliasCreate()
{
return NS_OK;
}
PRInt32
nsInstallFileOpItem::NativeFileOpUnixLinkCreate()
{
return NS_OK;
}

View File

@@ -0,0 +1,111 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsInstallFileOpItem_h__
#define nsInstallFileOpItem_h__
#include "prtypes.h"
#include "nsFileSpec.h"
#include "nsSoftwareUpdate.h"
#include "nsInstallObject.h"
#include "nsInstall.h"
class nsInstallFileOpItem : public nsInstallObject
{
public:
/* Public Fields */
/* Public Methods */
// used by:
// FileOpFileDelete()
nsInstallFileOpItem(nsInstall* installObj,
PRInt32 aCommand,
nsFileSpec& aTarget,
PRInt32 aFlags,
PRInt32* aReturn);
// used by:
// FileOpDirRemove()
// FileOpDirRename()
// FileOpFileCopy()
// FileOpFileMove()
// FileOpFileRename()
nsInstallFileOpItem(nsInstall* installObj,
PRInt32 aCommand,
nsFileSpec& aSrc,
nsFileSpec& aTarget,
PRInt32* aReturn);
// used by:
// FileOpDirCreate()
nsInstallFileOpItem(nsInstall* aInstallObj,
PRInt32 aCommand,
nsFileSpec& aTarget,
PRInt32* aReturn);
// used by:
// FileOpFileExecute()
nsInstallFileOpItem(nsInstall* aInstallObj,
PRInt32 aCommand,
nsFileSpec& aTarget,
nsString& aParams,
PRInt32* aReturn);
~nsInstallFileOpItem();
PRInt32 Prepare(void);
PRInt32 Complete();
char* toString();
void Abort();
float GetInstallOrder();
/* should these be protected? */
PRBool CanUninstall();
PRBool RegisterPackageNode();
private:
/* Private Fields */
nsInstall* mIObj; // initiating Install object
nsFileSpec* mSrc;
nsFileSpec* mTarget;
nsString* mParams;
long mFStat;
PRInt32 mFlags;
PRInt32 mCommand;
/* Private Methods */
PRInt32 NativeFileOpDirCreate(nsFileSpec* aTarget);
PRInt32 NativeFileOpDirRemove(nsFileSpec* aTarget, PRInt32 aFlags);
PRInt32 NativeFileOpDirRename(nsFileSpec* aSrc, nsFileSpec* aTarget);
PRInt32 NativeFileOpFileCopy(nsFileSpec* aSrc, nsFileSpec* aTarget);
PRInt32 NativeFileOpFileDelete(nsFileSpec* aTarget, PRInt32 aFlags);
PRInt32 NativeFileOpFileExecute(nsFileSpec* aTarget, nsString* aParams);
PRInt32 NativeFileOpFileMove(nsFileSpec* aSrc, nsFileSpec* aTarget);
PRInt32 NativeFileOpFileRename(nsFileSpec* aSrc, nsFileSpec* aTarget);
PRInt32 NativeFileOpWinShortcutCreate();
PRInt32 NativeFileOpMacAliasCreate();
PRInt32 NativeFileOpUnixLinkCreate();
};
#endif /* nsInstallFileOpItem_h__ */

View File

@@ -0,0 +1,336 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Daniel Veditz <dveditz@netscape.com>
* Douglas Turner <dougt@netscape.com>
*/
#include "nsInstall.h"
#include "nsInstallFolder.h"
#include "nscore.h"
#include "prtypes.h"
#include "nsRepository.h"
#include "nsString.h"
#include "nsFileSpec.h"
#include "nsSpecialSystemDirectory.h"
#include "nsFileLocations.h"
#include "nsIFileLocator.h"
struct DirectoryTable
{
char * directoryName; /* The formal directory name */
PRInt32 folderEnum; /* Directory ID */
};
struct DirectoryTable DirectoryTable[] =
{
{"Plugins", 100 },
{"Program", 101 },
{"Communicator", 102 },
{"User Pick", 103 },
{"Temporary", 104 },
{"Installed", 105 },
{"Current User", 106 },
{"Preferences", 107 },
{"OS Drive", 108 },
{"file:///", 109 },
{"Components", 110 },
{"Chrome", 111 },
{"Win System", 200 },
{"Windows", 201 },
{"Mac System", 300 },
{"Mac Desktop", 301 },
{"Mac Trash", 302 },
{"Mac Startup", 303 },
{"Mac Shutdown", 304 },
{"Mac Apple Menu", 305 },
{"Mac Control Panel", 306 },
{"Mac Extension", 307 },
{"Mac Fonts", 308 },
{"Mac Preferences", 309 },
{"Mac Documents", 310 },
{"Unix Local", 400 },
{"Unix Lib", 401 },
{"", -1 }
};
nsInstallFolder::nsInstallFolder(const nsString& aFolderID)
{
mFileSpec = nsnull;
SetDirectoryPath( aFolderID, "");
}
nsInstallFolder::nsInstallFolder(const nsString& aFolderID, const nsString& aRelativePath)
{
mFileSpec = nsnull;
/*
aFolderID can be either a Folder enum in which case we merely pass it to SetDirectoryPath, or
it can be a Directory. If it is the later, it must already exist and of course be a directory
not a file.
*/
nsFileSpec dirCheck(aFolderID);
if ( (dirCheck.Error() == NS_OK) && (dirCheck.IsDirectory()) && (dirCheck.Exists()))
{
nsString tempString = aFolderID;
tempString += aRelativePath;
mFileSpec = new nsFileSpec(tempString);
// make sure that the directory is created.
nsFileSpec(mFileSpec->GetCString(), PR_TRUE);
}
else
{
SetDirectoryPath( aFolderID, aRelativePath);
}
}
nsInstallFolder::~nsInstallFolder()
{
if (mFileSpec != nsnull)
delete mFileSpec;
}
void
nsInstallFolder::GetDirectoryPath(nsString& aDirectoryPath)
{
aDirectoryPath = "";
if (mFileSpec != nsnull)
{
// We want the a NATIVE path.
aDirectoryPath.SetString(mFileSpec->GetCString());
}
}
void
nsInstallFolder::SetDirectoryPath(const nsString& aFolderID, const nsString& aRelativePath)
{
if ( aFolderID.EqualsIgnoreCase("User Pick") )
{
PickDefaultDirectory();
return;
}
else if ( aFolderID.EqualsIgnoreCase("Installed") )
{
mFileSpec = new nsFileSpec(aRelativePath, PR_TRUE); // creates the directories to the relative path.
return;
}
else
{
PRInt32 folderDirSpecID = MapNameToEnum(aFolderID);
switch (folderDirSpecID)
{
case 100: /////////////////////////////////////////////////////////// Plugins
SetAppShellDirectory(nsSpecialFileSpec::App_PluginsDirectory );
break;
case 101: /////////////////////////////////////////////////////////// Program
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::OS_CurrentProcessDirectory ));
break;
case 102: /////////////////////////////////////////////////////////// Communicator
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::OS_CurrentProcessDirectory ));
break;
case 103: /////////////////////////////////////////////////////////// User Pick
// we should never be here.
mFileSpec = nsnull;
break;
case 104: /////////////////////////////////////////////////////////// Temporary
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::OS_TemporaryDirectory ));
break;
case 105: /////////////////////////////////////////////////////////// Installed
// we should never be here.
mFileSpec = nsnull;
break;
case 106: /////////////////////////////////////////////////////////// Current User
SetAppShellDirectory(nsSpecialFileSpec::App_UserProfileDirectory50 );
break;
case 107: /////////////////////////////////////////////////////////// Preferences
SetAppShellDirectory(nsSpecialFileSpec::App_PrefsDirectory50 );
break;
case 108: /////////////////////////////////////////////////////////// OS Drive
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::OS_DriveDirectory ));
break;
case 109: /////////////////////////////////////////////////////////// File URL
{
nsString tempFileURLString = aFolderID;
tempFileURLString += aRelativePath;
mFileSpec = new nsFileSpec( nsFileURL(tempFileURLString) );
}
break;
case 110: /////////////////////////////////////////////////////////// Components
SetAppShellDirectory(nsSpecialFileSpec::App_ComponentsDirectory );
break;
case 111: /////////////////////////////////////////////////////////// Chrome
SetAppShellDirectory(nsSpecialFileSpec::App_ChromeDirectory );
break;
case 200: /////////////////////////////////////////////////////////// Win System
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::Win_SystemDirectory ));
break;
case 201: /////////////////////////////////////////////////////////// Windows
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::Win_WindowsDirectory ));
break;
case 300: /////////////////////////////////////////////////////////// Mac System
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::Mac_SystemDirectory ));
break;
case 301: /////////////////////////////////////////////////////////// Mac Desktop
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::Mac_DesktopDirectory ));
break;
case 302: /////////////////////////////////////////////////////////// Mac Trash
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::Mac_TrashDirectory ));
break;
case 303: /////////////////////////////////////////////////////////// Mac Startup
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::Mac_StartupDirectory ));
break;
case 304: /////////////////////////////////////////////////////////// Mac Shutdown
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::Mac_StartupDirectory ));
break;
case 305: /////////////////////////////////////////////////////////// Mac Apple Menu
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::Mac_AppleMenuDirectory ));
break;
case 306: /////////////////////////////////////////////////////////// Mac Control Panel
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::Mac_ControlPanelDirectory ));
break;
case 307: /////////////////////////////////////////////////////////// Mac Extension
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::Mac_ExtensionDirectory ));
break;
case 308: /////////////////////////////////////////////////////////// Mac Fonts
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::Mac_FontsDirectory ));
break;
case 309: /////////////////////////////////////////////////////////// Mac Preferences
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::Mac_PreferencesDirectory ));
break;
case 310: /////////////////////////////////////////////////////////// Mac Documents
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::Mac_DocumentsDirectory ));
break;
case 400: /////////////////////////////////////////////////////////// Unix Local
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::Unix_LocalDirectory ));
break;
case 401: /////////////////////////////////////////////////////////// Unix Lib
mFileSpec = new nsFileSpec( nsSpecialSystemDirectory( nsSpecialSystemDirectory::Unix_LibDirectory ));
break;
case -1:
default:
mFileSpec = nsnull;
return;
}
#ifndef XP_MAC
if (aRelativePath.Length() > 0)
{
nsString tempPath(aRelativePath);
if (aRelativePath.Last() != '/' || aRelativePath.Last() != '\\')
tempPath += '/';
*mFileSpec += tempPath;
}
#endif
// make sure that the directory is created.
nsFileSpec(mFileSpec->GetCString(), PR_TRUE);
}
}
void nsInstallFolder::PickDefaultDirectory()
{
//FIX: Need to put up a dialog here and set mFileSpec
return;
}
/* MapNameToEnum
* maps name from the directory table to its enum */
PRInt32
nsInstallFolder::MapNameToEnum(const nsString& name)
{
int i = 0;
if ( name == "null")
return -1;
while ( DirectoryTable[i].directoryName[0] != 0 )
{
if ( name.EqualsIgnoreCase(DirectoryTable[i].directoryName) )
return DirectoryTable[i].folderEnum;
i++;
}
return -1;
}
static NS_DEFINE_IID(kFileLocatorIID, NS_IFILELOCATOR_IID);
static NS_DEFINE_IID(kFileLocatorCID, NS_FILELOCATOR_CID);
void
nsInstallFolder::SetAppShellDirectory(PRUint32 value)
{
nsIFileLocator * appShellLocator;
nsresult rv = nsComponentManager::CreateInstance(kFileLocatorCID,
nsnull,
kFileLocatorIID,
(void**) &appShellLocator);
if ( NS_SUCCEEDED(rv) )
{
mFileSpec = new nsFileSpec();
appShellLocator->GetFileLocation(value, mFileSpec);
NS_RELEASE(appShellLocator);
}
}

View File

@@ -0,0 +1,58 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Daniel Veditz <dveditz@netscape.com>
* Douglas Turner <dougt@netscape.com>
*/
#ifndef __NS_INSTALLFOLDER_H__
#define __NS_INSTALLFOLDER_H__
#include "nscore.h"
#include "prtypes.h"
#include "nsString.h"
#include "nsFileSpec.h"
#include "nsSpecialSystemDirectory.h"
class nsInstallFolder
{
public:
nsInstallFolder(const nsString& aFolderID);
nsInstallFolder(const nsString& aFolderID, const nsString& aRelativePath);
virtual ~nsInstallFolder();
void GetDirectoryPath(nsString& aDirectoryPath);
private:
nsFileSpec* mFileSpec;
void SetDirectoryPath(const nsString& aFolderID, const nsString& aRelativePath);
void PickDefaultDirectory();
PRInt32 MapNameToEnum(const nsString& name);
void SetAppShellDirectory(PRUint32 value);
};
#endif

View File

@@ -0,0 +1,52 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsInstallObject_h__
#define nsInstallObject_h__
#include "prtypes.h"
class nsInstall;
class nsInstallObject
{
public:
/* Public Methods */
nsInstallObject(nsInstall* inInstall) {mInstall = inInstall; }
/* Override with your set-up action */
virtual PRInt32 Prepare() = 0;
/* Override with your Completion action */
virtual PRInt32 Complete() = 0;
/* Override with an explanatory string for the progress dialog */
virtual char* toString() = 0;
/* Override with your clean-up function */
virtual void Abort() = 0;
/* should these be protected? */
virtual PRBool CanUninstall() = 0;
virtual PRBool RegisterPackageNode() = 0;
protected:
nsInstall* mInstall;
};
#endif /* nsInstallObject_h__ */

View File

@@ -0,0 +1,986 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsFileSpec.h"
#include "prmem.h"
#include "nsInstall.h"
#include "nsInstallPatch.h"
#include "nsInstallResources.h"
#include "nsIDOMInstallVersion.h"
#include "zlib.h"
#include "gdiff.h"
#include "VerReg.h"
#include "ScheduledTasks.h"
#include "plstr.h"
#include "xp_file.h" /* for XP_PlatformFileToURL */
#ifdef XP_MAC
#include "PatchableAppleSingle.h"
#endif
#define BUFSIZE 32768
#define OPSIZE 1
#define MAXCMDSIZE 12
#define SRCFILE 0
#define OUTFILE 1
#define getshort(s) (uint16)( ((uchar)*(s) << 8) + ((uchar)*((s)+1)) )
#define getlong(s) \
(uint32)( ((uchar)*(s) << 24) + ((uchar)*((s)+1) << 16 ) + \
((uchar)*((s)+2) << 8) + ((uchar)*((s)+3)) )
static int32 gdiff_parseHeader( pDIFFDATA dd );
static int32 gdiff_validateFile( pDIFFDATA dd, int file );
static int32 gdiff_valCRC32( pDIFFDATA dd, PRFileDesc* fh, uint32 chksum );
static int32 gdiff_ApplyPatch( pDIFFDATA dd );
static int32 gdiff_getdiff( pDIFFDATA dd, uchar *buffer, uint32 length );
static int32 gdiff_add( pDIFFDATA dd, uint32 count );
static int32 gdiff_copy( pDIFFDATA dd, uint32 position, uint32 count );
static int32 gdiff_validateFile( pDIFFDATA dd, int file );
nsInstallPatch::nsInstallPatch( nsInstall* inInstall,
const nsString& inVRName,
const nsString& inVInfo,
const nsString& inJarLocation,
PRInt32 *error)
: nsInstallObject(inInstall)
{
char tempTargetFile[MAXREGPATHLEN];
char* tempVersionString = inVRName.ToNewCString();
PRInt32 err = VR_GetPath(tempVersionString, MAXREGPATHLEN, tempTargetFile );
delete [] tempVersionString;
if (err != REGERR_OK)
{
*error = nsInstall::NO_SUCH_COMPONENT;
return;
}
nsString folderSpec(tempTargetFile);
mPatchFile = nsnull;
mTargetFile = nsnull;
mPatchedFile = nsnull;
mRegistryName = new nsString(inVRName);
mJarLocation = new nsString(inJarLocation);
mTargetFile = new nsFileSpec(folderSpec);
mVersionInfo = new nsInstallVersion();
mVersionInfo->Init(inVInfo);
}
nsInstallPatch::nsInstallPatch( nsInstall* inInstall,
const nsString& inVRName,
const nsString& inVInfo,
const nsString& inJarLocation,
const nsString& folderSpec,
const nsString& inPartialPath,
PRInt32 *error)
: nsInstallObject(inInstall)
{
if ((inInstall == nsnull) || (inVRName == "null") || (inJarLocation == "null"))
{
*error = nsInstall::INVALID_ARGUMENTS;
return;
}
mPatchFile = nsnull;
mTargetFile = nsnull;
mPatchedFile = nsnull;
mRegistryName = new nsString(inVRName);
mJarLocation = new nsString(inJarLocation);
mVersionInfo = new nsInstallVersion();
mVersionInfo->Init(inVInfo);
mTargetFile = new nsFileSpec(folderSpec);
if(inPartialPath != "null")
*mTargetFile += inPartialPath;
}
nsInstallPatch::~nsInstallPatch()
{
if (mVersionInfo)
delete mVersionInfo;
if (mTargetFile)
delete mTargetFile;
if (mJarLocation)
delete mJarLocation;
if (mRegistryName)
delete mRegistryName;
if (mPatchedFile)
delete mPatchedFile;
if (mPatchFile)
delete mPatchFile;
}
PRInt32 nsInstallPatch::Prepare()
{
PRInt32 err;
PRBool deleteOldSrc;
if (mTargetFile == nsnull)
return nsInstall::INVALID_ARGUMENTS;
if (mTargetFile->Exists())
{
if (mTargetFile->IsFile())
{
err = nsInstall::SUCCESS;
}
else
{
err = nsInstall::FILE_IS_DIRECTORY;
}
}
else
{
err = nsInstall::FILE_DOES_NOT_EXIST;
}
if (err != nsInstall::SUCCESS)
{
return err;
}
err = mInstall->ExtractFileFromJar(*mJarLocation, mTargetFile, &mPatchFile);
nsFileSpec *fileName = nsnull;
nsVoidKey ikey( HashFilePath( nsFilePath(*mTargetFile) ) );
mInstall->GetPatch(&ikey, fileName);
if (fileName != nsnull)
{
deleteOldSrc = PR_TRUE;
}
else
{
fileName = mTargetFile;
deleteOldSrc = PR_FALSE;
}
err = NativePatch( *fileName, // the file to patch
*mPatchFile, // the patch that was extracted from the jarfile
&mPatchedFile); // the new patched file
if (err != nsInstall::SUCCESS)
{
return err;
}
PR_ASSERT(mPatchedFile != nsnull);
mInstall->AddPatch(&ikey, mPatchedFile );
if ( deleteOldSrc )
{
DeleteFileNowOrSchedule(*fileName );
}
return err;
}
PRInt32 nsInstallPatch::Complete()
{
if ((mInstall == nsnull) || (mVersionInfo == nsnull) || (mPatchedFile == nsnull) || (mTargetFile == nsnull))
{
return nsInstall::INVALID_ARGUMENTS;
}
PRInt32 err = nsInstall::SUCCESS;
nsFileSpec *fileName = nsnull;
nsVoidKey ikey( HashFilePath( nsFilePath(*mTargetFile) ) );
mInstall->GetPatch(&ikey, fileName);
if (fileName != nsnull && (*fileName == *mPatchedFile) )
{
// the patch has not been superceded--do final replacement
err = ReplaceFileNowOrSchedule( *mTargetFile, *mPatchedFile);
if ( 0 == err || nsInstall::REBOOT_NEEDED == err )
{
nsString tempVersionString;
mVersionInfo->ToString(tempVersionString);
char* tempRegName = mRegistryName->ToNewCString();
char* tempVersion = tempVersionString.ToNewCString();
err = VR_Install( tempRegName,
(char*) (const char *) nsNSPRPath(*mTargetFile),
tempVersion,
PR_FALSE );
delete [] tempRegName;
delete [] tempVersion;
}
else
{
err = nsInstall::UNEXPECTED_ERROR;
}
}
else
{
// nothing -- old intermediate patched file was
// deleted by a superceding patch
}
return err;
}
void nsInstallPatch::Abort()
{
nsFileSpec *fileName = nsnull;
nsVoidKey ikey( HashFilePath( nsFilePath(*mTargetFile) ) );
mInstall->GetPatch(&ikey, fileName);
if (fileName != nsnull && (*fileName == *mPatchedFile) )
{
DeleteFileNowOrSchedule( *mPatchedFile );
}
}
char* nsInstallPatch::toString()
{
char* buffer = new char[1024];
// FIX! sprintf( buffer, nsInstallResources::GetPatchFileString(), mPatchedFile->GetCString());
return buffer;
}
PRBool
nsInstallPatch::CanUninstall()
{
return PR_FALSE;
}
PRBool
nsInstallPatch::RegisterPackageNode()
{
return PR_FALSE;
}
PRInt32
nsInstallPatch::NativePatch(const nsFileSpec &sourceFile, const nsFileSpec &patchFile, nsFileSpec **newFile)
{
DIFFDATA *dd;
PRInt32 status = GDIFF_ERR_MEM;
char *tmpurl = NULL;
char *realfile = PL_strdup(nsNSPRPath(sourceFile)); // needs to be sourceFile!!!
nsFileSpec outFileSpec = sourceFile;
dd = (DIFFDATA *)PR_Calloc( 1, sizeof(DIFFDATA));
if (dd != NULL)
{
dd->databuf = (uchar*)PR_Malloc(BUFSIZE);
if (dd->databuf == NULL)
{
status = GDIFF_ERR_MEM;
goto cleanup;
}
dd->bufsize = BUFSIZE;
// validate patch header & check for special instructions
dd->fDiff = PR_Open (nsNSPRPath(patchFile), PR_RDONLY, 0666);
if (dd->fDiff != NULL)
{
status = gdiff_parseHeader(dd);
} else {
status = GDIFF_ERR_ACCESS;
}
#ifdef dono
#ifdef WIN32
/* unbind Win32 images */
if ( dd->bWin32BoundImage && status == GDIFF_OK ) {
tmpurl = WH_TempName( xpURL, NULL );
if ( tmpurl != NULL ) {
if (su_unbind( srcfile, srctype, tmpurl, xpURL ))
{
PL_strfree(realfile);
realfile = tmpurl;
realtype = xpURL;
}
}
else
status = GDIFF_ERR_MEM;
}
#endif
#endif
#ifdef XP_MAC
if ( dd->bMacAppleSingle && status == GDIFF_OK )
{
// create a tmp file, so that we can AppleSingle the src file
nsSpecialSystemDirectory tempMacFile(nsSpecialSystemDirectory::OS_TemporaryDirectory);
nsString srcName = sourceFile.GetLeafName();
tempMacFile.SetLeafName(srcName);
tempMacFile.MakeUnique();
// Encode!
// Encode src file, and put into temp file
FSSpec sourceSpec = sourceFile.GetFSSpec();
FSSpec tempSpec = tempMacFile.GetFSSpec();
status = PAS_EncodeFile(&sourceSpec, &tempSpec);
if (status == noErr)
{
// set
PL_strfree(realfile);
realfile = PL_strdup(nsNSPRPath(tempMacFile));
}
}
#endif
if (status != NS_OK)
goto cleanup;
// make a unique file at the same location of our source file (FILENAME-ptch.EXT)
nsString patchFileName = "-ptch";
nsString newFileName = sourceFile.GetLeafName();
PRInt32 index;
if ((index = newFileName.RFind(".")) > 0)
{
nsString extention;
nsString fileName;
newFileName.Right(extention, (newFileName.Length() - index) );
newFileName.Left(fileName, (newFileName.Length() - (newFileName.Length() - index)));
newFileName = fileName + patchFileName + extention;
} else {
newFileName += patchFileName;
}
outFileSpec.SetLeafName(newFileName); //????
outFileSpec.MakeUnique();
char *outFile = PL_strdup(nsNSPRPath(outFileSpec));
// apply patch to the source file
dd->fSrc = PR_Open ( realfile, PR_RDONLY, 0666);
dd->fOut = PR_Open ( outFile, PR_RDWR|PR_CREATE_FILE|PR_TRUNCATE, 0666);
if (dd->fSrc != NULL && dd->fOut != NULL)
{
status = gdiff_validateFile (dd, SRCFILE);
// specify why diff failed
if (status == GDIFF_ERR_CHECKSUM)
status = GDIFF_ERR_CHECKSUM_TARGET;
if (status == GDIFF_OK)
status = gdiff_ApplyPatch(dd);
if (status == GDIFF_OK)
status = gdiff_validateFile (dd, OUTFILE);
if (status == GDIFF_ERR_CHECKSUM)
status = GDIFF_ERR_CHECKSUM_RESULT;
if (status == GDIFF_OK)
{
*newFile = &outFileSpec;
if ( outFile != nsnull)
PL_strfree( outFile );
}
} else {
status = GDIFF_ERR_ACCESS;
}
}
#ifdef XP_MAC
if ( dd->bMacAppleSingle && status == GDIFF_OK )
{
// create another file, so that we can decode somewhere
nsFileSpec anotherName = outFileSpec;
anotherName.MakeUnique();
// Close the out file so that we can read it
PR_Close( dd->fOut );
dd->fOut = NULL;
FSSpec outSpec = outFileSpec.GetFSSpec();
FSSpec anotherSpec = anotherName.GetFSSpec();
status = PAS_DecodeFile(&outSpec, &anotherSpec);
if (status != noErr)
{
goto cleanup;
}
nsFileSpec parent;
outFileSpec.GetParent(parent);
outFileSpec.Delete(PR_FALSE);
anotherName.Copy(parent);
*newFile = &anotherName;
}
#endif
cleanup:
if ( dd != NULL )
{
if ( dd->fSrc != nsnull )
PR_Close( dd->fSrc );
if ( dd->fDiff != nsnull )
PR_Close( dd->fDiff );
if ( dd->fOut != nsnull )
{
PR_Close( dd->fOut );
}
if ( status != GDIFF_OK )
//XP_FileRemove( outfile, outtype );
newFile = NULL;
PR_FREEIF( dd->databuf );
PR_FREEIF( dd->oldChecksum );
PR_FREEIF( dd->newChecksum );
PR_DELETE(dd);
}
if ( tmpurl != NULL ) {
//XP_FileRemove( tmpurl, xpURL );
tmpurl = NULL;
PR_DELETE( tmpurl );
}
/* lets map any GDIFF error to nice SU errors */
switch (status)
{
case GDIFF_OK:
break;
case GDIFF_ERR_HEADER:
case GDIFF_ERR_BADDIFF:
case GDIFF_ERR_OPCODE:
case GDIFF_ERR_CHKSUMTYPE:
status = nsInstall::PATCH_BAD_DIFF;
break;
case GDIFF_ERR_CHECKSUM_TARGET:
status = nsInstall::PATCH_BAD_CHECKSUM_TARGET;
break;
case GDIFF_ERR_CHECKSUM_RESULT:
status = nsInstall::PATCH_BAD_CHECKSUM_RESULT;
break;
case GDIFF_ERR_OLDFILE:
case GDIFF_ERR_ACCESS:
case GDIFF_ERR_MEM:
case GDIFF_ERR_UNKNOWN:
default:
status = nsInstall::UNEXPECTED_ERROR;
break;
}
return status;
// return -1; //old return value
}
void*
nsInstallPatch::HashFilePath(const nsFilePath& aPath)
{
PRUint32 rv = 0;
char* cPath = PL_strdup(nsNSPRPath(aPath));
if(cPath != nsnull)
{
char ch;
char* filePath = PL_strdup(cPath);
PRUint32 cnt=0;
while ((ch = *filePath++) != 0)
{
// FYI: rv = rv*37 + ch
rv = ((rv << 5) + (rv << 2) + rv) + ch;
cnt++;
}
for (PRUint32 i=0; i<=cnt; i++)
*filePath--;
PL_strfree(filePath);
}
PL_strfree(cPath);
return (void*)rv;
}
/*---------------------------------------------------------
* gdiff_parseHeader()
*
* reads and validates the GDIFF header info
*---------------------------------------------------------
*/
static
int32 gdiff_parseHeader( pDIFFDATA dd )
{
int32 err = GDIFF_OK;
uint8 cslen;
uint8 oldcslen;
uint8 newcslen;
uint32 nRead;
uchar header[GDIFF_HEADERSIZE];
/* Read the fixed-size part of the header */
nRead = PR_Read (dd->fDiff, header, GDIFF_HEADERSIZE);
if ( nRead != GDIFF_HEADERSIZE ||
memcmp( header, GDIFF_MAGIC, GDIFF_MAGIC_LEN ) != 0 ||
header[GDIFF_VER_POS] != GDIFF_VER )
{
err = GDIFF_ERR_HEADER;
}
else
{
/* get the checksum information */
dd->checksumType = header[GDIFF_CS_POS];
cslen = header[GDIFF_CSLEN_POS];
if ( cslen > 0 )
{
oldcslen = cslen / 2;
newcslen = cslen - oldcslen;
PR_ASSERT( newcslen == oldcslen );
dd->checksumLength = oldcslen;
dd->oldChecksum = (uchar*)PR_MALLOC(oldcslen);
dd->newChecksum = (uchar*)PR_MALLOC(newcslen);
if ( dd->oldChecksum != NULL && dd->newChecksum != NULL )
{
nRead = PR_Read (dd->fDiff, dd->oldChecksum, oldcslen);
if ( nRead == oldcslen )
{
nRead = PR_Read (dd->fDiff, dd->newChecksum, newcslen);
if ( nRead != newcslen ) {
err = GDIFF_ERR_HEADER;
}
}
else {
err = GDIFF_ERR_HEADER;
}
}
else {
err = GDIFF_ERR_MEM;
}
}
/* get application data, if any */
if ( err == GDIFF_OK )
{
uint32 appdataSize;
uchar *buf;
uchar lenbuf[GDIFF_APPDATALEN];
nRead = PR_Read(dd->fDiff, lenbuf, GDIFF_APPDATALEN);
if ( nRead == GDIFF_APPDATALEN )
{
appdataSize = getlong(lenbuf);
if ( appdataSize > 0 )
{
buf = (uchar *)PR_MALLOC( appdataSize );
if ( buf != NULL )
{
nRead = PR_Read (dd->fDiff, buf, appdataSize);
if ( nRead == appdataSize )
{
if ( 0 == memcmp( buf, APPFLAG_W32BOUND, appdataSize ) )
dd->bWin32BoundImage = TRUE;
if ( 0 == memcmp( buf, APPFLAG_APPLESINGLE, appdataSize ) )
dd->bMacAppleSingle = TRUE;
}
else {
err = GDIFF_ERR_HEADER;
}
PR_DELETE( buf );
}
else {
err = GDIFF_ERR_MEM;
}
}
}
else {
err = GDIFF_ERR_HEADER;
}
}
}
return (err);
}
/*---------------------------------------------------------
* gdiff_validateFile()
*
* computes the checksum of the file and compares it to
* the value stored in the GDIFF header
*---------------------------------------------------------
*/
static
int32 gdiff_validateFile( pDIFFDATA dd, int file )
{
int32 result;
PRFileDesc* fh;
uchar* chksum;
/* which file are we dealing with? */
if ( file == SRCFILE ) {
fh = dd->fSrc;
chksum = dd->oldChecksum;
}
else { /* OUTFILE */
fh = dd->fOut;
chksum = dd->newChecksum;
}
/* make sure file's at beginning */
PR_Seek( fh, 0, PR_SEEK_SET );
/* calculate appropriate checksum */
switch (dd->checksumType)
{
case GDIFF_CS_NONE:
result = GDIFF_OK;
break;
case GDIFF_CS_CRC32:
if ( dd->checksumLength == CRC32_LEN )
result = gdiff_valCRC32( dd, fh, getlong(chksum) );
else
result = GDIFF_ERR_HEADER;
break;
case GDIFF_CS_MD5:
case GDIFF_CS_SHA:
default:
/* unsupported checksum type */
result = GDIFF_ERR_CHKSUMTYPE;
break;
}
/* reset file position to beginning and return status */
PR_Seek( fh, 0, PR_SEEK_SET );
return (result);
}
/*---------------------------------------------------------
* gdiff_valCRC32()
*
* computes the checksum of the file and compares it to
* the passed in checksum. Assumes file is positioned at
* beginning.
*---------------------------------------------------------
*/
static
int32 gdiff_valCRC32( pDIFFDATA dd, PRFileDesc* fh, uint32 chksum )
{
uint32 crc;
uint32 nRead;
crc = crc32(0L, Z_NULL, 0);
nRead = PR_Read (fh, dd->databuf, dd->bufsize);
while ( nRead > 0 )
{
crc = crc32( crc, dd->databuf, nRead );
nRead = PR_Read (fh, dd->databuf, dd->bufsize);
}
if ( crc == chksum )
return GDIFF_OK;
else
return GDIFF_ERR_CHECKSUM;
}
/*---------------------------------------------------------
* gdiff_ApplyPatch()
*
* Combines patch data with source file to produce the
* new target file. Assumes all three files have been
* opened, GDIFF header read, and all other setup complete
*
* The GDIFF patch is processed sequentially which random
* access is neccessary for the source file.
*---------------------------------------------------------
*/
static
int32 gdiff_ApplyPatch( pDIFFDATA dd )
{
int32 err;
XP_Bool done;
uint32 position;
uint32 count;
uchar opcode;
uchar cmdbuf[MAXCMDSIZE];
done = FALSE;
while ( !done ) {
err = gdiff_getdiff( dd, &opcode, OPSIZE );
if ( err != GDIFF_OK )
break;
switch (opcode)
{
case ENDDIFF:
done = TRUE;
break;
case ADD16:
err = gdiff_getdiff( dd, cmdbuf, ADD16SIZE );
if ( err == GDIFF_OK ) {
err = gdiff_add( dd, getshort( cmdbuf ) );
}
break;
case ADD32:
err = gdiff_getdiff( dd, cmdbuf, ADD32SIZE );
if ( err == GDIFF_OK ) {
err = gdiff_add( dd, getlong( cmdbuf ) );
}
break;
case COPY16BYTE:
err = gdiff_getdiff( dd, cmdbuf, COPY16BYTESIZE );
if ( err == GDIFF_OK ) {
position = getshort( cmdbuf );
count = *(cmdbuf + sizeof(short));
err = gdiff_copy( dd, position, count );
}
break;
case COPY16SHORT:
err = gdiff_getdiff( dd, cmdbuf, COPY16SHORTSIZE );
if ( err == GDIFF_OK ) {
position = getshort( cmdbuf );
count = getshort(cmdbuf + sizeof(short));
err = gdiff_copy( dd, position, count );
}
break;
case COPY16LONG:
err = gdiff_getdiff( dd, cmdbuf, COPY16LONGSIZE );
if ( err == GDIFF_OK ) {
position = getshort( cmdbuf );
count = getlong(cmdbuf + sizeof(short));
err = gdiff_copy( dd, position, count );
}
break;
case COPY32BYTE:
err = gdiff_getdiff( dd, cmdbuf, COPY32BYTESIZE );
if ( err == GDIFF_OK ) {
position = getlong( cmdbuf );
count = *(cmdbuf + sizeof(long));
err = gdiff_copy( dd, position, count );
}
break;
case COPY32SHORT:
err = gdiff_getdiff( dd, cmdbuf, COPY32SHORTSIZE );
if ( err == GDIFF_OK ) {
position = getlong( cmdbuf );
count = getshort(cmdbuf + sizeof(long));
err = gdiff_copy( dd, position, count );
}
break;
case COPY32LONG:
err = gdiff_getdiff( dd, cmdbuf, COPY32LONGSIZE );
if ( err == GDIFF_OK ) {
position = getlong( cmdbuf );
count = getlong(cmdbuf + sizeof(long));
err = gdiff_copy( dd, position, count );
}
break;
case COPY64:
/* we don't support 64-bit file positioning yet */
err = GDIFF_ERR_OPCODE;
break;
default:
err = gdiff_add( dd, opcode );
break;
}
if ( err != GDIFF_OK )
done = TRUE;
}
/* return status */
return (err);
}
/*---------------------------------------------------------
* gdiff_getdiff()
*
* reads the next "length" bytes of the diff into "buffer"
*
* XXX: need a diff buffer to optimize reads!
*---------------------------------------------------------
*/
static
int32 gdiff_getdiff( pDIFFDATA dd, uchar *buffer, uint32 length )
{
uint32 bytesRead;
bytesRead = PR_Read (dd->fDiff, buffer, length);
if ( bytesRead != length )
return GDIFF_ERR_BADDIFF;
return GDIFF_OK;
}
/*---------------------------------------------------------
* gdiff_add()
*
* append "count" bytes from diff file to new file
*---------------------------------------------------------
*/
static
int32 gdiff_add( pDIFFDATA dd, uint32 count )
{
int32 err = GDIFF_OK;
uint32 nRead;
uint32 chunksize;
while ( count > 0 ) {
chunksize = ( count > dd->bufsize) ? dd->bufsize : count;
nRead = PR_Read (dd->fDiff, dd->databuf, chunksize);
if ( nRead != chunksize ) {
err = GDIFF_ERR_BADDIFF;
break;
}
PR_Write (dd->fOut, dd->databuf, chunksize);
count -= chunksize;
}
return (err);
}
/*---------------------------------------------------------
* gdiff_copy()
*
* copy "count" bytes from "position" in source file
*---------------------------------------------------------
*/
static
int32 gdiff_copy( pDIFFDATA dd, uint32 position, uint32 count )
{
int32 err = GDIFF_OK;
uint32 nRead;
uint32 chunksize;
PR_Seek (dd->fSrc, position, PR_SEEK_SET);
while ( count > 0 ) {
chunksize = (count > dd->bufsize) ? dd->bufsize : count;
nRead = PR_Read (dd->fSrc, dd->databuf, chunksize);
if ( nRead != chunksize ) {
err = GDIFF_ERR_OLDFILE;
break;
}
PR_Write (dd->fOut, dd->databuf, chunksize);
count -= chunksize;
}
return (err);
}

View File

@@ -0,0 +1,79 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsInstallPatch_h__
#define nsInstallPatch_h__
#include "prtypes.h"
#include "nsString.h"
#include "nsInstallObject.h"
#include "nsInstall.h"
#include "nsInstallFolder.h"
#include "nsInstallVersion.h"
class nsInstallPatch : public nsInstallObject
{
public:
nsInstallPatch( nsInstall* inInstall,
const nsString& inVRName,
const nsString& inVInfo,
const nsString& inJarLocation,
const nsString& folderSpec,
const nsString& inPartialPath,
PRInt32 *error);
nsInstallPatch( nsInstall* inInstall,
const nsString& inVRName,
const nsString& inVInfo,
const nsString& inJarLocation,
PRInt32 *error);
virtual ~nsInstallPatch();
PRInt32 Prepare();
PRInt32 Complete();
void Abort();
char* toString();
PRBool CanUninstall();
PRBool RegisterPackageNode();
private:
nsInstallVersion *mVersionInfo;
nsFileSpec *mTargetFile;
nsFileSpec *mPatchFile;
nsFileSpec *mPatchedFile;
nsString *mJarLocation;
nsString *mRegistryName;
PRInt32 NativePatch(const nsFileSpec &sourceFile, const nsFileSpec &patchfile, nsFileSpec **newFile);
void* HashFilePath(const nsFilePath& aPath);
};
#endif /* nsInstallPatch_h__ */

View File

@@ -0,0 +1,343 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Douglas Turner <dougt@netscape.com>
*/
#include "nsIXPInstallProgress.h"
#include "nsInstallProgressDialog.h"
#include "nsIAppShellComponentImpl.h"
#include "nsIServiceManager.h"
#include "nsIDocumentViewer.h"
#include "nsIContent.h"
#include "nsINameSpaceManager.h"
#include "nsIContentViewer.h"
#include "nsIDOMElement.h"
#include "nsINetService.h"
#include "nsIWebShell.h"
#include "nsIWebShellWindow.h"
static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID);
static NS_DEFINE_IID( kAppShellServiceCID, NS_APPSHELL_SERVICE_CID );
static NS_DEFINE_IID( kNetServiceCID, NS_NETSERVICE_CID );
// Utility to set element attribute.
static nsresult setAttribute( nsIDOMXULDocument *doc,
const char *id,
const char *name,
const nsString &value ) {
nsresult rv = NS_OK;
if ( doc ) {
// Find specified element.
nsCOMPtr<nsIDOMElement> elem;
rv = doc->GetElementById( id, getter_AddRefs( elem ) );
if ( elem ) {
// Set the text attribute.
rv = elem->SetAttribute( name, value );
if ( NS_SUCCEEDED( rv ) ) {
} else {
DEBUG_PRINTF( PR_STDOUT, "%s %d: SetAttribute failed, rv=0x%X\n",
__FILE__, (int)__LINE__, (int)rv );
}
} else {
DEBUG_PRINTF( PR_STDOUT, "%s %d: GetElementById failed, rv=0x%X\n",
__FILE__, (int)__LINE__, (int)rv );
}
} else {
rv = NS_ERROR_NULL_POINTER;
}
return rv;
}
// Utility to get element attribute.
static nsresult getAttribute( nsIDOMXULDocument *doc,
const char *id,
const char *name,
nsString &value ) {
nsresult rv = NS_OK;
if ( doc ) {
// Find specified element.
nsCOMPtr<nsIDOMElement> elem;
rv = doc->GetElementById( id, getter_AddRefs( elem ) );
if ( elem ) {
// Set the text attribute.
rv = elem->GetAttribute( name, value );
if ( NS_SUCCEEDED( rv ) ) {
} else {
DEBUG_PRINTF( PR_STDOUT, "%s %d: SetAttribute failed, rv=0x%X\n",
__FILE__, (int)__LINE__, (int)rv );
}
} else {
DEBUG_PRINTF( PR_STDOUT, "%s %d: GetElementById failed, rv=0x%X\n",
__FILE__, (int)__LINE__, (int)rv );
}
} else {
rv = NS_ERROR_NULL_POINTER;
}
return rv;
}
nsInstallProgressDialog::nsInstallProgressDialog()
{
NS_INIT_REFCNT();
mWindow = nsnull;
mDocument = nsnull;
}
nsInstallProgressDialog::~nsInstallProgressDialog()
{
}
NS_IMPL_ADDREF( nsInstallProgressDialog );
NS_IMPL_RELEASE( nsInstallProgressDialog );
NS_IMETHODIMP
nsInstallProgressDialog::QueryInterface(REFNSIID aIID,void** aInstancePtr)
{
if (aInstancePtr == NULL) {
return NS_ERROR_NULL_POINTER;
}
// Always NULL result, in case of failure
*aInstancePtr = NULL;
if (aIID.Equals(nsIXPInstallProgress::GetIID())) {
*aInstancePtr = (void*) ((nsInstallProgressDialog*)this);
NS_ADDREF_THIS();
return NS_OK;
}
if (aIID.Equals(nsIXULWindowCallbacks::GetIID())) {
*aInstancePtr = (void*) ((nsIXULWindowCallbacks*)this);
NS_ADDREF_THIS();
return NS_OK;
}
if (aIID.Equals(kISupportsIID)) {
*aInstancePtr = (void*) (nsISupports*)((nsIXPInstallProgress*)this);
NS_ADDREF_THIS();
return NS_OK;
}
return NS_ERROR_NO_INTERFACE;
}
NS_IMETHODIMP
nsInstallProgressDialog::BeforeJavascriptEvaluation()
{
nsresult rv = NS_OK;
// Get app shell service.
nsIAppShellService *appShell;
rv = nsServiceManager::GetService( kAppShellServiceCID,
nsIAppShellService::GetIID(),
(nsISupports**)&appShell );
if ( NS_SUCCEEDED( rv ) )
{
// Open "progress" dialog.
nsIURL *url;
rv = NS_NewURL( &url, "resource:/res/xpinstall/progress.xul" );
if ( NS_SUCCEEDED(rv) )
{
nsIWebShellWindow *newWindow;
rv = appShell->CreateTopLevelWindow( nsnull,
url,
PR_TRUE,
newWindow,
nsnull,
this, // callbacks??
0,
0 );
if ( NS_SUCCEEDED( rv ) )
{
mWindow = newWindow;
NS_RELEASE( newWindow );
if (mWindow != nsnull)
mWindow->Show(PR_TRUE);
}
else
{
DEBUG_PRINTF( PR_STDOUT, "Error creating progress dialog, rv=0x%X\n", (int)rv );
}
NS_RELEASE( url );
}
nsServiceManager::ReleaseService( kAppShellServiceCID, appShell );
}
else
{
DEBUG_PRINTF( PR_STDOUT, "Unable to get app shell service, rv=0x%X\n", (int)rv );
}
return NS_OK;
}
NS_IMETHODIMP
nsInstallProgressDialog::AfterJavascriptEvaluation()
{
if (mWindow)
{
mWindow->Close();
}
return NS_OK;
}
NS_IMETHODIMP
nsInstallProgressDialog::InstallStarted(const char *UIPackageName)
{
setAttribute( mDocument, "dialog.uiPackageName", "value", nsString(UIPackageName) );
return NS_OK;
}
NS_IMETHODIMP
nsInstallProgressDialog::ItemScheduled(const char *message)
{
PRInt32 maxChars = 40;
nsString theMessage(message);
PRInt32 len = theMessage.Length();
if (len > maxChars)
{
PRInt32 offset = (len/2) - ((len - maxChars)/2);
PRInt32 count = (len - maxChars);
theMessage.Cut(offset, count);
theMessage.Insert(nsString("..."), offset);
}
setAttribute( mDocument, "dialog.currentAction", "value", theMessage );
nsString aValue;
getAttribute( mDocument, "data.canceled", "value", aValue );
if (aValue.EqualsIgnoreCase("true"))
return -1;
return NS_OK;
}
NS_IMETHODIMP
nsInstallProgressDialog::InstallFinalization(const char *message, PRInt32 itemNum, PRInt32 totNum)
{
PRInt32 maxChars = 40;
nsString theMessage(message);
PRInt32 len = theMessage.Length();
if (len > maxChars)
{
PRInt32 offset = (len/2) - ((len - maxChars)/2);
PRInt32 count = (len - maxChars);
theMessage.Cut(offset, count);
theMessage.Insert(nsString("..."), offset);
}
setAttribute( mDocument, "dialog.currentAction", "value", theMessage );
nsresult rv = NS_OK;
char buf[16];
PR_snprintf( buf, sizeof buf, "%lu", totNum );
setAttribute( mDocument, "dialog.progress", "max", buf );
if (totNum != 0)
{
PR_snprintf( buf, sizeof buf, "%lu", ((totNum-itemNum)/totNum) );
}
else
{
PR_snprintf( buf, sizeof buf, "%lu", 0 );
}
setAttribute( mDocument, "dialog.progress", "value", buf );
return NS_OK;
}
NS_IMETHODIMP
nsInstallProgressDialog::InstallAborted()
{
return NS_OK;
}
// Do startup stuff from C++ side.
NS_IMETHODIMP
nsInstallProgressDialog::ConstructBeforeJavaScript(nsIWebShell *aWebShell)
{
nsresult rv = NS_OK;
// Get content viewer from the web shell.
nsCOMPtr<nsIContentViewer> contentViewer;
rv = aWebShell ? aWebShell->GetContentViewer(getter_AddRefs(contentViewer))
: NS_ERROR_NULL_POINTER;
if ( contentViewer ) {
// Up-cast to a document viewer.
nsCOMPtr<nsIDocumentViewer> docViewer( do_QueryInterface( contentViewer, &rv ) );
if ( docViewer ) {
// Get the document from the doc viewer.
nsCOMPtr<nsIDocument> document;
rv = docViewer->GetDocument(*getter_AddRefs(document));
if ( document ) {
// Upcast to XUL document.
mDocument = do_QueryInterface( document, &rv );
if ( ! mDocument )
{
DEBUG_PRINTF( PR_STDOUT, "%s %d: Upcast to nsIDOMXULDocument failed, rv=0x%X\n",
__FILE__, (int)__LINE__, (int)rv );
}
}
else
{
DEBUG_PRINTF( PR_STDOUT, "%s %d: GetDocument failed, rv=0x%X\n",
__FILE__, (int)__LINE__, (int)rv );
}
}
else
{
DEBUG_PRINTF( PR_STDOUT, "%s %d: Upcast to nsIDocumentViewer failed, rv=0x%X\n",
__FILE__, (int)__LINE__, (int)rv );
}
}
else
{
DEBUG_PRINTF( PR_STDOUT, "%s %d: GetContentViewer failed, rv=0x%X\n",
__FILE__, (int)__LINE__, (int)rv );
}
return rv;
}

View File

@@ -0,0 +1,67 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Douglas Turner <dougt@netscape.com>
*/
#ifndef __nsInstallProgressDialog_h__
#define __nsInstallProgressDialog_h__
#include "nsIXPInstallProgress.h"
#include "nsISupports.h"
#include "nsISupportsUtils.h"
#include "nsCOMPtr.h"
#include "nsIWebShell.h"
#include "nsIWebShellWindow.h"
#include "nsIXULWindowCallbacks.h"
#include "nsIDocument.h"
#include "nsIDOMXULDocument.h"
class nsInstallProgressDialog : public nsIXPInstallProgress, public nsIXULWindowCallbacks
{
public:
nsInstallProgressDialog();
virtual ~nsInstallProgressDialog();
NS_DECL_ISUPPORTS
NS_IMETHOD BeforeJavascriptEvaluation();
NS_IMETHOD AfterJavascriptEvaluation();
NS_IMETHOD InstallStarted(const char *UIPackageName);
NS_IMETHOD ItemScheduled(const char *message);
NS_IMETHOD InstallFinalization(const char *message, PRInt32 itemNum, PRInt32 totNum);
NS_IMETHOD InstallAborted();
// Declare implementations of nsIXULWindowCallbacks interface functions.
NS_IMETHOD ConstructBeforeJavaScript(nsIWebShell *aWebShell);
NS_IMETHOD ConstructAfterJavaScript(nsIWebShell *aWebShell) { return NS_OK; }
private:
nsCOMPtr<nsIDOMXULDocument> mDocument;
nsCOMPtr<nsIWebShellWindow> mWindow;
};
#endif

View File

@@ -0,0 +1,67 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Daniel Veditz <dveditz@netscape.com>
* Douglas Turner <dougt@netscape.com>
*/
#include "nsInstallResources.h"
char* nsInstallResources::GetInstallFileString(void)
{
return "Installing: %s";
}
char* nsInstallResources::GetReplaceFileString(void)
{
return "Replacing %s";
}
char* nsInstallResources::GetDeleteFileString(void)
{
return "Deleting file: %s";
}
char* nsInstallResources::GetDeleteComponentString(void)
{
return "Deleting component: %s";
}
char* nsInstallResources::GetExecuteString(void)
{
return "Executing: %s";
}
char* nsInstallResources::GetExecuteWithArgsString(void)
{
return "Executing: %s with argument: %s";
}
char* nsInstallResources::GetPatchFileString(void)
{
return "Patching: %s";
}
char* nsInstallResources::GetUninstallString(void)
{
return "Uninstalling: %s";
}

View File

@@ -0,0 +1,45 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Daniel Veditz <dveditz@netscape.com>
* Douglas Turner <dougt@netscape.com>
*/
#ifndef __NS_INSTALLRESOURCES_H__
#define __NS_INSTALLRESOURCES_H__
class nsInstallResources
{
public:
static char* GetInstallFileString(void);
static char* GetReplaceFileString(void);
static char* GetDeleteFileString(void);
static char* GetDeleteComponentString(void);
static char* GetExecuteString(void);
static char* GetExecuteWithArgsString(void);
static char* GetPatchFileString(void);
static char* GetUninstallString(void);
};
#endif

View File

@@ -0,0 +1,359 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client 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.
*/
#include "nsSoftwareUpdate.h"
#include "nsSoftwareUpdateStream.h"
#include "nsInstallTrigger.h"
#include "nsIDOMInstallTriggerGlobal.h"
#include "nscore.h"
#include "nsIFactory.h"
#include "nsISupports.h"
#include "nsIScriptGlobalObject.h"
#include "nsIPref.h"
#include "nsRepository.h"
#include "nsIServiceManager.h"
#include "nsSpecialSystemDirectory.h"
static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID);
static NS_DEFINE_IID(kIFactoryIID, NS_IFACTORY_IID);
static NS_DEFINE_IID(kIScriptObjectOwnerIID, NS_ISCRIPTOBJECTOWNER_IID);
static NS_DEFINE_IID(kIInstallTrigger_IID, NS_IDOMINSTALLTRIGGERGLOBAL_IID);
static NS_DEFINE_IID(kIInstallTrigger_CID, NS_SoftwareUpdateInstallTrigger_CID);
nsInstallTrigger::nsInstallTrigger()
{
mScriptObject = nsnull;
NS_INIT_REFCNT();
}
nsInstallTrigger::~nsInstallTrigger()
{
}
NS_IMETHODIMP
nsInstallTrigger::QueryInterface(REFNSIID aIID,void** aInstancePtr)
{
if (aInstancePtr == NULL)
{
return NS_ERROR_NULL_POINTER;
}
// Always NULL result, in case of failure
*aInstancePtr = NULL;
if ( aIID.Equals(kIScriptObjectOwnerIID))
{
*aInstancePtr = (void*) ((nsIScriptObjectOwner*)this);
AddRef();
return NS_OK;
}
else if ( aIID.Equals(kIInstallTrigger_IID) )
{
*aInstancePtr = (void*) ((nsIDOMInstallTriggerGlobal*)this);
AddRef();
return NS_OK;
}
else if ( aIID.Equals(kISupportsIID) )
{
*aInstancePtr = (void*)(nsISupports*)(nsIScriptObjectOwner*)this;
AddRef();
return NS_OK;
}
return NS_NOINTERFACE;
}
NS_IMPL_ADDREF(nsInstallTrigger)
NS_IMPL_RELEASE(nsInstallTrigger)
NS_IMETHODIMP
nsInstallTrigger::GetScriptObject(nsIScriptContext *aContext, void** aScriptObject)
{
NS_PRECONDITION(nsnull != aScriptObject, "null arg");
nsresult res = NS_OK;
if (nsnull == mScriptObject)
{
nsIScriptGlobalObject *global = aContext->GetGlobalObject();
res = NS_NewScriptInstallTriggerGlobal( aContext,
(nsISupports *)(nsIDOMInstallTriggerGlobal*)this,
(nsISupports *)global,
&mScriptObject);
NS_IF_RELEASE(global);
}
*aScriptObject = mScriptObject;
return res;
}
NS_IMETHODIMP
nsInstallTrigger::SetScriptObject(void *aScriptObject)
{
mScriptObject = aScriptObject;
return NS_OK;
}
static NS_DEFINE_IID(kPrefsIID, NS_IPREF_IID);
static NS_DEFINE_IID(kPrefsCID, NS_PREF_CID);
NS_IMETHODIMP
nsInstallTrigger::UpdateEnabled(PRBool* aReturn)
{
nsIPref * prefs;
nsresult rv = nsServiceManager::GetService(kPrefsCID,
kPrefsIID,
(nsISupports**) &prefs);
if ( NS_SUCCEEDED(rv) )
{
rv = prefs->GetBoolPref( (const char*) AUTOUPDATE_ENABLE_PREF, aReturn);
if (NS_FAILED(rv))
{
*aReturn = PR_FALSE;
}
NS_RELEASE(prefs);
}
else
{
*aReturn = PR_FALSE; /* no prefs manager. set to false */
}
//FIX!!!!!!!!!!
*aReturn = PR_TRUE;
return NS_OK;
}
NS_IMETHODIMP
nsInstallTrigger::StartSoftwareUpdate(const nsString& aURL, PRInt32 aFlags, PRInt32* aReturn)
{
nsString localFile;
CreateTempFileFromURL(aURL, localFile);
// start the download (this will clean itself up)
nsSoftwareUpdateListener *downloader = new nsSoftwareUpdateListener(aURL, localFile, aFlags);
*aReturn = NS_OK; // maybe we should do something more.
return NS_OK;
}
NS_IMETHODIMP
nsInstallTrigger::StartSoftwareUpdate(const nsString& aURL, PRInt32* aReturn)
{
nsString localFile;
CreateTempFileFromURL(aURL, localFile);
// start the download (this will clean itself up)
nsSoftwareUpdateListener *downloader = new nsSoftwareUpdateListener(aURL, localFile, 0);
*aReturn = NS_OK; // maybe we should do something more.
return NS_OK;
}
NS_IMETHODIMP
nsInstallTrigger::ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, PRInt32 aDiffLevel, const nsString& aVersion, PRInt32 aMode, PRInt32* aReturn)
{
return NS_OK;
}
NS_IMETHODIMP
nsInstallTrigger::ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, PRInt32 aDiffLevel, nsIDOMInstallVersion* aVersion, PRInt32 aMode, PRInt32* aReturn)
{
return NS_OK;
}
NS_IMETHODIMP
nsInstallTrigger::ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, nsIDOMInstallVersion* aVersion, PRInt32 aMode, PRInt32* aReturn)
{
return NS_OK;
}
NS_IMETHODIMP
nsInstallTrigger::ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, const nsString& aVersion, PRInt32 aMode, PRInt32* aReturn)
{
return NS_OK;
}
NS_IMETHODIMP
nsInstallTrigger::ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, const nsString& aVersion, PRInt32* aReturn)
{
return NS_OK;
}
NS_IMETHODIMP
nsInstallTrigger::ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, nsIDOMInstallVersion* aVersion, PRInt32* aReturn)
{
return NS_OK;
}
NS_IMETHODIMP
nsInstallTrigger::CompareVersion(const nsString& aRegName, PRInt32 aMajor, PRInt32 aMinor, PRInt32 aRelease, PRInt32 aBuild, PRInt32* aReturn)
{
return NS_OK;
}
NS_IMETHODIMP
nsInstallTrigger::CompareVersion(const nsString& aRegName, const nsString& aVersion, PRInt32* aReturn)
{
return NS_OK;
}
NS_IMETHODIMP
nsInstallTrigger::CompareVersion(const nsString& aRegName, nsIDOMInstallVersion* aVersion, PRInt32* aReturn)
{
return NS_OK;
}
// this will take a nsIUrl, and create a temporary file. If it is local, we just us it.
void
nsInstallTrigger::CreateTempFileFromURL(const nsString& aURL, nsString& tempFileString)
{
// Checking to see if the url is local
if ( aURL.EqualsIgnoreCase("file://", 7) )
{
tempFileString.SetString( nsNSPRPath(nsFileURL(aURL)) );
}
else
{
nsSpecialSystemDirectory tempFile(nsSpecialSystemDirectory::OS_TemporaryDirectory);
PRInt32 result = aURL.RFind("/");
if (result != -1)
{
nsString jarName;
aURL.Right(jarName, (aURL.Length() - result) );
PRInt32 argOffset = jarName.RFind("?");
if (argOffset != -1)
{
// we need to remove ? and everything after it
jarName.Truncate(argOffset);
}
tempFile += jarName;
}
else
{
tempFile += "xpinstall.jar";
}
tempFile.MakeUnique();
tempFileString.SetString( nsNSPRPath( nsFilePath(tempFile) ) );
}
}
/////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////
nsInstallTriggerFactory::nsInstallTriggerFactory(void)
{
NS_INIT_REFCNT();
}
nsInstallTriggerFactory::~nsInstallTriggerFactory(void)
{
NS_ASSERTION(mRefCnt == 0, "non-zero refcnt at destruction");
}
NS_IMETHODIMP
nsInstallTriggerFactory::QueryInterface(const nsIID &aIID, void **aResult)
{
if (! aResult)
return NS_ERROR_NULL_POINTER;
// Always NULL result, in case of failure
*aResult = nsnull;
if (aIID.Equals(kISupportsIID)) {
*aResult = NS_STATIC_CAST(nsISupports*, this);
AddRef();
return NS_OK;
} else if (aIID.Equals(kIFactoryIID)) {
*aResult = NS_STATIC_CAST(nsIFactory*, this);
AddRef();
return NS_OK;
}
return NS_NOINTERFACE;
}
NS_IMPL_ADDREF(nsInstallTriggerFactory);
NS_IMPL_RELEASE(nsInstallTriggerFactory);
NS_IMETHODIMP
nsInstallTriggerFactory::CreateInstance(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (! aResult)
return NS_ERROR_NULL_POINTER;
*aResult = nsnull;
nsresult rv;
nsInstallTrigger *inst = new nsInstallTrigger();
if (! inst)
return NS_ERROR_OUT_OF_MEMORY;
if (NS_FAILED(rv = inst->QueryInterface(aIID, aResult)))
{
// We didn't get the right interface.
NS_ERROR("didn't support the interface you wanted");
}
return rv;
}
NS_IMETHODIMP
nsInstallTriggerFactory::LockFactory(PRBool aLock)
{
// Not implemented in simplest case.
return NS_OK;
}

View File

@@ -0,0 +1,72 @@
#ifndef __NS_INSTALLTRIGGER_H__
#define __NS_INSTALLTRIGGER_H__
#include "nscore.h"
#include "nsString.h"
#include "nsIFactory.h"
#include "nsISupports.h"
#include "nsIScriptObjectOwner.h"
#include "nsIDOMInstallTriggerGlobal.h"
#include "nsSoftwareUpdate.h"
#include "prtypes.h"
#include "nsHashtable.h"
#include "nsVector.h"
class nsInstallTrigger: public nsIScriptObjectOwner, public nsIDOMInstallTriggerGlobal
{
public:
static const nsIID& IID() { static nsIID iid = NS_SoftwareUpdateInstallTrigger_CID; return iid; }
nsInstallTrigger();
~nsInstallTrigger();
NS_DECL_ISUPPORTS
NS_IMETHOD GetScriptObject(nsIScriptContext *aContext, void** aScriptObject);
NS_IMETHOD SetScriptObject(void* aScriptObject);
NS_IMETHOD UpdateEnabled(PRBool* aReturn);
NS_IMETHOD StartSoftwareUpdate(const nsString& aURL, PRInt32 aFlags, PRInt32* aReturn);
NS_IMETHOD StartSoftwareUpdate(const nsString& aURL, PRInt32* aReturn);
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, PRInt32 aDiffLevel, const nsString& aVersion, PRInt32 aMode, PRInt32* aReturn);
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, PRInt32 aDiffLevel, nsIDOMInstallVersion* aVersion, PRInt32 aMode, PRInt32* aReturn);
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, nsIDOMInstallVersion* aVersion, PRInt32 aMode, PRInt32* aReturn);
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, const nsString& aVersion, PRInt32 aMode, PRInt32* aReturn);
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, const nsString& aVersion, PRInt32* aReturn);
NS_IMETHOD ConditionalSoftwareUpdate(const nsString& aURL, const nsString& aRegName, nsIDOMInstallVersion* aVersion, PRInt32* aReturn);
NS_IMETHOD CompareVersion(const nsString& aRegName, PRInt32 aMajor, PRInt32 aMinor, PRInt32 aRelease, PRInt32 aBuild, PRInt32* aReturn);
NS_IMETHOD CompareVersion(const nsString& aRegName, const nsString& aVersion, PRInt32* aReturn);
NS_IMETHOD CompareVersion(const nsString& aRegName, nsIDOMInstallVersion* aVersion, PRInt32* aReturn);
private:
void *mScriptObject;
void CreateTempFileFromURL(const nsString& aURL, nsString& tempFileString);
};
class nsInstallTriggerFactory : public nsIFactory
{
public:
nsInstallTriggerFactory();
~nsInstallTriggerFactory();
NS_DECL_ISUPPORTS
NS_IMETHOD CreateInstance(nsISupports *aOuter,
REFNSIID aIID,
void **aResult);
NS_IMETHOD LockFactory(PRBool aLock);
};
#endif

View File

@@ -0,0 +1,196 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Daniel Veditz <dveditz@netscape.com>
* Douglas Turner <dougt@netscape.com>
*/
#include "nsInstall.h"
#include "nsInstallUninstall.h"
#include "nsInstallResources.h"
#include "VerReg.h"
#include "prmem.h"
#include "nsFileSpec.h"
#include "ScheduledTasks.h"
extern "C" NS_EXPORT PRInt32 SU_Uninstall(char *regPackageName);
REGERR su_UninstallProcessItem(char *component_path);
nsInstallUninstall::nsInstallUninstall( nsInstall* inInstall,
const nsString& regName,
PRInt32 *error)
: nsInstallObject(inInstall)
{
if (regName == "null")
{
*error = nsInstall::INVALID_ARGUMENTS;
return;
}
mRegName.SetString(regName);
char* userName = (char*)PR_Malloc(MAXREGPATHLEN);
PRInt32 err = VR_GetUninstallUserName( (char*) (const char*) nsAutoCString(regName),
userName,
MAXREGPATHLEN );
mUIName.SetString(userName);
if (err != REGERR_OK)
{
*error = nsInstall::NO_SUCH_COMPONENT;
}
PR_FREEIF(userName);
}
nsInstallUninstall::~nsInstallUninstall()
{
}
PRInt32 nsInstallUninstall::Prepare()
{
// no set-up necessary
return nsInstall::SUCCESS;
}
PRInt32 nsInstallUninstall::Complete()
{
PRInt32 err = nsInstall::SUCCESS;
if (mInstall == NULL)
return nsInstall::INVALID_ARGUMENTS;
err = SU_Uninstall( (char*)(const char*) nsAutoCString(mRegName) );
return err;
}
void nsInstallUninstall::Abort()
{
}
char* nsInstallUninstall::toString()
{
char* buffer = new char[1024];
char* temp = mUIName.ToNewCString();
sprintf( buffer, nsInstallResources::GetUninstallString(), temp);
delete [] temp;
return buffer;
}
PRBool
nsInstallUninstall::CanUninstall()
{
return PR_FALSE;
}
PRBool
nsInstallUninstall::RegisterPackageNode()
{
return PR_FALSE;
}
extern "C" NS_EXPORT PRInt32 SU_Uninstall(char *regPackageName)
{
REGERR status = REGERR_FAIL;
char pathbuf[MAXREGPATHLEN+1] = {0};
char sharedfilebuf[MAXREGPATHLEN+1] = {0};
REGENUM state = 0;
int32 length;
int32 err;
if (regPackageName == NULL)
return REGERR_PARAM;
if (pathbuf == NULL)
return REGERR_PARAM;
/* Get next path from Registry */
status = VR_Enum( regPackageName, &state, pathbuf, MAXREGPATHLEN );
/* if we got a good path */
while (status == REGERR_OK)
{
char component_path[2*MAXREGPATHLEN+1] = {0};
strcat(component_path, regPackageName);
length = strlen(regPackageName);
if (component_path[length - 1] != '/')
strcat(component_path, "/");
strcat(component_path, pathbuf);
err = su_UninstallProcessItem(component_path);
status = VR_Enum( regPackageName, &state, pathbuf, MAXREGPATHLEN );
}
err = VR_Remove(regPackageName);
// there is a problem here. It looks like if the file is refcounted, we still blow away the reg key
// FIX!
state = 0;
status = VR_UninstallEnumSharedFiles( regPackageName, &state, sharedfilebuf, MAXREGPATHLEN );
while (status == REGERR_OK)
{
err = su_UninstallProcessItem(sharedfilebuf);
err = VR_UninstallDeleteFileFromList(regPackageName, sharedfilebuf);
status = VR_UninstallEnumSharedFiles( regPackageName, &state, sharedfilebuf, MAXREGPATHLEN );
}
err = VR_UninstallDeleteSharedFilesKey(regPackageName);
err = VR_UninstallDestroy(regPackageName);
return err;
}
REGERR su_UninstallProcessItem(char *component_path)
{
int refcount;
int err;
char filepath[MAXREGPATHLEN];
err = VR_GetPath(component_path, sizeof(filepath), filepath);
if ( err == REGERR_OK )
{
err = VR_GetRefCount(component_path, &refcount);
if ( err == REGERR_OK )
{
--refcount;
if (refcount > 0)
err = VR_SetRefCount(component_path, refcount);
else
{
err = VR_Remove(component_path);
DeleteFileNowOrSchedule(nsFileSpec(filepath));
}
}
else
{
/* delete node and file */
err = VR_Remove(component_path);
DeleteFileNowOrSchedule(nsFileSpec(filepath));
}
}
return err;
}

View File

@@ -0,0 +1,63 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client code,
* released March 31, 1998.
*
* 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.
*
* Contributors:
* Daniel Veditz <dveditz@netscape.com>
* Douglas Turner <dougt@netscape.com>
*/
#ifndef nsInstallUninstall_h__
#define nsInstallUninstall_h__
#include "prtypes.h"
#include "nsString.h"
#include "nsInstallObject.h"
#include "nsInstall.h"
class nsInstallUninstall : public nsInstallObject
{
public:
nsInstallUninstall( nsInstall* inInstall,
const nsString& regName,
PRInt32 *error);
virtual ~nsInstallUninstall();
PRInt32 Prepare();
PRInt32 Complete();
void Abort();
char* toString();
PRBool CanUninstall();
PRBool RegisterPackageNode();
private:
nsString mRegName; // Registry name of package
nsString mUIName; // User name of package
};
#endif /* nsInstallUninstall_h__ */

View File

@@ -0,0 +1,399 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (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 Communicator client 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.
*/
#include "nsSoftwareUpdate.h"
#include "nsInstallVersion.h"
#include "nsIDOMInstallVersion.h"
#include "nscore.h"
#include "nsIFactory.h"
#include "nsISupports.h"
#include "nsIScriptGlobalObject.h"
#include "prprf.h"
static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID);
static NS_DEFINE_IID(kIFactoryIID, NS_IFACTORY_IID);
static NS_DEFINE_IID(kIScriptObjectOwnerIID, NS_ISCRIPTOBJECTOWNER_IID);
static NS_DEFINE_IID(kIInstallVersion_IID, NS_IDOMINSTALLVERSION_IID);
nsInstallVersion::nsInstallVersion()
{
mScriptObject = nsnull;
NS_INIT_REFCNT();
}
nsInstallVersion::~nsInstallVersion()
{
}
NS_IMETHODIMP
nsInstallVersion::QueryInterface(REFNSIID aIID,void** aInstancePtr)
{
if (aInstancePtr == NULL)
{
return NS_ERROR_NULL_POINTER;
}
// Always NULL result, in case of failure
*aInstancePtr = NULL;
if ( aIID.Equals(kIScriptObjectOwnerIID))
{
*aInstancePtr = (void*) ((nsIScriptObjectOwner*)this);
AddRef();
return NS_OK;
}
else if ( aIID.Equals(kIInstallVersion_IID) )
{
*aInstancePtr = (void*) ((nsIDOMInstallVersion*)this);
AddRef();
return NS_OK;
}
else if ( aIID.Equals(kISupportsIID) )
{
*aInstancePtr = (void*)(nsISupports*)(nsIScriptObjectOwner*)this;
AddRef();
return NS_OK;
}
return NS_NOINTERFACE;
}
NS_IMPL_ADDREF(nsInstallVersion)
NS_IMPL_RELEASE(nsInstallVersion)
NS_IMETHODIMP
nsInstallVersion::GetScriptObject(nsIScriptContext *aContext, void** aScriptObject)
{
NS_PRECONDITION(nsnull != aScriptObject, "null arg");
nsresult res = NS_OK;
if (nsnull == mScriptObject)
{
res = NS_NewScriptInstallVersion(aContext,
(nsISupports *)(nsIDOMInstallVersion*)this,
nsnull,
&mScriptObject);
}
*aScriptObject = mScriptObject;
return res;
}
NS_IMETHODIMP
nsInstallVersion::SetScriptObject(void *aScriptObject)
{
mScriptObject = aScriptObject;
return NS_OK;
}
// this will go away when our constructors can have parameters.
NS_IMETHODIMP
nsInstallVersion::Init(PRInt32 aMajor, PRInt32 aMinor, PRInt32 aRelease, PRInt32 aBuild)
{
major = aMajor;
minor = aMinor;
release = aRelease;
build = aBuild;
return NS_OK;
}
NS_IMETHODIMP
nsInstallVersion::Init(const nsString& version)
{
PRInt32 errorCode;
PRInt32 aMajor, aMinor, aRelease, aBuild;
major = minor = release = build = 0;
errorCode = nsInstallVersion::StringToVersionNumbers(version, &aMajor, &aMinor, &aRelease, &aBuild);
if (NS_SUCCEEDED(errorCode))
{
Init(aMajor, aMinor, aRelease, aBuild);
}
return NS_OK;
}
NS_IMETHODIMP
nsInstallVersion::GetMajor(PRInt32* aMajor)
{
*aMajor = major;
return NS_OK;
}
NS_IMETHODIMP
nsInstallVersion::SetMajor(PRInt32 aMajor)
{
major = aMajor;
return NS_OK;
}
NS_IMETHODIMP
nsInstallVersion::GetMinor(PRInt32* aMinor)
{
*aMinor = minor;
return NS_OK;
}
NS_IMETHODIMP
nsInstallVersion::SetMinor(PRInt32 aMinor)
{
minor = aMinor;
return NS_OK;
}
NS_IMETHODIMP
nsInstallVersion::GetRelease(PRInt32* aRelease)
{
*aRelease = release;
return NS_OK;
}
NS_IMETHODIMP
nsInstallVersion::SetRelease(PRInt32 aRelease)
{
release = aRelease;
return NS_OK;
}
NS_IMETHODIMP
nsInstallVersion::GetBuild(PRInt32* aBuild)
{
*aBuild = build;
return NS_OK;
}
NS_IMETHODIMP
nsInstallVersion::SetBuild(PRInt32 aBuild)
{
build = aBuild;
return NS_OK;
}
NS_IMETHODIMP
nsInstallVersion::CompareTo(nsIDOMInstallVersion* aVersion, PRInt32* aReturn)
{
PRInt32 aMajor, aMinor, aRelease, aBuild;
aVersion->GetMajor(&aMajor);
aVersion->GetMinor(&aMinor);
aVersion->GetRelease(&aRelease);
aVersion->GetBuild(&aBuild);
CompareTo(aMajor, aMinor, aRelease, aBuild, aReturn);
return NS_OK;
}
NS_IMETHODIMP
nsInstallVersion::CompareTo(const nsString& aAString, PRInt32* aReturn)
{
return NS_OK;
}
NS_IMETHODIMP
nsInstallVersion::CompareTo(PRInt32 aMajor, PRInt32 aMinor, PRInt32 aRelease, PRInt32 aBuild, PRInt32* aReturn)
{
int diff;
if ( major == aMajor )
{
if ( minor == aMinor )
{
if ( release == aRelease )
{
if ( build == aBuild )
diff = EQUAL;
else if ( build > aBuild )
diff = BLD_DIFF;
else
diff = BLD_DIFF_MINUS;
}
else if ( release > aRelease )
diff = REL_DIFF;
else
diff = REL_DIFF_MINUS;
}
else if ( minor > aMinor )
diff = MINOR_DIFF;
else
diff = MINOR_DIFF_MINUS;
}
else if ( major > aMajor )
diff = MAJOR_DIFF;
else
diff = MAJOR_DIFF_MINUS;
*aReturn = diff;
return NS_OK;
}
NS_IMETHODIMP
nsInstallVersion::ToString(nsString& aReturn)
{
char *result=NULL;
result = PR_sprintf_append(result, "%d.%d.%d.%d", major, minor, release, build);
aReturn = result;
return NS_OK;
}
nsresult
nsInstallVersion::StringToVersionNumbers(const nsString& version, PRInt32 *aMajor, PRInt32 *aMinor, PRInt32 *aRelease, PRInt32 *aBuild)
{
PRInt32 errorCode;
int dot = version.Find('.', 0);
if ( dot == -1 )
{
*aMajor = version.ToInteger(&errorCode);
}
else
{
nsString majorStr;
version.Mid(majorStr, 0, dot);
*aMajor = majorStr.ToInteger(&errorCode);
int prev = dot+1;
dot = version.Find('.',prev);
if ( dot == -1 )
{
nsString minorStr;
version.Mid(minorStr, prev, version.Length() - prev);
*aMinor = minorStr.ToInteger(&errorCode);
}
else
{
nsString minorStr;
version.Mid(minorStr, prev, dot - prev);
*aMinor = minorStr.ToInteger(&errorCode);
prev = dot+1;
dot = version.Find('.',prev);
if ( dot == -1 )
{
nsString releaseStr;
version.Mid(releaseStr, prev, version.Length() - prev);
*aRelease = releaseStr.ToInteger(&errorCode);
}
else
{
nsString releaseStr;
version.Mid(releaseStr, prev, dot - prev);
*aRelease = releaseStr.ToInteger(&errorCode);
prev = dot+1;
if ( version.Length() > dot )
{
nsString buildStr;
version.Mid(buildStr, prev, version.Length() - prev);
*aBuild = buildStr.ToInteger(&errorCode);
}
}
}
}
return errorCode;
}
/////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////
nsInstallVersionFactory::nsInstallVersionFactory(void)
{
NS_INIT_REFCNT();
}
nsInstallVersionFactory::~nsInstallVersionFactory(void)
{
NS_ASSERTION(mRefCnt == 0, "non-zero refcnt at destruction");
}
NS_IMETHODIMP
nsInstallVersionFactory::QueryInterface(const nsIID &aIID, void **aResult)
{
if (! aResult)
return NS_ERROR_NULL_POINTER;
// Always NULL result, in case of failure
*aResult = nsnull;
if (aIID.Equals(kISupportsIID)) {
*aResult = NS_STATIC_CAST(nsISupports*, this);
AddRef();
return NS_OK;
} else if (aIID.Equals(kIFactoryIID)) {
*aResult = NS_STATIC_CAST(nsIFactory*, this);
AddRef();
return NS_OK;
}
return NS_NOINTERFACE;
}
NS_IMPL_ADDREF(nsInstallVersionFactory);
NS_IMPL_RELEASE(nsInstallVersionFactory);
NS_IMETHODIMP
nsInstallVersionFactory::CreateInstance(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (aResult == NULL)
{
return NS_ERROR_NULL_POINTER;
}
*aResult = NULL;
/* do I have to use iSupports? */
nsInstallVersion *inst = new nsInstallVersion();
if (inst == NULL)
return NS_ERROR_OUT_OF_MEMORY;
nsresult result = inst->QueryInterface(aIID, aResult);
if (NS_FAILED(result))
delete inst;
return result;
}
NS_IMETHODIMP
nsInstallVersionFactory::LockFactory(PRBool aLock)
{
return NS_OK;
}

View File

@@ -0,0 +1,76 @@
#ifndef __NS_INSTALLVERSION_H__
#define __NS_INSTALLVERSION_H__
#include "nscore.h"
#include "nsString.h"
#include "nsIFactory.h"
#include "nsISupports.h"
#include "nsIScriptObjectOwner.h"
#include "nsIDOMInstallVersion.h"
#include "nsSoftwareUpdate.h"
#include "prtypes.h"
class nsInstallVersion: public nsIScriptObjectOwner, public nsIDOMInstallVersion
{
public:
static const nsIID& IID() { static nsIID iid = NS_SoftwareUpdateInstallVersion_CID; return iid; }
nsInstallVersion();
virtual ~nsInstallVersion();
NS_DECL_ISUPPORTS
NS_IMETHOD GetScriptObject(nsIScriptContext *aContext, void** aScriptObject);
NS_IMETHOD SetScriptObject(void* aScriptObject);
NS_IMETHOD Init(PRInt32 aMajor, PRInt32 aMinor, PRInt32 aRelease, PRInt32 aBuild);
NS_IMETHOD Init(const nsString& aVersionString);
NS_IMETHOD GetMajor(PRInt32* aMajor);
NS_IMETHOD SetMajor(PRInt32 aMajor);
NS_IMETHOD GetMinor(PRInt32* aMinor);
NS_IMETHOD SetMinor(PRInt32 aMinor);
NS_IMETHOD GetRelease(PRInt32* aRelease);
NS_IMETHOD SetRelease(PRInt32 aRelease);
NS_IMETHOD GetBuild(PRInt32* aBuild);
NS_IMETHOD SetBuild(PRInt32 aBuild);
NS_IMETHOD ToString(nsString& aReturn);
NS_IMETHOD CompareTo(nsIDOMInstallVersion* aVersion, PRInt32* aReturn);
NS_IMETHOD CompareTo(const nsString& aString, PRInt32* aReturn);
NS_IMETHOD CompareTo(PRInt32 aMajor, PRInt32 aMinor, PRInt32 aRelease, PRInt32 aBuild, PRInt32* aReturn);
static nsresult StringToVersionNumbers(const nsString& version, PRInt32 *aMajor, PRInt32 *aMinor, PRInt32 *aRelease, PRInt32 *aBuild);
private:
void *mScriptObject;
PRInt32 major;
PRInt32 minor;
PRInt32 release;
PRInt32 build;
};
class nsInstallVersionFactory : public nsIFactory
{
public:
nsInstallVersionFactory();
virtual ~nsInstallVersionFactory();
NS_DECL_ISUPPORTS
NS_IMETHOD CreateInstance(nsISupports *aOuter,
REFNSIID aIID,
void **aResult);
NS_IMETHOD LockFactory(PRBool aLock);
};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,665 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
/* AUTO-GENERATED. DO NOT EDIT!!! */
#include "jsapi.h"
#include "nsJSUtils.h"
#include "nscore.h"
#include "nsIScriptContext.h"
#include "nsIJSScriptObject.h"
#include "nsIScriptObjectOwner.h"
#include "nsIScriptGlobalObject.h"
#include "nsIPtr.h"
#include "nsString.h"
#include "nsIDOMInstallVersion.h"
#include "nsIDOMInstallTriggerGlobal.h"
extern void ConvertJSValToStr(nsString& aString,
JSContext* aContext,
jsval aValue);
extern void ConvertStrToJSVal(const nsString& aProp,
JSContext* aContext,
jsval* aReturn);
extern PRBool ConvertJSValToBool(PRBool* aProp,
JSContext* aContext,
jsval aValue);
extern PRBool ConvertJSValToObj(nsISupports** aSupports,
REFNSIID aIID,
const nsString& aTypeName,
JSContext* aContext,
jsval aValue);
static NS_DEFINE_IID(kIScriptObjectOwnerIID, NS_ISCRIPTOBJECTOWNER_IID);
static NS_DEFINE_IID(kIJSScriptObjectIID, NS_IJSSCRIPTOBJECT_IID);
static NS_DEFINE_IID(kIScriptGlobalObjectIID, NS_ISCRIPTGLOBALOBJECT_IID);
static NS_DEFINE_IID(kIInstallTriggerGlobalIID, NS_IDOMINSTALLTRIGGERGLOBAL_IID);
NS_DEF_PTR(nsIDOMInstallTriggerGlobal);
/***********************************************************************/
//
// InstallTriggerGlobal Properties Getter
//
PR_STATIC_CALLBACK(JSBool)
GetInstallTriggerGlobalProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
{
nsIDOMInstallTriggerGlobal *a = (nsIDOMInstallTriggerGlobal*)JS_GetPrivate(cx, obj);
// If there's no private data, this must be the prototype, so ignore
if (nsnull == a) {
return JS_TRUE;
}
if (JSVAL_IS_INT(id)) {
switch(JSVAL_TO_INT(id)) {
case 0:
default:
return nsJSUtils::nsCallJSScriptObjectGetProperty(a, cx, id, vp);
}
}
else {
return nsJSUtils::nsCallJSScriptObjectGetProperty(a, cx, id, vp);
}
return PR_TRUE;
}
/***********************************************************************/
//
// InstallTriggerGlobal Properties Setter
//
PR_STATIC_CALLBACK(JSBool)
SetInstallTriggerGlobalProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
{
nsIDOMInstallTriggerGlobal *a = (nsIDOMInstallTriggerGlobal*)JS_GetPrivate(cx, obj);
// If there's no private data, this must be the prototype, so ignore
if (nsnull == a) {
return JS_TRUE;
}
if (JSVAL_IS_INT(id)) {
switch(JSVAL_TO_INT(id)) {
case 0:
default:
return nsJSUtils::nsCallJSScriptObjectSetProperty(a, cx, id, vp);
}
}
else {
return nsJSUtils::nsCallJSScriptObjectSetProperty(a, cx, id, vp);
}
return PR_TRUE;
}
//
// InstallTriggerGlobal finalizer
//
PR_STATIC_CALLBACK(void)
FinalizeInstallTriggerGlobal(JSContext *cx, JSObject *obj)
{
nsJSUtils::nsGenericFinalize(cx, obj);
}
//
// InstallTriggerGlobal enumerate
//
PR_STATIC_CALLBACK(JSBool)
EnumerateInstallTriggerGlobal(JSContext *cx, JSObject *obj)
{
return nsJSUtils::nsGenericEnumerate(cx, obj);
}
//
// InstallTriggerGlobal resolve
//
PR_STATIC_CALLBACK(JSBool)
ResolveInstallTriggerGlobal(JSContext *cx, JSObject *obj, jsval id)
{
return nsJSUtils::nsGenericResolve(cx, obj, id);
}
//
// Native method UpdateEnabled
//
PR_STATIC_CALLBACK(JSBool)
InstallTriggerGlobalUpdateEnabled(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
nsIDOMInstallTriggerGlobal *nativeThis = (nsIDOMInstallTriggerGlobal*)JS_GetPrivate(cx, obj);
JSBool rBool = JS_FALSE;
PRBool nativeRet;
*rval = JSVAL_NULL;
// If there's no private data, this must be the prototype, so ignore
if (nsnull == nativeThis) {
return JS_TRUE;
}
if (argc >= 0) {
if (NS_OK != nativeThis->UpdateEnabled(&nativeRet)) {
return JS_FALSE;
}
*rval = BOOLEAN_TO_JSVAL(nativeRet);
}
else {
JS_ReportError(cx, "Function UpdateEnabled requires 0 parameters");
return JS_FALSE;
}
return JS_TRUE;
}
//
// Native method StartSoftwareUpdate
//
PR_STATIC_CALLBACK(JSBool)
InstallTriggerGlobalStartSoftwareUpdate(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
nsIDOMInstallTriggerGlobal *nativeThis = (nsIDOMInstallTriggerGlobal*)JS_GetPrivate(cx, obj);
JSBool rBool = JS_FALSE;
PRInt32 nativeRet;
nsAutoString b0;
PRInt32 b1;
*rval = JSVAL_NULL;
// If there's no private data, this must be the prototype, so ignore
if (nsnull == nativeThis) {
return JS_TRUE;
}
if (argc >= 2)
{
// public int StartSoftwareUpdate(String url,
// int flag);
ConvertJSValToStr(b0, cx, argv[0]);
if(!JS_ValueToInt32(cx, argv[1], (int32 *)&b1))
{
JS_ReportError(cx, "2nd parameter must be a number");
return JS_FALSE;
}
if(NS_OK != nativeThis->StartSoftwareUpdate(b0, b1, &nativeRet))
{
return JS_FALSE;
}
*rval = INT_TO_JSVAL(nativeRet);
}
else if(argc >= 1)
{
// public int StartSoftwareUpdate(String url);
ConvertJSValToStr(b0, cx, argv[0]);
if(NS_OK != nativeThis->StartSoftwareUpdate(b0, &nativeRet))
{
return JS_FALSE;
}
*rval = INT_TO_JSVAL(nativeRet);
}
else
{
JS_ReportError(cx, "Function StartSoftwareUpdate requires 2 parameters");
return JS_FALSE;
}
return JS_TRUE;
}
//
// Native method ConditionalSoftwareUpdate
//
PR_STATIC_CALLBACK(JSBool)
InstallTriggerGlobalConditionalSoftwareUpdate(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
nsIDOMInstallTriggerGlobal *nativeThis = (nsIDOMInstallTriggerGlobal*)JS_GetPrivate(cx, obj);
JSBool rBool = JS_FALSE;
PRInt32 nativeRet;
nsAutoString b0;
nsAutoString b1;
nsAutoString b2str;
PRInt32 b2int;
nsAutoString b3str;
PRInt32 b3int;
PRInt32 b4;
*rval = JSVAL_NULL;
// If there's no private data, this must be the prototype, so ignore
if (nsnull == nativeThis) {
return JS_TRUE;
}
if(argc >= 5)
{
// public int ConditionalSoftwareUpdate(String url,
// String registryName,
// int diffLevel,
// String version, --OR-- VersionInfo version
// int mode);
ConvertJSValToStr(b0, cx, argv[0]);
ConvertJSValToStr(b1, cx, argv[1]);
if(!JS_ValueToInt32(cx, argv[2], (int32 *)&b2int))
{
JS_ReportError(cx, "3rd parameter must be a number");
return JS_FALSE;
}
if(!JS_ValueToInt32(cx, argv[4], (int32 *)&b4))
{
JS_ReportError(cx, "5th parameter must be a number");
return JS_FALSE;
}
if(JSVAL_IS_OBJECT(argv[3]))
{
JSObject* jsobj = JSVAL_TO_OBJECT(argv[3]);
JSClass* jsclass = JS_GetClass(cx, jsobj);
if((nsnull != jsclass) && (jsclass->flags & JSCLASS_HAS_PRIVATE))
{
nsIDOMInstallVersion* version = (nsIDOMInstallVersion*)JS_GetPrivate(cx, jsobj);
if(NS_OK != nativeThis->ConditionalSoftwareUpdate(b0, b1, b2int, version, b4, &nativeRet))
{
return JS_FALSE;
}
}
}
else
{
ConvertJSValToStr(b3str, cx, argv[3]);
if(NS_OK != nativeThis->ConditionalSoftwareUpdate(b0, b1, b2int, b3str, b4, &nativeRet))
{
return JS_FALSE;
}
}
*rval = INT_TO_JSVAL(nativeRet);
}
else if(argc >= 4)
{
// public int ConditionalSoftwareUpdate(String url,
// String registryName,
// String version, --OR-- VersionInfo version
// int mode);
ConvertJSValToStr(b0, cx, argv[0]);
ConvertJSValToStr(b1, cx, argv[1]);
if(!JS_ValueToInt32(cx, argv[3], (int32 *)&b3int))
{
JS_ReportError(cx, "4th parameter must be a number");
return JS_FALSE;
}
if(JSVAL_IS_OBJECT(argv[2]))
{
JSObject* jsobj = JSVAL_TO_OBJECT(argv[2]);
JSClass* jsclass = JS_GetClass(cx, jsobj);
if((nsnull != jsclass) && (jsclass->flags & JSCLASS_HAS_PRIVATE))
{
nsIDOMInstallVersion* version = (nsIDOMInstallVersion*)JS_GetPrivate(cx, jsobj);
if(NS_OK != nativeThis->ConditionalSoftwareUpdate(b0, b1, version, b3int, &nativeRet))
{
return JS_FALSE;
}
}
}
else
{
ConvertJSValToStr(b2str, cx, argv[2]);
if(NS_OK != nativeThis->ConditionalSoftwareUpdate(b0, b1, b2str, b3int, &nativeRet))
{
return JS_FALSE;
}
}
*rval = INT_TO_JSVAL(nativeRet);
}
else if(argc >= 3)
{
// public int ConditionalSoftwareUpdate(String url,
// String registryName,
// String version); --OR-- VersionInfo version
ConvertJSValToStr(b0, cx, argv[0]);
ConvertJSValToStr(b1, cx, argv[1]);
if(JSVAL_IS_OBJECT(argv[2]))
{
JSObject* jsobj = JSVAL_TO_OBJECT(argv[2]);
JSClass* jsclass = JS_GetClass(cx, jsobj);
if((nsnull != jsclass) && (jsclass->flags & JSCLASS_HAS_PRIVATE))
{
nsIDOMInstallVersion* version = (nsIDOMInstallVersion*)JS_GetPrivate(cx, jsobj);
if(NS_OK != nativeThis->ConditionalSoftwareUpdate(b0, b1, version, &nativeRet))
{
return JS_FALSE;
}
}
}
else
{
ConvertJSValToStr(b2str, cx, argv[2]);
if(NS_OK != nativeThis->ConditionalSoftwareUpdate(b0, b1, b2str, &nativeRet))
{
return JS_FALSE;
}
}
*rval = INT_TO_JSVAL(nativeRet);
}
else
{
JS_ReportError(cx, "Function ConditionalSoftwareUpdate requires 5 parameters");
return JS_FALSE;
}
return JS_TRUE;
}
//
// Native method CompareVersion
//
PR_STATIC_CALLBACK(JSBool)
InstallTriggerGlobalCompareVersion(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
nsIDOMInstallTriggerGlobal *nativeThis = (nsIDOMInstallTriggerGlobal*)JS_GetPrivate(cx, obj);
JSBool rBool = JS_FALSE;
PRInt32 nativeRet;
nsAutoString b0;
nsAutoString b1str;
PRInt32 b1int;
PRInt32 b2int;
PRInt32 b3int;
PRInt32 b4int;
*rval = JSVAL_NULL;
// If there's no private data, this must be the prototype, so ignore
if (nsnull == nativeThis) {
return JS_TRUE;
}
if(argc >= 5)
{
// public int CompareVersion(String registryName,
// int major,
// int minor,
// int release,
// int build);
ConvertJSValToStr(b0, cx, argv[0]);
if(!JS_ValueToInt32(cx, argv[1], (int32 *)&b1int))
{
JS_ReportError(cx, "2th parameter must be a number");
return JS_FALSE;
}
if(!JS_ValueToInt32(cx, argv[2], (int32 *)&b2int))
{
JS_ReportError(cx, "3th parameter must be a number");
return JS_FALSE;
}
if(!JS_ValueToInt32(cx, argv[3], (int32 *)&b3int))
{
JS_ReportError(cx, "4th parameter must be a number");
return JS_FALSE;
}
if(!JS_ValueToInt32(cx, argv[4], (int32 *)&b4int))
{
JS_ReportError(cx, "5th parameter must be a number");
return JS_FALSE;
}
if(NS_OK != nativeThis->CompareVersion(b0, b1int, b2int, b3int, b4int, &nativeRet))
{
return JS_FALSE;
}
*rval = INT_TO_JSVAL(nativeRet);
}
else if(argc >= 2)
{
// public int CompareVersion(String registryName,
// String version); --OR-- VersionInfo version
ConvertJSValToStr(b0, cx, argv[0]);
if(JSVAL_IS_OBJECT(argv[1]))
{
JSObject* jsobj = JSVAL_TO_OBJECT(argv[1]);
JSClass* jsclass = JS_GetClass(cx, jsobj);
if((nsnull != jsclass) && (jsclass->flags & JSCLASS_HAS_PRIVATE))
{
nsIDOMInstallVersion* version = (nsIDOMInstallVersion*)JS_GetPrivate(cx, jsobj);
if(NS_OK != nativeThis->CompareVersion(b0, version, &nativeRet))
{
return JS_FALSE;
}
}
}
else
{
ConvertJSValToStr(b1str, cx, argv[1]);
if(NS_OK != nativeThis->CompareVersion(b0, b1str, &nativeRet))
{
return JS_FALSE;
}
}
*rval = INT_TO_JSVAL(nativeRet);
}
else
{
JS_ReportError(cx, "Function CompareVersion requires 5 parameters");
return JS_FALSE;
}
return JS_TRUE;
}
/***********************************************************************/
//
// class for InstallTriggerGlobal
//
JSClass InstallTriggerGlobalClass = {
"InstallTriggerGlobal",
JSCLASS_HAS_PRIVATE,
JS_PropertyStub,
JS_PropertyStub,
GetInstallTriggerGlobalProperty,
SetInstallTriggerGlobalProperty,
EnumerateInstallTriggerGlobal,
ResolveInstallTriggerGlobal,
JS_ConvertStub,
FinalizeInstallTriggerGlobal
};
//
// InstallTriggerGlobal class properties
//
static JSPropertySpec InstallTriggerGlobalProperties[] =
{
{0}
};
//
// InstallTriggerGlobal class methods
//
static JSFunctionSpec InstallTriggerGlobalMethods[] =
{
{"UpdateEnabled", InstallTriggerGlobalUpdateEnabled, 0},
{"StartSoftwareUpdate", InstallTriggerGlobalStartSoftwareUpdate, 2},
{"ConditionalSoftwareUpdate", InstallTriggerGlobalConditionalSoftwareUpdate, 5},
{"CompareVersion", InstallTriggerGlobalCompareVersion, 5},
{0}
};
//
// InstallTriggerGlobal constructor
//
PR_STATIC_CALLBACK(JSBool)
InstallTriggerGlobal(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
return JS_FALSE;
}
//
// InstallTriggerGlobal class initialization
//
nsresult NS_InitInstallTriggerGlobalClass(nsIScriptContext *aContext, void **aPrototype)
{
JSContext *jscontext = (JSContext *)aContext->GetNativeContext();
JSObject *proto = nsnull;
JSObject *constructor = nsnull;
JSObject *parent_proto = nsnull;
JSObject *global = JS_GetGlobalObject(jscontext);
jsval vp;
if ((PR_TRUE != JS_LookupProperty(jscontext, global, "InstallTriggerGlobal", &vp)) ||
!JSVAL_IS_OBJECT(vp) ||
((constructor = JSVAL_TO_OBJECT(vp)) == nsnull) ||
(PR_TRUE != JS_LookupProperty(jscontext, JSVAL_TO_OBJECT(vp), "prototype", &vp)) ||
!JSVAL_IS_OBJECT(vp)) {
proto = JS_InitClass(jscontext, // context
global, // global object
parent_proto, // parent proto
&InstallTriggerGlobalClass, // JSClass
InstallTriggerGlobal, // JSNative ctor
0, // ctor args
InstallTriggerGlobalProperties, // proto props
InstallTriggerGlobalMethods, // proto funcs
nsnull, // ctor props (static)
nsnull); // ctor funcs (static)
if (nsnull == proto) {
return NS_ERROR_FAILURE;
}
if ((PR_TRUE == JS_LookupProperty(jscontext, global, "InstallTriggerGlobal", &vp)) &&
JSVAL_IS_OBJECT(vp) &&
((constructor = JSVAL_TO_OBJECT(vp)) != nsnull)) {
vp = INT_TO_JSVAL(nsIDOMInstallTriggerGlobal::MAJOR_DIFF);
JS_SetProperty(jscontext, constructor, "MAJOR_DIFF", &vp);
vp = INT_TO_JSVAL(nsIDOMInstallTriggerGlobal::MINOR_DIFF);
JS_SetProperty(jscontext, constructor, "MINOR_DIFF", &vp);
vp = INT_TO_JSVAL(nsIDOMInstallTriggerGlobal::REL_DIFF);
JS_SetProperty(jscontext, constructor, "REL_DIFF", &vp);
vp = INT_TO_JSVAL(nsIDOMInstallTriggerGlobal::BLD_DIFF);
JS_SetProperty(jscontext, constructor, "BLD_DIFF", &vp);
vp = INT_TO_JSVAL(nsIDOMInstallTriggerGlobal::EQUAL);
JS_SetProperty(jscontext, constructor, "EQUAL", &vp);
}
}
else if ((nsnull != constructor) && JSVAL_IS_OBJECT(vp)) {
proto = JSVAL_TO_OBJECT(vp);
}
else {
return NS_ERROR_FAILURE;
}
if (aPrototype) {
*aPrototype = proto;
}
return NS_OK;
}
//
// Method for creating a new InstallTriggerGlobal JavaScript object
//
extern "C" NS_DOM nsresult NS_NewScriptInstallTriggerGlobal(nsIScriptContext *aContext, nsISupports *aSupports, nsISupports *aParent, void **aReturn)
{
NS_PRECONDITION(nsnull != aContext && nsnull != aSupports && nsnull != aReturn, "null argument to NS_NewScriptInstallTriggerGlobal");
JSObject *proto;
JSObject *parent;
nsIScriptObjectOwner *owner;
JSContext *jscontext = (JSContext *)aContext->GetNativeContext();
nsresult result = NS_OK;
nsIDOMInstallTriggerGlobal *aInstallTriggerGlobal;
if (nsnull == aParent) {
parent = nsnull;
}
else if (NS_OK == aParent->QueryInterface(kIScriptObjectOwnerIID, (void**)&owner)) {
if (NS_OK != owner->GetScriptObject(aContext, (void **)&parent)) {
NS_RELEASE(owner);
return NS_ERROR_FAILURE;
}
NS_RELEASE(owner);
}
else {
return NS_ERROR_FAILURE;
}
if (NS_OK != NS_InitInstallTriggerGlobalClass(aContext, (void **)&proto)) {
return NS_ERROR_FAILURE;
}
result = aSupports->QueryInterface(kIInstallTriggerGlobalIID, (void **)&aInstallTriggerGlobal);
if (NS_OK != result) {
return result;
}
// create a js object for this class
*aReturn = JS_NewObject(jscontext, &InstallTriggerGlobalClass, proto, parent);
if (nsnull != *aReturn) {
// connect the native object to the js object
JS_SetPrivate(jscontext, (JSObject *)*aReturn, aInstallTriggerGlobal);
}
else {
NS_RELEASE(aInstallTriggerGlobal);
return NS_ERROR_FAILURE;
}
return NS_OK;
}

Some files were not shown because too many files have changed in this diff Show More