TOC PREV NEXT INDEX


Appendix B:
XPCOM API Reference


XPCOM Core

XPCOM is Mozilla's Cross Platform Component Object Model. It is used to unify the creation, ownership, and deletion of objects and other data throughout Mozilla. The following interfaces are the core interfaces associated with the functioning of XPCOM.

Included Interfaces:

nsISupports

This is the interface from which all other XPCOM interfaces inherit. It provides the foundation for XPCOM interface discovery and lifetime object management. In most of our examples through the book, we used nsCOMPtr which calls these methods. For example, when we made calls to do_QueryInterface, it made a call to the method QueryInterface on the target object.

Methods:

QueryInterface

Provides a mechanism for requesting interfaces to which a given object might provide access. The semantics of QueryInterface dictate that given an interface A that you call QueryInterfce on to get to interface B, you must be able to call QueryInterface on B to get back to A.

Syntax:

nsresult QueryInterface(const nsIID & uuid, void * *result); 

Parameters:

uuid: The IID of the requested interface.
result: [out] The reference to return. If this method call was successful, this out parameter will have had its reference count increased by one, effectively making the caller and owner of this object.

Result:

NS_OK if the interface was successfully returned.
NS_NOINTERFACE if the object does not support the given interface.

Example
#include "nsIComponentRegistrar.h" 
 
nsIComponentRegistrar* compReg = nsnull; 
nsresult rv = 
   aCompMgr->QueryInterface(kIComponentRegistrarIID,(void**)& comp); 

You can also use nsCOMPtr helper method do_QueryInterface that calls through to the QueryInterface method of the aCompMgr object:

#include "nsIComponentRegistrar.h" 
nsresult rv; 
nsCOMPtr<nsIComponentRegistrar> compRef = 
  do_QueryInterface(aCompMgr, &rv); 

AddRef

Increments the internal refcount of the interface.

Syntax:

nsrefcnt AddRef()

Parameters:

None.

Result:

The refcount.

Release

Decrements the internal refcount of the interface. When the count reaches zero, the interface deletes itself. To prevent objects leaking, every reference count must be accounted for. For example, if you call QueryInterface on an object, the result of this must be release at some point before the application shuts down. To release an object you must either use nsCOMPtr, a smart pointer which keeps track of references, or you must manually called Release on that object.

Syntax:

nsrefcnt Release() 

Parameters:

None.

Result:

The refcount.

nsIInterfaceRequestor

This interface defines a generic interface for requesting interfaces to which a given object might provide access. It is very similar to QueryInterface found in nsISupports . The main difference is that interfaces returned from GetInterface are not required to provide a way back to the object implementing this interface. The semantics of QI dictate that given an interface A that you QI on to get to interface B, you must be able to QI on B to get back to A. This interface, however, allows you to obtain an interface C from A that may or most likely will not have the ability to get back to A.

Methods:

GetInterface

Retrieves the specified interface pointer.

Syntax:

nsresult GetInterface(const nsIID & uuid, void * *result);  

Parameters:

uuid: The IID of the interface being requested.
result: [out] The interface pointer to be filled in if the interface is accessible.

Result:

NS_OK if the interface was successfully returned.
NS_NOINTERFACE if the interface is not accessible.
NS_ERROR* if there is method failure.

Example:

The interface that mWebBrowser references is a nsIInterfaceRequestor. We can ask this interface, if it knows anything about the nsIWebBrowser. If it does, it will return that object:

 nsCOMPtr<nsIWebBrowserFind> finder(do_GetInterface(mWebBrowser)); 

nsIWeakReference

This interface gives access to a proxy object that cooperates with its referent to give clients a non-owning, non-dangling reference. Clients own the proxy, and should generally manage it with an nsCOMPtr as they would any other XPCOM object. The QueryReferent member function provides a owning reference on demand, through which clients can get useful access to the referent, while it still exists.

There are two common usage of this interface. The first is used for breaking a shutdown problems where the implementing object may be deleted without the owning object knowing about it. The second usage of this interface is to break circular dependencies. A circular dependency is when object A refers to object B and at the same time, object B refers to object A. In this case, special measures must be taken to avoid memory leaks.

Methods:

QueryReferent

Queries the referent, if it exists, and like QueryInterface, returns an owning reference to the desired interface.It is designed to look and act exactly like (a proxied) QueryInterface. Don't hold on to the produced interface permanently; that would defeat the purpose of using a non-owning nsIWeakReference in the first place.

Syntax:

nsresult QueryReferent(const nsIID & uuid, void * *result);  

Parameters:

uuid: The IID of the interface being requested.
result: [out] The interface pointer to be filled in if the interface is accessible.

Result:

NS_OK if successful.

Example

 nsCOMPtr<nsIWeakReference>
    thisListener(dont_AddRef(NS_GetWeakReference(listener))); 

nsIMemory

This interface is used to allocate and deallocate memory. It also provides for notifications in low-memory situations. This interface must be used to allocate all memory that is passed between interface bountries. For example, if an interface passes a memory buffer with the expectation that the buffer is now owned by the caller, the assuption is that this memory buffer will be freed by the nsIMemory. This rule need only apply to memory which passes through the interface boundry. Internal component memory usage can use any allocator.

There is a static helper class known as the nsMemory which aides in using the nsIMemory. nsMemory allows you to quickly obtain memory access without having to aquire the pointer to the nsIMemory interface.

A client that wishes to be notified of low memory situations (for example, because the client maintains a large memory cache that could be released when memory is tight) should register with the observer service (see nsIObserverService ) using the topic memory-pressure.

There are three specific types of notications that can occur. These types will be passed as the aData parameter of the of the "memory-pressure" notification:

low-memory: This will be passed as the extra data when the pressure observer is being asked to flush for low-memory conditions.
heap-minimize: This will be passed as the extra data when the pressure observer is being asked to flush because of a heap minimize call.
alloc-failure: This will be passed as the extra data when the pressure observer has been asked to flush because a malloc() or realloc() has failed.

Methods:

Alloc

Allocates a block of memory of a particular size. If the memory cannot be allocated (because of an out-of-memory condition), null is returned.

Syntax:

void * Alloc(size_t size) 

Parameters:

size: The size of the block to allocate.

Returns:

The block of memory.

Realloc

Reallocates a block of memory to a new size.

Syntax:

void * Realloc(void * ptr, size_t newSize); 

Parameters:

ptr: The block of memory to reallocate.
size: The new size.

Returns:

The reallocated block of memory

Note: If ptr is null, this function behaves like malloc. If s is the size of the block to which ptr points, the first min(s, size) bytes of ptr's block are copied to the new block. If the allocation succeeds, ptr is freed and a pointer to the new block returned. If the allocation fails, ptr is not freed and null is returned. The returned value may be the same as ptr.

Free

Frees a block of memory. Null is a permissible value, in which case nothing happens.

Syntax:

void Free(void * ptr); 

Parameters:

ptr: The block of memory to free.

Returns:

None.

HeapMinimize

Attempts to shrink the heap. This method is scriptable.

Syntax:

nsresult HeapMinimize(PRBool immediate); 

Parameters:

immediate: If the value is true, heap minimization will occur immediately if the call was made on the main thread. If the value is false, the flush will be scheduled to happen when the app is idle.

Result:

NS_ERROR_FAILURE if 'immediate' is set and the call was not on the application's main thread.

IsLowMemory

Indicates a low-memory situation (what constitutes low-memory is platform dependent). This can be used to trigger the memory pressure observers.

Syntax:

nsresult IsLowMemory(PRBool *_retval) 

Parameters:

None.

Returns:

TRUE if memory is low.
FALSE otherwise.

nsIProgrammingLanguage

Enumeration of programming languages. These values are used by the nsIClassInfo interface and indicate in what programming language the component was implemented. Note that the ZX81_BASIC value is a joke.

Constants

This list can grow indefinitely. Existing items, however, must not be changed.

XPCOM Components

These interfaces provide access to XPCOM's mechanisms for creating, managing and destroying objects.

Included Interfaces:

nsIComponentManager

This interface accesses the mechanism used to organize and create objects in XPCOM.

Methods:

GetClassObject

Returns the class object represented by the CID aClass. The result is an object that implements the nsIFactory interface. The result may also implement the nsIClassInfo interface.

Syntax:

nsresult GetClassObject(const nsCID & aClass, const nsIID & aIID, void * *result); 

Parameters:

aClass: The class ID of the class whose factory is being requested.
aIID: The interface ID of the interface that the factory's class implements.
result: [out] The reference to return.

Result:

NS_OK if successful.

GetClassObjectByContractID

This method is exactly the same as getClassObject but instead of a CID parameter, this method takes a contract ID string.

Syntax:

nsresult GetClassObjectByContractID(const char *aContractID, const nsIID & aIID, void * *result); 

Parameters:

aContractID: The contract ID of the class whose factory is being requested.
aIID: The interface ID of the interface that the factory's class implements.
result: [out] The reference to return.

Result:

NS_OK if successful.

CreateInstance

Creates an instance of the class indicated by the class ID and returns the interface indicated by the interface ID.

Syntax:

nsresult CreateInstance(const nsCID & aClass, nsISupports *aDelegate, const nsIID & aIID, void * *result); 

Parameters:

aClass: The class ID of the requested class.
aDelegate: Used for aggregation.
aIID: The ID of the requested interface.
result: [out] The reference to return.

Result:

NS_OK if successful

Example

#include "nsXPCOMCID.h" 
#include "nsXPCOM.h" 
#include "nsIComponentManager.h" 
#include "nsISupportsPrimitives.h" 
 
static NS_DEFINE_CID(kSupportsStringCID, NS_SUPPORTS_CSTRING_CID); 
 
nsCOMPtr<nsIComponentManager> compMgr; 
rv = NS_GetComponentManager(getter_AddRefs(compMgr)); 
if (NS_FAILED(rv)) return rv; 
 
nsISupportsCString* stringSupports; 
compMgr->CreateInstance(kSupportsStringCID, nsnull,  
                             NS_GET_IID(nsISupportsCString),  
                             (void**)&stringSupports); 
 
if (!stringSupports) 
        return NS_ERROR_UNEXPECTED; 

CreateInstanceByContractID

Creates an instance of the class indicated by the contract ID string and returns the interface indicated by the interface ID.

Syntax:

nsresult CreateInstanceByContractID(const char *aContractID, nsISupports *aDelegate, const nsIID & aIID, void * *result);  

Parameters:

aContractID: The contract ID of the requested class.
aDelegate: Used for aggregation.
aIID: The ID of the requested interface.
result: [out] The reference to return.

Result:

NS_OK if successful

Example

#include "nsXPCOMCID.h" 
#include "nsXPCOM.h" 
#include "nsIComponentManager.h" 
#include "nsISupportsPrimitives.h" 
 
nsCOMPtr<nsIComponentManager> compMgr; 
rv = NS_GetComponentManager(getter_AddRefs(compMgr)); 
if (NS_FAILED(rv)) return rv; 
 
nsISupportsCString* stringSupports; 
compMgr->CreateInstanceByContractID(NS_SUPPORTS_CSTRING_CONTRACTID, nsnull,  
                             NS_GET_IID(nsISupportsCString),  
                             (void**)&stringSupports); 
 
if (!stringSupports) 
        return NS_ERROR_UNEXPECTED; 

nsIFactory

A class factory allows the creation of nsISupports derived components without specifying a concrete base class.

See "webLock1.cpp" on page 68 for a complete listing of a sample nsIModule implementation.

Methods:

CreateInstance

Creates an instance of an object that implements the specified IID.

Syntax:

nsresult CreateInstance(nsISupports *aOuter, const nsIID & iid, void * *result) 

Parameters:

aOuter: Pointer to a component that wishes to be aggregated in the resulting instance. This will be nsnull if no aggregation is requested.
iid: The IID of the interface being requested in the component which is being currently created.
result: [out] Pointer to the newly created instance, if successful.

Result:

NS_OK if the component was successfully created and the interface being requested was successfully returned in result.
NS_NOINTERFACE if the interface not accessible.
NS_ERROR_NO_AGGREGATION if an 'outer' object is supplied, but the component is not aggregatable.
NS_ERROR* if there is a method failure.

LockFactory

Provides the client a way to keep the component in memory until the client is finished with it. The client can call LockFactory(PR_TRUE) to lock the factory and LockFactory(PR_FALSE) to release the factory.

In the generic factory code we used thorough our examples, this method is a noop.

Syntax:

nsresult LockFactory(PRBool lock);  

Parameters:

lock must be PR_TRUE or PR_FALSE

Result:

NS_OK if the lock operation was successful.
NS_ERROR* if there is a method failure.

nsIModule

This interface handles module registration and management. A module is a non empty set of factories. The main entry point of all XPCOM component librares are expected to return a nsIModule implementation. This interface is meant to be implemented by a component and called only from inside XPCOM. Developers are not encouraged to call on this interface directly, but instead use the Component and Service Manager for component access and control.

See page "webLock1.cpp" on page 68 for a complete listing of a sample nsIModule implementation.

Methods:

GetClassObject

Obtains a factory object from an nsIModule for a given CID and IID pair. This method is called from XPCOM when XPCOM wants to discover a class object for CID implementing a given IID in a component library.

Syntax:

nsresult GetClassObject(nsIComponentManager *aCompMgr, const nsCID & aClass, const nsIID & aIID, void * *aResult) 

Parameters:

aCompMgr: The component manager.
aClass: The class ID of the class for which aResult is the factory.
aIID: The interface ID of the requested interface.
aResult: [out] The reference to return.

Result:

NS_OK if successful.

RegisterSelf

registerSelf is called by XPCOM on a component giving the component time to register with the Component Manager.

Syntax:

nsresult RegisterSelf(nsIComponentManager *aCompMgr, nsIFile *aLocation, const char *aLoaderStr, const char *aType) 

Parameters:

aCompMgr: The Component Manager. This interface may be queried to the nsIComponentRegistrar for registration needs.
aLocation : The location of the module on disk .
aLoaderStr: Opaque loader specific string. This value is meant to be passed into the registration methods of nsIComponentRegistrar unmodified.
aType: Loader Type being used to load this module. This value is meant to be passed into the registration methods of nsIComponentRegistrar unmodified.

Result:

NS_OK if successful.

UnregisterSelf

unregisterSelf is called by XPCOM on a component giving the component time to unregister itself from the Component Manager.

Syntax:

nsresult UnregisterSelf(nsIComponentManager *aCompMgr, nsIFile *aLocation, const char *aLoaderStr) 

Parameters:

aCompMgr : The component manager. This interface may be queried to the nsIComponentRegistrar for registration needs.
aLocation : The location of the module on disk. This value is meant to be passed into the registration methods of nsIComponentRegistrar unmodified.

aLoaderStr: Opaque loader specific string.This value is meant to be passed into the registration methods of nsIComponentRegistrar unmodified.

Result:

NS_OK if successful.

CanUnload

Indicates that the module is willing to be unloaded. This does not guarantee that the module will be unloaded. Unless you know that you component can be unloaded safely, you must return FALSE.

The generic module always returns false.

Syntax:

nsresult CanUnload(nsIComponentManager *aCompMgr, PRBool *_retval) 

Parameters:

aCompMgr: The component manager.

Return:

PR_TRUE if the module is willing to be unloaded. It is very important to check that no outstanding references to the module's code/data exist before returning true.
PR_FALSE guarantees that the module will not be unloaded.

nsIComponentRegistrar

This interface handles all component registration and management in XPCOM. There are basically four conceptual parts to this interface: (1) queries to see what has been registered, (2) register methods that take an in-memory instance of nsIFactory objects, (3) register components that exist at a specific place, and finally (4) callbacks that allow components to register themselves during nsIModule method RegisterSelf.

Methods:

AutoRegister

Registers a component file or all component files in a directory. This method is usually called by the application to register a component or all components in a directory. If a directory is pass, the directory will be recursively traversed. Each component file must be valid as defined by acomponent's loader. For example, if the given file is a native library, it must export the symbol NSGetModule. Other loaders may have different semantics.

This method may only be called from the main thread.

Syntax:

nsrsult AutoRegister(nsIFile *aSpec); 

Parameters:

aSpec: Filename spec for component file's location. If aSpec is a directory, then every component file in the directory will be registered. If the aSpec is null, then the application component's directory and the GRE components directory, if one exists, will be registered. (see nsIDirectoryService.idl)

Result:

NS_OK if registration was successful.
NS_ERROR if not.
#include "nsXPCOMCID.h" 
#include "nsXPCOM.h" 
#include "nsIComponentRegistrar.h" 
 
nsCOMPtr<nsIComponentRegistrar> registrar; 
nsresult rv = NS_GetComponentRegistrar(getter_AddRefs(registrar)); 
if (NS_FAILED(rv)) return rv; 
 
rv = registrar->AutoRegister(nsnull); 
 

AutoUnregister

Similar to autoRegister, this method registers a component file or all component files in a directory. This method is usually called by the application to unregister a component or all components in a directory.

This method may only be called from the main thread.

Syntax:

nsresult AutoUnregister(nsIFile *aSpec) 

Parameters:

aSpec: Filename spec for component file's location. If aSpec is a directory, then every component file in the directory will be registered. If the aSpec is null, then the application component's directory and the GRE components directory, if one exists, will be registered. (see nsIDirectoryService.idl)

Result:

NS_OK if unregistration was successful.
NS_ERROR if not.

RegisterFactory

Registers a instantiated nsIFactory factory object with a given ContractID, CID, and Class Name. This nsIFactory object will only be registered until XPCOM shuts down.

Syntax:

nsresult RegisterFactory(const nsCID & aClass, const char *aClassName, const char *aContractID, nsIFactory *aFactory) 

Parameters:

aClass: The CID.
aClassName: The Class Name associated with aClass.
aContractID: The ContractID associated with aClass.
aFactory: The factory that will be registered for aClass.

Result:

NS_OK if registration was successful.
NS_ERROR if not.

UnregisterFactory

Unregisters a factory associated with CID aClass.

Syntax:

nsresult UnregisterFactory(const nsCID & aClass, nsIFactory *aFactory) 

Parameters:

aClass: The CID being unregistered.
aFactory: The factory that will be unregistered for aClass.

Result:

NS_OK if unregistration was successful.
NS_ERROR if not.

RegisterFactoryLocation

This is a low level method that allows registration of a factory object given ContractID, CID and Class Name, location, and so forth. This call is usually maded from the nsIModule implementations of a component library to register its factories.

Syntax:

nsresult RegisterFactoryLocation(const nsCID & aClass, const char *aClassName, const char *aContractID, nsIFile *aFile, const char *aLoaderStr, const char *aType) 

Parameters:

aClass: The CID of the class.
aClassName: The Class Name of aClass.
aContractID: The ContractID associated with aClass.
aFile: The Component File. This file must have an associated loader and export the required symbols which this loader specifies.
aLoaderStr: An opaque loader specific string. This value is passed into the nsIModule's registerSelf callback and must be fowarded unmodified when registering factories via their location.
aType: The Component Type of aClass. This value is passed into the nsIModule's registerSelf callback and must be fowarded unmodified when registering factories via their location.

Result:

NS_OK if registration was successful.
NS_ERROR if not.

See page "webLock1.cpp" on page 68 for a complete listing of a sample nsIModule implementation which calls registerFactoryLocation.

UnregisterFactoryLocation

This is a low level method that allows unregistering a factory associated with aClass. This call is usually maded from the nsIModule implementations of a component library to unregister its factories.

Syntax:

nsresult UnregisterFactoryLocation(const nsCID & aClass, nsIFile *aFile) 

Parameters:

aClass: The CID being unregistered.
aFile: The Component File previously registered.

Result:

NS_OK if unregistration was successful.
NS_ERROR if not.

See page "webLock1.cpp" on page 68 for a complete listing of a sample nsIModule implementation which calls unregisterFactoryLocation.

IsCIDRegistered

Returns true if a factory is registered for a CID.

Syntax:

nsresult IsCIDRegistered(const nsCID & aClass, PRBool *_retval) 

Parameters:

aClass: The CID queried for registration.

Returns:

TRUE if a factory is registered for the CID
FALSE if not.

IsContractIDRegistered

Returns true if a factory is registered for a ContractID.

Syntax:

nsresult IsContractIDRegistered(const char *aContractID, PRBool *_retval) 

Parameters:

aContractID: The ContractID queried for registration.

Returns:

TRUE if a factory is registered for the ContractID.
FALSE if not.

EnumerateCIDs

Enumerates the list of all registered CIDs. Elements of the enumeration can be QueryInterface'd for the nsISupportsID interface. From the nsISupportsID, you can obtain the actual CID.

Syntax:

nsresult EnumerateCIDs(nsISimpleEnumerator **_retval) 

Parameters:

None.

Returns:

An enumerator for CIDs

EnumerateContractIDs

Enumerates the list of all registered ContractIDs. Elements of the enumeration can be QueryInterface'd for the nsISupportsCString interface. From the nsISupportsCString interface, you can obtain the actual Contract ID string.

Syntax:

EnumerateContractIDs(nsISimpleEnumerator **_retval) 

Parameters:

None.

Returns:

An enumerator for ContractIDs.

CIDToContractID

Gets the ContractID for a given CID, if one exists and is registered.

Syntax:

nsresult CIDToContractID(const nsCID & aClass, char **_retval) 

Parameters:

aClass: The CID whose ContractID is being sought.

Returns:

The ContractID.

ContractIDToCID

Gets the CID for a given Contract ID, if one exists and is registered.

Syntax:

nsresult ContractIDToCID(const char *aContractID, nsCID * *_retval) 

Parameters:

aContractID: The ContractID whose CID is being sought.

Returns:

The CID.

nsIServiceManager

This interface provides a means to obtain global services (ie, access to a singleton object) in an application. . Users of the service manager must first obtain a pointer to the global service manager by calling NS_GetServiceManager. After that, they can request specific services by calling GetService. When they are finished they should NS_RELEASE the service as usual. A user of a service may keep references to particular services indefinitely and must call Release only when XPCOM shuts down.

Methods:

GetService

Returns the object that implements aClass and the interface aIID. This may result in the object being created.

Syntax:

nsresult GetService(const nsCID & aClass, const nsIID & aIID, void * *result) 

Parameters:

aClass: The class ID of the requested class.
aIID : The interface ID of the requested interface.
result :[out] The resulting service

Result:

NS_OK if successful.

Example

nsCOMPtr<nsIServiceManager> mgr; 
NS_GetServiceManager(getter_AddRefs(mgr)); 
if (mgr) 
rv = mgr->GetService(mCID, aIID, (void**)aInstancePtr); 

GetServiceByContractID

Returns the object that implements aContractID and the interface aIID. This may result in the instance being created.

Syntax:

void nsIServiceManager::GetServiceByContractID(in string aContractID, in nsIIDRef aIID,[iid_is(aIID),retval] out nsQIResult result)  

Parameters:

aContractID: The contract ID of the requested class.
aIID : The interface ID of the requested interface.
result :[out] The reference to return.

Result:

NS_OK if successful.

Example

nsCOMPtr<nsIServiceManager> mgr; 
NS_GetServiceManager(getter_AddRefs(mgr)); 
if (mgr) 
rv = mgr->GetServiceByContractID(
  mContractID, aIID, (void**)aServicePtr); 

IsServiceInstantiated

Returns TRUE if the singleton service object has already been created.

Syntax:

nsresult IsServiceInstantiated(const nsCID & aClass, const nsIID & aIID, PRBool *_retval) 

Parameters:

aClass: The class ID of the requested class.
aIID : The interface ID of the requested interface.

Return:

PR_TRUE if the object has already been created.
PR_FALSE if the object has not been created.

IsServiceInstantiatedByContractID

ReturnsTRUE if the singleton service object has already been created.

Syntax:

nsresult IsServiceInstantiatedByContractID(const char *aContractID, const nsIID & aIID, PRBool *_retval) 

Parameters:

aContractID: The contract ID of the requested class.
aIID : The interface ID of the requested interface.

Result:

PR_TRUE if the object has already been created.
PR_FALSE if the object has not been created.

nsIClassInfo

This interface provides information about a specific implementation class.

Methods:

GetInterfaces

Returns an ordered list of the interface IDs that instances of the class promise to implement. Note that nsISupports is an implicit member of any such list and need not be included. Should set *count = 0 and *array = null and return NS_OK if getting the list is not supported.

Syntax:

nsresult GetInterfaces(PRUint32 *count, nsIID * **array) 

Parameters:

count: [out]The number of implemented interfaces.
array: [out] The list of implemented interfaces.

Result:

NS_OK if successful, or if getting list is not supported.

GetHelperForLanguage

Gets a language mapping specific helper object that may assist in using objects of this class in a specific lanaguage. For instance, if asked for the helper for nsIProgrammingLanguage::JAVASCRIPT this might return an object that can be QI'd into the nsIXPCScriptable interface to assist XPConnect in supplying JavaScript specific behavior to callers of the instance object. Should return null if no helper available for given language.

Syntax:

nsresult GetHelperForLanguage(PRUint32 language, nsISupports **_retval) 

Parameters:

language: An integer representing the requested language.

Returns:

The helper object.

See also: nsIProgrammingLanguage for language constants.

GetContractID

Returnes a string contract ID through which an instance of this class can be created (or accessed as a service, if flags & SINGLETON), or null.

Syntax:

nsresult GetContractID(char * *aContractID)

GetClassDescription

Gets a human readable string naming the class, or null.

Syntax:

nsresult GetClassDescription(char * *aClassDescription)

GetClassID

Gets the class ID through which an instance of this class can be created (or accessed as a service, if flags & SINGLETON), or null.

Syntax:

nsresult GetClassID(nsCID * *aClassID);

GetImplementationLanguage

Gets the language type from list in nsIProgrammingLanguage.

Syntax:

nsresult GetImplementationLanguage(PRUint32 *aImplementationLanguage);

GetClassIDNoAlloc

Gets a class ID through which an instance of this class can be created (or accessed as a service, if flags & SINGLETON). If the class does not have a CID, it should return NS_ERROR_NOT_AVAILABLE. This attribute exists so C++ callers can avoid allocating and freeing a CID, as would happen if they used class ID.

Syntax:

nsresult GetClassIDNoAlloc(nsCID *aClassIDNoAlloc)

GetFlags

Returns implementation flags which made be ORed together of the values below.

Syntax:

nsresult GetFlags(PRUint32 *aFlags)

Flags:

Note: The high order bit is RESERVED for consumers of these flags. No implementor of this interface should ever return flags with this bit set.

SINGLETON
Flag specifies that the object is a singleton or service.
THREADSAFE
Flag specifies that the object is a threadsafe.
MAIN_THREAD_ONLY
Flag specifies that the object may only be called from the main (UI) thread.
DOM_OBJECT
Flag specifies that the object is part of the DOM.
PLUGIN_OBJECT
Flag specifies that the object is a plugin object.
CONTENT_NODE
Flag specifies that the object is a content node.
EAGER_CLASSINFO
Flag tells the generic module code to construct a factory object during initialization.
RESERVED

Flags saved for future use.

XPCOM Data Structures

These interfaces provide access to various utility mechanisms in XPCOM.

Included Interfaces:

nsICategoryManager

This interface is implemented by an object that wants to observe an event corresponding to a topic.

Methods:

GetCategoryEntry

Get the value for the given category's entry.

Syntax:

nsresult GetCategoryEntry(const char *aCategory, const char *aEntry, char **_retval) 

Parameters:

aCategory: The name of the category (e.g. "protocol").
aEntry: The entry you're looking for (e.g. "http").
_retval: [out] returns the category entry corresponding to the category and entry.

Result:

NS_OK if successful.

AddCategoryEntry

Add an entry to a category.

Syntax:

nsresult AddCategoryEntry(const char *aCategory, const char *aEntry, const char *aValue, PRBool aPersist, PRBool aReplace, char **_retval) 

Parameters:

aCategory: The name of the category (e.g. "protocol").
aEntry: The entry you're looking for (e.g. "http").
aValue: The value for the entry ("moz.httprulez.1")
aPersist: Should we persist between invocations? This value is ignored in some implementations.
aReplace: Should we replace an existing entry? This value is ignored in some implementations.
_retval: [out] Returns the previous category entry corresponding to the category and entry Previous entry, if any..

Result:

NS_OK if successful.

DeleteCategoryEntry

Delete an entry from the category.

Syntax:

nsresult DeleteCategoryEntry(const char *aCategory, const char *aEntry, PRBool aPersist) 

Parameters:

aCategory: The name of the category (e.g. "protocol").
aEntry: The entry you're looking for (e.g. "http").
aPersist: Should we persist between invocations? This value is ignored in some implementations.

Result:

NS_OK if successful.

DeleteCategory

Delete a category and all entries.

Syntax:

nsresult DeleteCategory(const char *aCategory) 

Parameters:

aCategory: The name of the category (e.g. "protocol").

Result:

NS_OK if successful.

EnumerateCategory

Enumerate the entries in a category.

Syntax:

nsresult EnumerateCategory(const char *aCategory, nsISimpleEnumerator **_retval) 

Parameters:

aCategory: The name of the category (e.g. "protocol").
_retval: [out] returns an enumeration of all of the entries in the given category. The elements of the enumeration can be QueryInterface'd for the nsISupportsCString interface. From the nsISupportsCString, you can obtain the actual string of the entry.

Result:

NS_OK if successful.

EnumerateCategories

Enumerate the entries in a category.

Syntax:

nsresult EnumerateCategories(nsISimpleEnumerator **_retval) 

Parameters:

_retval: [out] returns an enumeration of all of the category. The elements of the enumeration can be QueryInterface'd for the nsISupportsCString interface. From the nsISupportsCString, you can obtain the actual string of the category name.

Result:

NS_OK if successful.

nsIObserver

This interface is implemented by an object that wants to observe an event corresponding to a topic.

See also: nsIObserverService.

Methods:

Observe

Called when there is a notification for the topic aTopic. The object implementing this interface must have been registered with an observer service such as the nsIObserverService. If you expect multiple topics/subjects, your implementation is responsible for filtering. You should not modify, add, remove, or enumerate notifications in the implemention of observe.

Syntax:

nsresult Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData)  

Parameters:

aSubject: Notification specific interface pointer.
aTopic: The notification topic or subject.
aData: Notification specific wide string, depending on the subject event.

Result:

NS_OK if successful.

See page "Getting Called at Startup" on page 91, where this interface is implemented.

nsIObserverService

Service allows a client listener (nsIObserver ) to register and unregister for notifications of a specific string referenced topic. Service also provides a way to notify registered listeners and a way to enumerate registered client listeners

Methods:

AddObserver

Registers a given listener for a notifications regarding the specified topic.

Syntax:

nsresult AddObserver(nsIObserver *anObserver, const char *aTopic, PRBool ownsWeak) 

Parameters:

anObserver: The interface pointer to the object which will receive notifications.
aTopic: The notification topic or subject.
ownsWeak: If set to false, the nsIObserverService will hold a strong reference to anObserver. If set to true and anObserver supports the nsIWeakReference interface, a weak reference will be held. Otherwise an error will be returned.

Result:

NS_OK if successful.

Example:

nsCOMPtr<nsIObserverService> observerService( 
  do_GetService(/"@mozilla.org/observer-service;1"/, &rv)); 
if (NS_SUCCEEDED(rv))  
  rv = observerService->AddObserver( 
     this, 
     NS_XPCOM_SHUTDOWN_OBSERVER_ID, PR_TRUE); 

RemoveObserver

Unregisters a given listener from notifications regarding the specified topic.

Syntax:

nsresult RemoveObserver(nsIObserver *anObserver, const char *aTopic) 

Parameters:

anObserver: The interface pointer to the object which should stop receiving notifications.
aTopic: The notification topic or subject.

Result:

NS_OK if successful.

Example:

nsCOMPtr<nsIObserverService> observerService(
   do_GetService(/"@mozilla.org/observer-service;1"/, &rv)); 
if (NS_SUCCEEDED(rv))  
  rv = observerService->RemoveObserver(
    this, 
    NS_XPCOM_SHUTDOWN_OBSERVER_ID); 
 

NotifyObservers

Notifies all registered listeners of the given topic.

Syntax:

nsresult NotifyObservers(nsISupports *aSubject, const char *aTopic, const PRUnichar *someData) 

Parameters:

aSubject: Notification specific interface pointer.
aTopic: The notification topic or subject.
someData: Notification specific wide string.

Result:

NS_OK if successful.

Example:

 
nsCOMPtr<nsIServiceManager> mgr; 
NS_GetServiceManager(getter_AddRefs(mgr)); 
 
if (!mgr) 
    return NS_ERROR_FAILURE; 
 
nsCOMPtr<nsIObserverService> observerService; 
rv = mgr->GetServiceByContractID("@mozilla.org/observer-service;1",  
                                 NS_GET_IID(nsIObserverService),  
                                 getter_AddRefs(observerService)); 
 
if (!observerService) 
    return NS_ERROR_FAILURE; 
 
char* string = "My Topic"; 
PRUnichar* wstring = nsnull; 
nsISupports* context; 
 
observerService->NotifyObservers( context, string, wstring ); 
 

EnumerateObservers

Returns an enumeration of all registered listeners.

See also: nsISimpleEnumerator.

Syntax:

nsresult EnumerateObservers(const char *aTopic, nsISimpleEnumerator **_retval) 

Parameters:

aTopic: The notification topic or subject.

Result:

NS_OK if successful.

Example

nsCOMPtr<nsIServiceManager> mgr; 
NS_GetServiceManager(getter_AddRefs(mgr)); 
if (!mgr) 
    return NS_ERROR_FAILURE; 
 
nsCOMPtr<nsIObserverService> observerService; 
mgr->GetServiceByContractID("@mozilla.org/observer-service;1",  
                            NS_GET_IID(nsIObserverService),  
                            getter_AddRefs(observerService)); 
 
if (!observerService) 
    return NS_ERROR_FAILURE; 
 
nsCOMPtr<nsISimpleEnumerator> theEnum; 
rv = observerService->EnumerateObservers( <sometopic>, 
                                         getter_AddRefs(theEnum)); 
if (theEnum)  
{ 
    PRBool loop = PR_TRUE 
    while (NS_SUCCEEDED(theEnum->HasMoreElements(&loop)) && loop)  
    { 
        nsCOMPtr<nsISupports> inst; 
        theEnum->GetNext(getter_AddRefs(inst)); 
 
        if (inst) { do something useful } 
    } 
} 
 

nsIProperties

This interface is .

See "The Directory Service" on page 112 for both an implementation of this interface and a client usage example.

Methods:

Get

Gets a property with a given name.

Syntax:

nsresult Get(const char *prop, const nsIID & iid, void * *result) 

Parameters:

prop: A property name string key.
iid: The IID to QueryInterface any result of the Get.
result: [out] The property with the given name, if any.

Result:

NS_OK if successful.
NS_ERROR_FAILURE if a property with that name doesn't exist.
NS_ERROR_NO_INTERFACE if a property with that name doesn't exist.

Set

Sets a property with a given name to a given value.

Syntax:

nsresult Set(const char *prop, nsISupports *result) 

Parameters:

prop: A property name string key.
result: The property with the given name.

Result:

NS_OK if successful.

Has

Returns true if the property with the given name exists.

Syntax:

nsresult Has(const char *prop, PRBool *_retval) 

Parameters:

prop: A property name string key.
_retval: True if the propery exists with the given string key.

Result:

NS_OK if successful.

Undefine

Undefines a property.

Syntax:

nsresult Undefine(const char *prop) 

Parameters:

prop: A property name string key.

Result:

NS_OK if successful.
NS_ERROR_FAILURE if a property with that name doesn't exist.

GetKeys

Returns an array of the keys.

Syntax:

nsresult GetKeys(PRUint32 *count, char ***keys) 

Parameters:

count: If successful, count will contain the number of keys.
keys: An array of all keys in know by the object implementing the nsIProperties interface.

Result:

NS_OK if successful.
NS_ERROR_FAILURE if a property with that name doesn't exist.

nsISimpleEnumerator

This interface is used to enumerate over elements defined by its implementor. Although hasMoreElements() can be called independently of getNext(), getNext() must be preceded by a call to hasMoreElements(). There is no way to "reset" an enumerator, once you obtain one.

The nsISimpleEnumerator interface is shown in the section "The Web Locking Interface" on page 105.

Methods:

HasMoreElements

Determines whether or not the enumerator has any elements that can be returned via getNext(). This method is generally used to determine whether or not to initiate or continue iteration over the enumerator, though it can be called without subsequent getNext() calls. This does not affect internal state of enumerator.

Syntax:

nsresult HasMoreElements(PRBool *_retval) 

Parameters:

None.

Result:

PR_TRUE if there are remaining elements in the enumerator.
PR_FALSE if there are no more elements in the enumerator.

GetNext

Called to retrieve the next element in the enumerator. The "next" element is the first element upon the first call. Must be preceded by a call to hasMoreElements() which returns PR_TRUE. This method is generally called within a loop to iterate over the elements in the enumerator.

Syntax:

nsresult GetNext(nsISupports **_retval) 

Parameters:

None.

Result:

NS_OK if the call succeeded in returning a non-null value.
NS_ERROR_FAILURE if there are no more elements to enumerate.

nsISupportsPrimitives

This group of interfaces provide ways to wrap primiatives such as integers, floats, doubles, chars, strings, etc. so that these values may be passed between interface boundries using a nsISupports parameter. The base class of these primitive wrappers is the nsISupportsPrimitive.

These objects can be constructed by calling the Component Manager with the appropriate Class ID or Contract ID listed in nsXPCOMCID.h.

Also see "SetSites" on page 124, where we create and use an nsISupportsCString object.

GetType

Determines what kind of primative the nsISupportsPrimimitive subclass supports..

Syntax:

nsresult GetType(PRUint16 *aType) 

Parameters:

aType: [out] The type of the primative. This value will be one of the following constants:
TYPE_ID
TYPE_CSTRING
TYPE_STRING
TYPE_PRBOOL
TYPE_PRUINT8
TYPE_PRUINT16
TYPE_PRUINT32
TYPE_PRUINT64
TYPE_PRTIME
TYPE_CHAR
TYPE_PRINT16
TYPE_PRINT32
TYPE_PRINT64
TYPE_FLOAT
TYPE_DOUBLE
TYPE_INTERFACE_POINTER
TYPE_VOID

These first three are pointer types and do data copying using the nsIMemory.

The derived classes implement a getter and setter for its data type and a ToString method that returns a nsIMemory allocated string representative of the data. These interfaces are:

nsISupportsID
nsISupportsString
nsISupportsCString
nsISupportsPRBool
nsISupportsPRUint8
nsISupportsPRUint16
nsISupportsPRUint32
nsISupportsPRUint64
nsISupportsPRTime
nsISupportsChar
nsISupportsPRInt16
nsISupportsPRInt32
nsISupportsPRInt64
nsISupportsFloat
nsISupportsDouble
nsISupportsVoid
nsISupportsInterfacePointer

XPCOM I/O

These interfaces provide access to various XPCOM I/O related services.

Included Interfaces:

nsIDirectoryServiceProvider

This interface is used by Directory Service to get file locations.

Methods:

GetFile

Provides DirectoryService with a prop on the first request or on every request if the prop is not persistent.

Syntax:

nsresult GetFile(const char *prop, PRBool *persistent, nsIFile **_retval) 

Parameters:

prop: The symbolic name of the file.
persistent: [out] If true, the returned file will be cached by Directory Service. Subsequent requests for this prop will bypass the provider and use the cache. If false, the provider will be asked for this prop each time it is requested.

Returns:

The file represented by the property.

Example:
nsCOMPtr<nsIProperties> dirService; 
rv = servMgr->GetServiceByContractID(
  NS_DIRECTORY_SERVICE_CONTRACTID,  
  NS_GET_IID(nsIProperties),  
  getter_AddRefs(dirService)); 
 
if (NS_FAILED(rv)) 
        return rv; 
 
nsCOMPtr<nsIFile> xpcomDll; 
rv = dirService->Get(
  NS_XPCOM_LIBRARY_FILE, NS_GET_IID(nsIFile),   getter_AddRefs(xpcomDll)); 
 
if (NS_FAILED(rv)) 
        return rv; 

nsIDirectoryServiceProvider2

This interface is an extension of nsIDirectoryServiceProvider which allows multiple files to be returned for a given key.

Methods:

GetFiles

Provides Directory Service with a prop when it gets a request for it and the requested type is nsISimpleEnumerator.

Syntax:

nsresult GetFiles(const char *prop, nsISimpleEnumerator **_retval) 

Parameters:

prop: The symbolic name of the file list.

Returns:

An enumerator for a list of file locations. The elements in the enumeration are of the type nsIFile.

nsIDirectoryService

This interface provides XPCOM's directory service.

Methods:

Init

Must be called. This function is used internally by XPCOM initialization and developers are not required nor expected to call this method.

Syntax:

nsresult Init(void) 

Parameters:

None.

Result:

NS_OK if successful.

RegisterProvider

Registers a provider with the service.

Syntax:

nsresult RegisterProvider(nsIDirectoryServiceProvider *prov) 

Parameters:

prov: The provider to be registered. The service will keep a strong reference to this object. It will be released when the service is released.

Result:

NS_OK if successful.

UnregisterProvider

Unregisters a provider with the service.

Syntax:

nsresult UnregisterProvider(nsIDirectoryServiceProvider *prov) 

Parameters:

prov: The provider to be unregistered.

Result:

NS_OK if successful.

nsIFile

There are many built in location which are known to XPCOM and are accessible from the nsIDirectoryService. These values are defined in the nsDirectoryServiceDefs.h.

This interface is the only correct cross-platform way to specify a file. Strings are not such a way. Despite the fact that they work on Windows or Unix, they will not work here.

All methods with string parameters have two forms. The preferred form operates on UCS-2 encoded characters strings. An alternate form operates on characters strings encoded in the "native" charset. A string containing characters encoded in the native charset cannot be safely passed to javascript via xpconnect. Therefore, the UCS-2 forms are scriptable, but the "native methods" are not.

Methods:

Attributes and Constants:

Append

AppendNative

Makes a descendent of the current nsIFile.

Syntax:

nsresult Append(const nsAString & node) 
nsresult AppendNative(const nsACString & node) 
 

Parameters:

node: A string which is intended to be a child node of the nsIFile. For the appendNative method, the node must be in the native filesystem charset.

Result:

NS_OK if successful.

Normalize

Normalizes the pathName (e.g. removing .. and . components on Unix).

Syntax:

nsresult Normalize(void)  

Parameters:

None.

Result:

NS_OK if successful.

Create

Creates a new file or directory in the file system. Any nodes that have not been created or resolved, will be. If the file or directory already exists, create() returns NS_ERROR_FILE_ALREADY_EXISTS.

The type flag must be either NORMAL_FILE_TYPE or DIRECTORY_TYPE

Syntax:

nsresult Create(PRUint32 type, PRUint32 permissions)  

Parameters:

type: This specifies the type of file system object to be made. The only two types at this time are file and directory which are defined below. If the type is unrecognized, returns (NS_ERROR_FILE_UNKNOWN_TYPE).
permissions: Unix style octal permissions. This may be ignored on systems that do not need to do permissions.

Result:

NS_OK if successful.

CopyTo

CopyToNative

Copies this file to the specified newParentDir. If a newName is specified, the file will be renamed. If 'this' is not created, returns the error (NS_ERROR_FILE_TARGET_DOES_NOT_EXIST). copyTo may fail if the file already exists in the destination directory. copyTo will NOT resolve aliases/shortcuts during the copy.

Syntax:

nsresult CopyTo(nsIFile *newParentDir, const nsAString & newName) 
nsresult CopyToNative(nsIFile *newParentDir, const nsACString & newName) 

Parameters:

newParentDir: The destination directory. If the newParentDir is empty, copyTo() will use the parent directory of this file. If the newParentDir is not empty and is not a directory, an error will be returned (NS_ERROR_FILE_DESTINATION_NOT_DIR). For the CopyToNative method, the newName must be in the native filesystem charset.
newName: This param allows you to specify a new name for the file to be copied. This param may be empty, in which case the current leaf name will be used.

Result:

NS_OK if successful.

CopyToFollowingLinks

CopyToFollowingLinksNative

Is identical to copyTo except, as the name implies, it follows symbolic links. The XP_UNIX implementation always follows symbolic links when copying.

Syntax:

nsresult CopyToFollowingLinks(nsIFile *newParentDir, const nsAString & newName) 
  nsresult CopyToFollowingLinksNative(nsIFile *newParentDir, const nsACString & newName) 

Parameters:

newParentDir: The destination directory. If the newParentDir is empty, copyTo() will use the parent directory of this file. If the newParentDir is not empty and is not a directory, an error will be returned (NS_ERROR_FILE_DESTINATION_NOT_DIR).
newName: This param allows you to specify a new name for the file to be copied. This param may be empty, in which case the current leaf name will be used. For the copyToFollowingLinksNative method, the newName must be in the native filesystem charset.

Result:

NS_OK if successful.

MoveTo

MoveToNative

Moves this file to the specified newParentDir. If a newName is specified, the file will be renamed. If 'this' is not created, returns an error (NS_ERROR_FILE_TARGET_DOES_NOT_EXIST). moveTo will NOT resolve aliases/shortcuts during the copy. moveTo will do the right thing and allow copies across volumes.

Syntax:

nsresult MoveTo(nsIFile *newParentDir, const nsAString & newName) 
nsresult MoveToNative(nsIFile *newParentDir, const nsACString & newName) 

Parameters:

newParentDir: This param is the destination directory. If the newParentDir is empty, moveTo() will rename the file within its current directory. If the newParentDir is not empty and does not name a directory, an error will be returned (NS_ERROR_FILE_DESTINATION_NOT_DIR). For the moveToNative method, the newName must be in the native filesystem charset.
newName: This param allows you to specify a new name for the file to be moved. This param may be empty, in which case the current leaf name will be used.For the moveToNative method, the newName must be in the native filesystem charset.

Result:

NS_OK if successful.

Remove

Tries to delete this file. The 'recursive' flag must be PR_TRUE to delete directories which are not empty. It will not resolve any symlinks.

Syntax:

nsresult Remove(PRBool recursive) 

Parameters:

recursive: A boolean indicating whether or not to delete directories recursively.

Result:

NS_OK if successful.

Exists

Determines if this file exists.

Syntax:

nsresult Exists(PRBool *_retval) 

Parameters:

None.

Returns:

TRUE if it exists.
FALSE otherwise.

IsWritable

Determines if this file is writable.

Syntax:

nsresult IsWritable(PRBool *_retval)  

Parameters:

None.

Returns:

TRUE if it is writable.
FALSE otherwise.

IsReadable

Determines if this file is readable.

Syntax:

nsresult IsReadable(PRBool *_retval)  

Parameters:

None.

Returns:

TRUE if it is readable.
FALSE otherwise.

IsExecutable

Determines if this file is executable.

Syntax:

nsresult IsExecutable(PRBool *_retval)  

Parameters:

None.

Returns:

TRUE if it is executable.
FALSE otherwise.

IsHidden

Determines if this file is hidden.

Syntax:

nsresult IsHidden(PRBool *_retval)  

Parameters:

None.

Returns:

TRUE if it is hidden.
FALSE otherwise.

IsDirectory

Determines if this file is a directory.

Syntax:

nsresult IsDirectory(PRBool *_retval) 

Parameters:

None.

Returns:

TRUE if it is a directory.
FALSE otherwise.

IsFile

Determines if this file is a file.

Syntax:

nsresult IsFile(PRBool *_retval)  

Parameters:

None.

Returns:

TRUE if it is a file.
FALSE otherwise.

IsSymlink

Determines if this file is a symbolic link.

Syntax:

nsresult IsSymlink(PRBool *_retval)  

Parameters:

None.

Returns:

TRUE if it is a symlink.
FALSE otherwise.

IsSpecial

Determines if this file is other than a regular file, a directory, or a symbolic link.

Syntax:

nsresult IsSpecial(PRBool *_retval)  

Parameters:

None.

Returns:

TRUE if it is not a file, a directory, or a symlink.
FALSE otherwise.

CreateUnique

Create a new file or directory in the file system. Any nodes that have not been created or resolved, will be. If this file already exists, this tries variations on the leaf name "suggestedName" until it finds one that does not already exist. If the search for nonexistent files takes too long (thousands of the variants already exist), it gives up and return NS_ERROR_FILE_TOO_BIG.

The type flag must be either NORMAL_FILE_TYPE or DIRECTORY_TYPE

Syntax:

nsresult CreateUnique(PRUint32 type, PRUint32 permissions) 

Parameters:

type: The type of file system object to be made. The only two types at this time are file and directory which are defined below. If the type is unrecongnized, returns an error (NS_ERROR_FILE_UNKNOWN_TYPE).
permissions: Unix style octal permissions. This may be ignored on systems that do not need to do permissions.

Result:

NS_OK if successful.

Clone

Allocates and initializes an nsIFile object to the exact location of this nsIFile

Syntax:

nsresult Clone(nsIFile **_retval) 

Parameters:

None.

Returns:

An nsIFile with which this object will be initialized.

Equals

Determines if inFile equals this.

Syntax:

Equals(nsIFile *inFile, PRBool *_retval)  

Parameters:

inFile: The comparison object.

Returns:

TRUE if the files are equal.
FALSE otherwise.

Contains

Determines if inFile is a descendant of this file. If recur is true, it will also look in subdirectories.

Syntax:

nsresult Contains(nsIFile *inFile, PRBool recur, PRBool *_retval) 

Parameters:

inFile: The file to be evaluated.
recur: A boolean indicating whether subdirectories should be searched.

Returns:

TRUE if infile is a descendent of this file.
FALSE otherwise.

LeafName

Getters and setters for the leaf name of the file itself. nativeLeafName must be in the native filesystem charset.

nsresult GetLeafName(nsAString & aLeafName) 
nsresult SetLeafName(const nsAString & aLeafName) 
nsresult GetNativeLeafName(nsACString & aNativeLeafName) 
nsresult SetNativeLeafName(const nsACString & aNativeLeafName) 

Permissions

Getters and setters for the permssion of the file or link.
nsresult GetPermissions(PRUint32 *aPermissions) 
nsresult SetPermissions(PRUint32 aPermissions) 
nsresult GetPermissionsOfLink(PRUint32 *aPermissionsOfLink) 
nsresult SetPermissionsOfLink(PRUint32 aPermissionsOfLink) 

LastModificationTime

Gets and sets time of the last file modification. Times are stored as milliseconds from midnight (00:00:00), January 1, 1970 Greenwich Mean Time (GMT).
Syntax
nsresult GetLastModifiedTime(PRInt64 *aLastModifiedTime) 
nsresult SetLastModifiedTime(PRInt64 aLastModifiedTime) 
nsresult GetLastModifiedTimeOfLink(PRInt64 *aLastModifiedTimeOfLink) 
nsresult SetLastModifiedTimeOfLink(PRInt64 aLastModifiedTimeOfLink) 

FileSize

Getters and setters for the file size.

Warning: On the Mac, getting/setting the file size with nsIFile only deals with the size of the data fork. If you need to know the size of the combined data and resource forks use the GetFileSizeWithResFork() method defined on nsILocalFileMac.

Syntax
nsresult GetFileSize(PRInt64 *aFileSize) 
nsresult SetFileSize(PRInt64 aFileSize) 
nsresult GetFileSizeOfLink(PRInt64 *aFileSizeOfLink) 

Target

Gets the target, ie, what the symlink points at. Gives an error (NS_ERROR_FILE_INVALID_PATH) if not a symlink. Note that the ACString attribute is returned in the native filesystem charset.

Warning:The native version of these strings are not guaranteed to be a usable path to pass to NSPR or the C stdlib. There are problems that affect platforms on which a path does not fully specify a file because two volumes can have the same name (e.g., XP_MAC). This is solved by holding "private", native data in the nsIFile implementation. This native data is lost when you convert to a string.

Note: NOT USE TO PASS TO NSPR OR STDLIB!

Syntax

nsresult GetTarget(nsAString & aTarget) 
nsresult GetNativeTarget(nsACString & aNativeTarget) 

Parent

Gets the parent of this file. Parent will be null when this file is at the top of the volume.

Syntax
nsresult GetParent(nsIFile * *aParent);  

DirectoryEntries

Gets an enumeration of the elements in a directory. Each element in the enumerator is an nsIFile. If the current nsIFile does not specify a dirctory, returns an error NS_ERROR_FILE_NOT_DIRECTORY.

Syntax
nsresult GetDirectoryEntries(nsISimpleEnumerator * *aDirectoryEntries) 

Example
PRBool RecursiveDirectories(nsIFile* file) 
{ 
    nsresult rv; 
    nsCOMPtr<nsISimpleEnumerator> entries; 
    rv = file->GetDirectoryEntries(getter_AddRefs(entries)); 
    if(NS_FAILED(rv) || !entries) 
        return PR_FALSE; 
     
    PRUint32 count = 0; 
    PRBool hasMore; 
    while(NS_SUCCEEDED(entries->HasMoreElements(&hasMore)) && hasMore) 
    { 
        nsCOMPtr<nsISupports> sup; 
        entries->GetNext(getter_AddRefs(sup)); 
        if(!sup) 
            return PR_FALSE; 
         
        nsCOMPtr<nsIFile> file = do_QueryInterface(sup); 
        if(!file) 
            return PR_FALSE; 
     
        nsEmbedCString name; 
        if(NS_FAILED(file->GetNativeLeafName(name))) 
            return PR_FALSE; 
         
        PRBool isDir; 
        printf("%s\n", name.get()); 
        rv = file->IsDirectory(&isDir); 
        if (NS_FAILED(rv)) 
        {        
            printf("IsDirectory Failed!!!\n"); 
            return PR_FALSE; 
        } 
         
        if (isDir == PR_TRUE) 
        { 
           RecursiveDirectories(file);    
        }         
    } 
    return PR_TRUE; 
} 
 

nsIInputStream

This interface manages reading data in from an input stream. It is partially scriptable.

Methods:

close

Closes the stream.

Syntax:

nsresult Close(void) 

Parameters:

None.

Result:

NS_OK if successful.

Available

Gets number of bytes currently available in the stream.

Syntax:

nsresult Available(PRUint32 *_retval) 

Parameters:

None.

Returns:

The number of bytes.

Read

Reads data from the stream.

Syntax:

nsresult Read(char * aBuf, PRUint32 aCount, PRUint32 *_retval) 

Parameters:

aBuf: The buffer into which the data is to be read.
aCount: The maximum number of bytes to be read.

Returns:

The number of bytes read. Returns 0 if end of file has been reached.
Throws NS_BASE_STREAM_WOULD_BLOCK if reading from the input stream would block the calling thread (non-blocking mode only).
Throws <other-error> on failure.

ReadSegments

Low-level read method that has access to the stream's underlying buffer. The writer function may be called multiple times for segmented buffers.

Syntax:

nsresult ReadSegments(nsWriteSegmentFun aWriter, void * aClosure, PRUint32 aCount, PRUint32 *_retval) 

Parameters:

aWriter: The "consumer" of the data to be read. The type is described below.
aClosure: Opaque parameter passed to writer.
aCount: The maximum number of bytes to be read.
typedef NS_CALLBACK(nsWriteSegmentFun)(nsIInputStream *aInStream, void *aClosure, const char *aFromSegment, PRUint32 aToOffset, PRUint32 aCount, PRUint32 *aWriteCount); 

aInStream: The stream being read.

aClosure: Opaque parameter passed to ReadSegments.

aFromSegment: A pointer to memory owned by the input stream.

aToOffset: The amount already read (since ReadSegments was called).

aCount: The length of fromSegment.

aWriteCount: The number of bytes read.

Note: Implementers should return the following: NS_OK and (*aWriteCount > 0) if consumed some data; NS_BASE_STREAM_WOULD_BLOCK if not interested in consuming any data; <other-error> on failure. Errors are passed to the caller of ReadSegments, unless aToOffset is greater than zero.

Returning NS_OK and (*aWriteCount = 0) has undefined behavior.

Returns:

The number of bytes read. Returns 0 if end of file has been reached.
Throws NS_BASE_STREAM_WOULD_BLOCK if reading from the input stream would block the calling thread (non-blocking mode only).
Throws <other-error> on failure.

Note: This method may be unimplemented if a stream has no underlying buffer (e.g., socket input stream).

IsNonBlocking

Returns TRUE if stream is non-blocking.

Syntax:

nsresult IsNonBlocking(PRBool *_retval) 

Parameters:

None.

Returns:

TRUE if stream is non-blocking.
FALSE otherwise.

nsILocalFile

This interface adds methods to nsIFile that are particular to a file that is accessible via the local file system. It follows the same string conventions as nsIFile.

Methods:

InitWithPath

InitWithNativePath

Initializes the nsILocalFile object. Any internal state information will be reset.

Note: This function has a known bug on the macintosh and other operating systems which do not represent file locations as paths. If you do use this function, be very aware of this problem.

Syntax:

nsresult InitWithPath(const nsAString & filePath) 
nsresult InitWithNativePath(const nsACString & filePath) 

Parameters:

filePath: A string which specifies a full file path to a location. Relative paths will be treated as an error (NS_ERROR_FILE_UNRECOGNIZED_PATH). For InitWithNativePath, filePath must be in the native filesystem charset.

Result:

NS_OK if successful.

InitWithFile

Initializes this object with another file.

Syntax:

nsresult InitWithFile(nsILocalFile *aFile) 

Parameters:

aFile: The file to which this becomes equivalent.

Result:

NS_OK if successful.

OpenNSPRFileDesc

Opens the NSPR file descriptor.

Syntax:

nsresult OpenNSPRFileDesc(PRInt32 flags, PRInt32 mode, PRFileDesc * *_retval)  

Parameters:

flags: The appropriate flags.
mode: The appropriate mode.

Returns:

A pointer to the descriptor.

See NSPR's documentation regarding PRFileDesc at http://www.mozilla.org/projects/nspr.

OpenANSIFileDesc

Opens the ANSI file descriptor.

Syntax:

nsresult OpenANSIFileDesc(const char *mode, FILE * *_retval) 

Parameters:

mode: The appropriate mode.

Returns:

A pointer to the file.

Load

Loads this file (a library).

Syntax:

nsresult Load(PRLibrary * *_retval) 

Parameters:

None.

Returns:

A pointer to the library.

See NSPR's documentation regarding PRLibrary at http://www/mozilla.org/projects/nspr.

appendRelativePath

appendRelativeNativePath

Appends a relative path to the current path of the nsILocalFile object.

Syntax:

nsresult AppendRelativePath(const nsAString & relativeFilePath) 
nsresult AppendRelativeNativePath(const nsACString & relativeFilePath) 

Parameters:

relativeFilePath: The relativeFilePath. It is a native relative path. For security reasons, it cannot contain .. or start with a directory separator. For the appendRelativeNativePath method, the relativeFilePath must be in the native filesystem charset.

Result:

NS_OK if successful.

Reveal

Asks the operating system to open the folder which contains this file or folder. This routine only works on platforms which support the ability to open a folder.

Syntax:

nsresult Reveal(void) 

Parameters:

None.

Result:

NS_OK if successful.

Launch

Asks the operating system to attempt to open the file. This really just simulates "double clicking" the file on your platform and thus only works on platforms which support this functionality.

Syntax:

nsresult Launch(void) 

Parameters:

None.

Result:

NS_OK if successful.

GetRelativeDescriptor

Gets a relative file path in an opaque, XP format. It is therefore not a native path.

Note: The character set of the string returned from this function is undefined.

DO NOT TRY TO INTERPRET IT AS HUMAN READABLE TEXT!

Syntax:

nsresult GetPersistentDescriptor(nsACString & aPersistentDescriptor) 

Parameters:

fromFile: The file from which the descriptor is relative.

Returns:

The descriptor.

SetRelativeDescriptor

Initializes the file to the location relative to fromFile using a string returned by getRelativeDescriptor.

Syntax:

nsresult SetPersistentDescriptor(const nsACString & aPersistentDescriptor) 

Parameters:

fromFile: The file to which the descriptor is relative.
relativeDesc: The relative descriptor obtained from getRelativeDescriptor.

Result:

NS_OK if successful.

FollowingLinks

Getter and Setter for FollowingLinks attribute. Gets and sets whether the nsLocalFile will auto resolve symbolic links. By default, this value will be false on all non unix systems. On Unix, this attribute is effectively a no-op.

Be aware that changing this attribute from true to false after the nsILocalFile has been initialized may lead to errors. This could happen if there were resolved symlink in the initialized path. For example if you had /a/b/c where |b| was a symlink, and you change this attribute to false, the next usage would mostlikely fail.

Syntax:

nsresult GetFollowLinks(PRBool *aFollowLinks) 
nsresult SetFollowLinks(PRBool aFollowLinks) 

Result:

NS_OK if successful.

GetDiskSpaceAvailable

Return the available disk space on the volume or drive reference by the nsILocalFile.

Syntax:

nsresult GetDiskSpaceAvailable(PRInt64 *aDiskSpaceAvailable) 

Result:

NS_OK if successful.

nsIOutputStream

This interface manages writing data to an output stream. It is partially scriptable.

Methods:

Close

Closes the stream. Forces the output stream to flush any buffered data.

Syntax:

nsresult Close(void) 

Parameters:

None.

Result:

NS_OK if successful.
Throws NS_BASE_STREAM_WOULD_BLOCK if unable to flush without blocking the calling thread (non-blocking mode only)

Flush

Flushes the stream.

Syntax:

nsresult Flush(void) 

Parameters:

None.

Result:

NS_OK if successful.
Throws NS_BASE_STREAM_WOULD_BLOCK if unable to flush without blocking the calling thread (non-blocking mode only).

Write

Writes data into the stream from an input stream.

Syntax:

nsresult Write(const char *aBuf, PRUint32 aCount, PRUint32 *_retval) 

Parameters:

aBuf: The buffer containing the data to be written.
aCount: The maximum number of bytes to be written.

Returns:

The number of bytes written.
Throws NS_BASE_STREAM_WOULD_BLOCK if unable to flush without blocking the calling thread (non-blocking mode only)
Throws <other-error> on failure.

WriteFrom

Writes data into the stream from an input stream.

Syntax:

nsresult WriteSegments(nsReadSegmentFun aReader, void * aClosure, PRUint32 aCount, PRUint32 *_retval) 

Parameters:

aFromStream:The stream containing the data to be written.
aCount: The maximum number of bytes to be written.

Returns:

The number of bytes written.
Throws NS_BASE_STREAM_WOULD_BLOCK if unable to flush without blocking the calling thread (non-blocking mode only)
Throws <other-error> on failure

Note: This method is defined by this interface in order to allow the output stream to efficiently copy the data from the input stream into its internal buffer (if any). If this method was provided as an external facility, a separate char* buffer would need to be used in order to call the output stream's other Write method.

WriteSegments

Low-level write method that has access to the stream's underlying buffer. The reader function may be called multiple times for segmented buffers.

Syntax:

nsresult WriteSegments(nsReadSegmentFun aReader, void * aClosure, PRUint32 aCount, PRUint32 *_retval) 

Parameters:

aReader: The "provider" of the data to be written. The type is described below.
aClosure: Opaque parameter passed to reader.
aCount: The maximum number of bytes to be written.
typedef NS_CALLBACK(nsReadSegmentFun)(nsIOutputStream *aOutStream, void *aClosure, char *aToSegment, PRUint32 aFromOffset, PRUint32 aCount, PRUint32 *aReadCount) 

aOutStream: The stream being written to.

aClosure: Opaque parameter passed to WriteSegments.

aToSegment: A pointer to memory owned by the output stream.

aFromOffset: The amount already written (since WriteSegments was called).

aCount: The length of toSegment.

aReadCount: The number of bytes written.

Note: Implementers should return the following: NS_OK and (*aReadCount > 0) if successfully provided some data; NS_OK and (*aReadCount = 0); or NS_BASE_STREAM_WOULD_BLOCK if not interested in providing any data;<other-error> on failure

Errors are passed to the caller of WriteSegments, unless aFromOffset is greater than zero.

Returns:

The number of bytes written.
Throws NS_BASE_STREAM_WOULD_BLOCK if writing to the output stream would block the calling thread (non-blocking mode only).
Throws <other-error> on failure.

Note: this function may be unimplemented if a stream has no underlying buffer (e.g., socket output stream).

IsNonBlocking

Returns TRUE if stream is non-blocking.

Syntax:

nsresult IsNonBlocking(PRBool *_retval) 

Parameters:

None.

Returns:

TRUE if stream is non-blocking.
FALSE otherwise.

XPCOM Startup/Shutdown

These C++ functions serve to initialize and terminate XPCOM. (In an embedding situation, this is usually taken care of by embedding initialization.) Also included are a number of global functions that provide access to the main XPCOM components.

Note: These are C++ functions only, and are therefore not scriptable.

NS_InitXPCOM2

Initializes XPCOM. This function must be called by the application before using XPCOM. Components should not call this function. The one exception is that you may call NS_NewLocalFile to create an nsIFile object to supply as the bin directory path in this call.

Syntax:

nsresult NS_InitXPCOM2(nsIServiceManager** result,nsIFile* binDirectory,nsIDirectoryServiceProvider* appFileLocationProvider) 

Parameters:

result: The service manager. You may pass null.
binDirectory: The directory containing the component registry and runtime libraries. You can use nsnull to use the working directory.
appFileLocProvider: The object to be used by Gecko that specifies to Gecko where to find profiles, the component registry preferences and so on. You can use nsnull for the default behaviour.

nsresult

NS_OK if successful.
Other error codes indicate failure during initialization.

See also: see NS_NewLocalFile, nsILocalFile, and nsIDirectoryServiceProvider.

NS_ShutdownXPCOM

Shuts down XPCOM. This function must be called by the application when you are finished using XPCOM.

Syntax:

nsresult NS_ShutdownXPCOM(nsIServiceManager* servMgr) 

Parameters:

servMgr: The service manager which was returned by NS_InitXPCOM2. This will release the service manager. You may pass null.

Result:

NS_OK if successful.
Other error codes indicate failure.

NS_GetServiceManager

Accesses the Service Manager.

Syntax:

nsresult NS_GetServiceManager(nsIServiceManager** result) 

Parameters:

result: An interface pointer to the service manager.

Result:

NS_OK if successful.

NS_GetComponentManager

Accesses the Component Manager.

Syntax:

NS_COM nsresult NS_GetComponentManager(nsIComponentManager** result) 

Parameters:

result: An interface pointer to the component manager.

Result:

NS_OK if successful.

NS_GetComponentRegistrar

Accesses the Component Registration Manager.

Syntax:

NS_COM nsresult NS_GetComponentRegistrar(nsIComponentRegistrar** result)  

Parameters:

result: An interface pointer to the component registration manager.

Result:

NS_OK if successful.

NS_GetMemoryManager

Accesses the memory manager.

Syntax:

NS_COM nsresult NS_GetMemoryManager(nsIMemory** result) 

Parameters:

result: An interface pointer to the memory manager

Result:

NS_OK if successful.

NS_NewLocalFile

NS_NewNativeLocalFile

Creates a new instanstance of an object implementating the nsIFile and nsILocalFile interfaces. (On the Macintosh platform, this object also implments the nsILocalFileMac interface). If using the native form of this call, path must be in the native filesystem charset.

Syntax:

nsresult 
NS_NewLocalFile(const nsAString &path,  
                PRBool followLinks,  
                nsILocalFile* *result); 
nsresult 
NS_NewNativeLocalFile(const nsACString &path,  
                      PRBool followLinks,  
                      nsILocalFile* *result); 

Parameters:

path: A string which specifies a full file path to a location. Relative paths will be treated as an error (NS_ERROR_FILE_UNRECOGNIZED_PATH). For initWithNativePath, the filePath must be in the native filesystem charset.
followLinks: Sets whether the nsLocalFile will auto resolve symbolic links. On Unix, this parameter is ignored
result: [out] An interface pointer to the new nsILocalFile.

Result:

NS_OK if successful.

Copyright (c) 2003 by Doug Turner and Ian Oeschger. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.02 or later. Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder. Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.
TOC PREV NEXT INDEX