Back to index

lightning-sunbird  0.9+nobinonly
nsConsoleService.cpp
Go to the documentation of this file.
00001 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
00002 /* ***** BEGIN LICENSE BLOCK *****
00003  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00004  *
00005  * The contents of this file are subject to the Mozilla Public License Version
00006  * 1.1 (the "License"); you may not use this file except in compliance with
00007  * the License. You may obtain a copy of the License at
00008  * http://www.mozilla.org/MPL/
00009  *
00010  * Software distributed under the License is distributed on an "AS IS" basis,
00011  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00012  * for the specific language governing rights and limitations under the
00013  * License.
00014  *
00015  * The Original Code is mozilla.org code.
00016  *
00017  * The Initial Developer of the Original Code is
00018  * Netscape Communications Corporation.
00019  * Portions created by the Initial Developer are Copyright (C) 1998
00020  * the Initial Developer. All Rights Reserved.
00021  *
00022  * Contributor(s):
00023  *   Simon B├╝nzli <zeniko@gmail.com>
00024  *
00025  * Alternatively, the contents of this file may be used under the terms of
00026  * either of the GNU General Public License Version 2 or later (the "GPL"),
00027  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00028  * in which case the provisions of the GPL or the LGPL are applicable instead
00029  * of those above. If you wish to allow use of your version of this file only
00030  * under the terms of either the GPL or the LGPL, and not to allow others to
00031  * use your version of this file under the terms of the MPL, indicate your
00032  * decision by deleting the provisions above and replace them with the notice
00033  * and other provisions required by the GPL or the LGPL. If you do not delete
00034  * the provisions above, a recipient may use your version of this file under
00035  * the terms of any one of the MPL, the GPL or the LGPL.
00036  *
00037  * ***** END LICENSE BLOCK ***** */
00038 
00039 /*
00040  * Maintains a circular buffer of recent messages, and notifies
00041  * listeners when new messages are logged.
00042  */
00043 
00044 /* Threadsafe. */
00045 
00046 #include "nsMemory.h"
00047 #include "nsIServiceManager.h"
00048 #include "nsIProxyObjectManager.h"
00049 #include "nsSupportsArray.h"
00050 
00051 #include "nsConsoleService.h"
00052 #include "nsConsoleMessage.h"
00053 
00054 NS_IMPL_THREADSAFE_ADDREF(nsConsoleService)
00055 NS_IMPL_THREADSAFE_RELEASE(nsConsoleService)
00056 NS_IMPL_QUERY_INTERFACE2_CI(nsConsoleService,
00057                             nsIConsoleService,
00058                             nsIConsoleService_MOZILLA_1_8_BRANCH)
00059 NS_IMPL_CI_INTERFACE_GETTER2(nsConsoleService,
00060                              nsIConsoleService,
00061                              nsIConsoleService_MOZILLA_1_8_BRANCH)
00062 
00063 nsConsoleService::nsConsoleService()
00064     : mMessages(nsnull), mCurrent(0), mFull(PR_FALSE), mListening(PR_FALSE), mLock(nsnull)
00065 {
00066     // XXX grab this from a pref!
00067     // hm, but worry about circularity, bc we want to be able to report
00068     // prefs errs...
00069     mBufferSize = 250;
00070 }
00071 
00072 nsConsoleService::~nsConsoleService()
00073 {
00074     PRUint32 i = 0;
00075     while (i < mBufferSize && mMessages[i] != nsnull) {
00076         NS_RELEASE(mMessages[i]);
00077         i++;
00078     }
00079 
00080 #ifdef DEBUG_mccabe
00081     if (mListeners.Count() != 0) {
00082         fprintf(stderr, 
00083             "WARNING - %d console error listeners still registered!\n"
00084             "More calls to nsIConsoleService::UnregisterListener needed.\n",
00085             mListeners.Count());
00086     }
00087     
00088 #endif
00089 
00090     if (mMessages)
00091         nsMemory::Free(mMessages);
00092     if (mLock)
00093         PR_DestroyLock(mLock);
00094 }
00095 
00096 nsresult
00097 nsConsoleService::Init()
00098 {
00099     mMessages = (nsIConsoleMessage **)
00100         nsMemory::Alloc(mBufferSize * sizeof(nsIConsoleMessage *));
00101     if (!mMessages)
00102         return NS_ERROR_OUT_OF_MEMORY;
00103 
00104     // Array elements should be 0 initially for circular buffer algorithm.
00105     memset(mMessages, 0, mBufferSize * sizeof(nsIConsoleMessage *));
00106 
00107     mLock = PR_NewLock();
00108     if (!mLock)
00109         return NS_ERROR_OUT_OF_MEMORY;
00110 
00111     return NS_OK;
00112 }
00113 
00114 static PRBool PR_CALLBACK snapshot_enum_func(nsHashKey *key, void *data, void* closure)
00115 {
00116     nsISupportsArray *array = (nsISupportsArray *)closure;
00117 
00118     // Copy each element into the temporary nsSupportsArray...
00119     array->AppendElement((nsISupports*)data);
00120     return PR_TRUE;
00121 }
00122 
00123 // nsIConsoleService methods
00124 NS_IMETHODIMP
00125 nsConsoleService::LogMessage(nsIConsoleMessage *message)
00126 {
00127     if (message == nsnull)
00128         return NS_ERROR_INVALID_ARG;
00129 
00130     nsSupportsArray listenersSnapshot;
00131     nsIConsoleMessage *retiredMessage;
00132 
00133     NS_ADDREF(message); // early, in case it's same as replaced below.
00134 
00135     /*
00136      * Lock while updating buffer, and while taking snapshot of
00137      * listeners array.
00138      */
00139     {
00140         nsAutoLock lock(mLock);
00141 
00142         /*
00143          * If there's already a message in the slot we're about to replace,
00144          * we've wrapped around, and we need to release the old message.  We
00145          * save a pointer to it, so we can release below outside the lock.
00146          */
00147         retiredMessage = mMessages[mCurrent];
00148         
00149         mMessages[mCurrent++] = message;
00150         if (mCurrent == mBufferSize) {
00151             mCurrent = 0; // wrap around.
00152             mFull = PR_TRUE;
00153         }
00154 
00155         /*
00156          * Copy the listeners into the snapshot array - in case a listener
00157          * is removed during an Observe(...) notification...
00158          */
00159         mListeners.Enumerate(snapshot_enum_func, &listenersSnapshot);
00160     }
00161     if (retiredMessage != nsnull)
00162         NS_RELEASE(retiredMessage);
00163 
00164     /*
00165      * Iterate through any registered listeners and tell them about
00166      * the message.  We use the mListening flag to guard against
00167      * recursive message logs.  This could sometimes result in
00168      * listeners being skipped because of activity on other threads,
00169      * when we only care about the recursive case.
00170      */
00171     nsCOMPtr<nsIConsoleListener> listener;
00172     nsresult rv;
00173     nsresult returned_rv;
00174     PRUint32 snapshotCount;
00175     rv = listenersSnapshot.Count(&snapshotCount);
00176     if (NS_FAILED(rv))
00177         return rv;
00178 
00179     {
00180         nsAutoLock lock(mLock);
00181         if (mListening)
00182             return NS_OK;
00183         mListening = PR_TRUE;
00184     }
00185 
00186     returned_rv = NS_OK;
00187     for (PRUint32 i = 0; i < snapshotCount; i++) {
00188         rv = listenersSnapshot.GetElementAt(i, getter_AddRefs(listener));
00189         if (NS_FAILED(rv)) {
00190             returned_rv = rv;
00191             break; // fall thru to mListening restore code below.
00192         }
00193         listener->Observe(message);
00194     }
00195     
00196     {
00197         nsAutoLock lock(mLock);
00198         mListening = PR_FALSE;
00199     }
00200 
00201     return returned_rv;
00202 }
00203 
00204 NS_IMETHODIMP
00205 nsConsoleService::LogStringMessage(const PRUnichar *message)
00206 {
00207     nsConsoleMessage *msg = new nsConsoleMessage(message);
00208     return this->LogMessage(msg);
00209 }
00210 
00211 NS_IMETHODIMP
00212 nsConsoleService::GetMessageArray(nsIConsoleMessage ***messages, PRUint32 *count)
00213 {
00214     nsIConsoleMessage **messageArray;
00215 
00216     /*
00217      * Lock the whole method, as we don't want anyone mucking with mCurrent or
00218      * mFull while we're copying out the buffer.
00219      */
00220     nsAutoLock lock(mLock);
00221 
00222     if (mCurrent == 0 && !mFull) {
00223         /*
00224          * Make a 1-length output array so that nobody gets confused,
00225          * and return a count of 0.  This should result in a 0-length
00226          * array object when called from script.
00227          */
00228         messageArray = (nsIConsoleMessage **)
00229             nsMemory::Alloc(sizeof (nsIConsoleMessage *));
00230         *messageArray = nsnull;
00231         *messages = messageArray;
00232         *count = 0;
00233         
00234         return NS_OK;
00235     }
00236 
00237     PRUint32 resultSize = mFull ? mBufferSize : mCurrent;
00238     messageArray =
00239         (nsIConsoleMessage **)nsMemory::Alloc((sizeof (nsIConsoleMessage *))
00240                                               * resultSize);
00241 
00242     if (messageArray == nsnull) {
00243         *messages = nsnull;
00244         *count = 0;
00245         return NS_ERROR_FAILURE;
00246     }
00247 
00248     PRUint32 i;
00249     if (mFull) {
00250         for (i = 0; i < mBufferSize; i++) {
00251             // if full, fill the buffer starting from mCurrent (which'll be
00252             // oldest) wrapping around the buffer to the most recent.
00253             messageArray[i] = mMessages[(mCurrent + i) % mBufferSize];
00254             NS_ADDREF(messageArray[i]);
00255         }
00256     } else {
00257         for (i = 0; i < mCurrent; i++) {
00258             messageArray[i] = mMessages[i];
00259             NS_ADDREF(messageArray[i]);
00260         }
00261     }
00262     *count = resultSize;
00263     *messages = messageArray;
00264 
00265     return NS_OK;
00266 }
00267 
00268 NS_IMETHODIMP
00269 nsConsoleService::RegisterListener(nsIConsoleListener *listener) {
00270     nsresult rv;
00271 
00272     /*
00273      * Store a threadsafe proxy to the listener rather than the
00274      * listener itself; we want the console service to be callable
00275      * from any thread, but listeners can be implemented in
00276      * thread-specific ways, and we always want to call them on their
00277      * originating thread.  JavaScript is the motivating example.
00278      */
00279     nsCOMPtr<nsIConsoleListener> proxiedListener;
00280 
00281     rv = GetProxyForListener(listener, getter_AddRefs(proxiedListener));
00282     if (NS_FAILED(rv))
00283         return rv;
00284 
00285     {
00286         nsAutoLock lock(mLock);
00287         nsISupportsKey key(listener);
00288 
00289         /*
00290          * Put the proxy event listener into a hashtable using the *real* 
00291          * listener as the key.
00292          *
00293          * This is necessary because proxy objects do *not* maintain
00294          * nsISupports identity.  Therefore, since GetProxyForListener(...)
00295          * can return different proxies for the same object (see bug #85831)
00296          * we need to use the real object as the unique key...
00297          */
00298         mListeners.Put(&key, proxiedListener);
00299     }
00300     return NS_OK;
00301 }
00302 
00303 NS_IMETHODIMP
00304 nsConsoleService::UnregisterListener(nsIConsoleListener *listener) {
00305     nsAutoLock lock(mLock);
00306 
00307     nsISupportsKey key(listener);
00308     mListeners.Remove(&key);
00309     return NS_OK;
00310 }
00311 
00312 nsresult 
00313 nsConsoleService::GetProxyForListener(nsIConsoleListener* aListener,
00314                                       nsIConsoleListener** aProxy)
00315 {
00316     nsresult rv;
00317     *aProxy = nsnull;
00318 
00319     nsCOMPtr<nsIProxyObjectManager> proxyManager =
00320         (do_GetService(NS_XPCOMPROXY_CONTRACTID));
00321 
00322     if (proxyManager == nsnull)
00323         return NS_ERROR_NOT_AVAILABLE;
00324 
00325     /*
00326      * NOTE this will fail if the calling thread doesn't have an eventQ.
00327      *
00328      * Would it be better to catch that case and leave the listener unproxied?
00329      */
00330     rv = proxyManager->GetProxyForObject(NS_CURRENT_EVENTQ,
00331                                          NS_GET_IID(nsIConsoleListener),
00332                                          aListener,
00333                                          PROXY_ASYNC | PROXY_ALWAYS,
00334                                          (void**) aProxy);
00335     return rv;
00336 }
00337 
00338 NS_IMETHODIMP
00339 nsConsoleService::Reset()
00340 {
00341     /*
00342      * Make sure nobody trips into the buffer while it's being reset
00343      */
00344     nsAutoLock lock(mLock);
00345 
00346     mCurrent = 0;
00347     mFull = PR_FALSE;
00348 
00349     /*
00350      * Free all messages stored so far (cf. destructor)
00351      */
00352     for (PRUint32 i = 0; i < mBufferSize && mMessages[i] != nsnull; i++)
00353         NS_RELEASE(mMessages[i]);
00354 
00355     return NS_OK;
00356 }