DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Untracked file

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla Communicator client code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#include "nsCOMPtr.h"
#include "nsEventQueue.h"
#include "nsIEventQueueService.h"
#include "nsIThread.h"
#include "nsIEventQueueListener.h"

#include "nsIServiceManager.h"
#include "nsIObserverService.h"

#include "nsString.h"

#include "prlog.h"

#ifdef NS_DEBUG
#include "prprf.h"
#endif

#if defined(PR_LOGGING) && defined(DEBUG_danm)
/* found these logs useful in conjunction with netlibStreamEvent logging
   from netwerk. */
PRLogModuleInfo* gEventQueueLog = 0;
PRUint32 gEventQueueLogCount = 0;
PRUint32 gEventQueueLogPPCount = 0;
static int gEventQueueLogPPLevel = 0;
static PLEventQueue *gEventQueueLogQueue = 0;
static PRThread *gEventQueueLogThread = 0;
#endif

// in a real system, these would be members in a header class...
static const char gActivatedNotification[] = "nsIEventQueueActivated";
static const char gDestroyedNotification[] = "nsIEventQueueDestroyed";

class ListenerCaller {
public:
  ListenerCaller(nsIEventQueue* aQueue, nsresult* rv) : mQueue(aQueue)
  {
    mListener = do_GetService(NS_EVENT_QUEUE_LISTENER_CONTRACTID);
    // There might be no listener...  but if so, warn
    if (mListener) {
      *rv = mListener->WillProcessEvents(mQueue);
    } else {
      NS_WARNING("No event queue listener?");
      *rv = NS_OK;
    }
  }

  ~ListenerCaller() {
    if (mListener) {
      mListener->DidProcessEvents(mQueue);
    }
  }
  
private:
  nsIEventQueue* mQueue;
  nsCOMPtr<nsIEventQueueListener> mListener;
};

nsEventQueueImpl::nsEventQueueImpl()
{
  NS_ADDREF_THIS();
  /* The slightly weird ownership model for eventqueues goes like this:

     General:
       There's an addref from the factory generally held by whoever asked for
     the queue. The queue addrefs itself (right here) and releases itself
     after someone calls StopAcceptingEvents() on the queue and when it is
     dark and empty (in CheckForDeactivation()).

     Chained queues:

       Eldest queue:
         The eldest queue in a chain is held on to by the EventQueueService
       in a hash table, so it is possible that the eldest queue may not be
       released until the EventQueueService is shutdown.
         You may not call StopAcceptingEvents() on this queue until you have
       done so on all younger queues.

       General:
         Each queue holds a reference to their immediate elder link and a weak
       reference to their immediate younger link.  Because you must shut down
       queues from youngest to eldest, all the references will be removed.

       It happens something like:
         queue->StopAcceptingEvents()
         {
           CheckForDeactivation()
           {
             -- hopefully we are able to shutdown now --
             Unlink()
             {
               -- remove the reference we hold to our elder queue  --
               -- NULL out our elder queues weak reference to us --
             }
             RELEASE ourself (to balance the ADDREF here in the constructor)
             -- and we should go away. --
           }
         }


     Notes:
       A dark queue no longer accepts events.  An empty queue simply has no events.
  */

#if defined(PR_LOGGING) && defined(DEBUG_danm)
  PR_LOG(gEventQueueLog, PR_LOG_DEBUG,
         ("EventQueue: Created [queue=%lx]",(long)mEventQueue));
  ++gEventQueueLogCount;
#endif

  mYoungerQueue = nsnull;
  mEventQueue = nsnull;
  mAcceptingEvents = PR_TRUE;
  mCouldHaveEvents = PR_TRUE;
}

nsEventQueueImpl::~nsEventQueueImpl()
{
  Unlink();

#if defined(PR_LOGGING) && defined(DEBUG_danm)
  PR_LOG(gEventQueueLog, PR_LOG_DEBUG,
         ("EventQueue: Destroyed [queue=%lx]",(long)mEventQueue));
  ++gEventQueueLogCount;
#endif

  if (mEventQueue) {
    // Perhaps CheckForDeactivation wasn't called...
    if (mCouldHaveEvents)
      NotifyObservers(gDestroyedNotification);
    PL_DestroyEventQueue(mEventQueue);
  }
}

NS_IMETHODIMP
nsEventQueueImpl::Init(PRBool aNative)
{
  PRThread *thread = PR_GetCurrentThread();
  if (aNative)
    mEventQueue = PL_CreateNativeEventQueue("Thread event queue...", thread);
  else
    mEventQueue = PL_CreateMonitoredEventQueue("Thread event queue...", thread);
  if (!mEventQueue)
    return NS_ERROR_FAILURE;
  NotifyObservers(gActivatedNotification);
  return NS_OK;
}

NS_IMETHODIMP
nsEventQueueImpl::InitFromPRThread(PRThread* thread, PRBool aNative)
{
  if (thread == NS_CURRENT_THREAD)
  {
     thread = PR_GetCurrentThread();
  }
  else if (thread == NS_UI_THREAD)
  {
    nsCOMPtr<nsIThread>  mainIThread;
    nsresult rv;

    // Get the primordial thread
    rv = nsIThread::GetMainThread(getter_AddRefs(mainIThread));
    if (NS_FAILED(rv)) return rv;

    rv = mainIThread->GetPRThread(&thread);
    if (NS_FAILED(rv)) return rv;
  }

  if (aNative)
    mEventQueue = PL_CreateNativeEventQueue("Thread event queue...", thread);
  else
    mEventQueue = PL_CreateMonitoredEventQueue("Thread event queue...", thread);
  if (!mEventQueue)
    return NS_ERROR_FAILURE;

  NotifyObservers(gActivatedNotification);
  return NS_OK;
}

NS_IMETHODIMP
nsEventQueueImpl::InitFromPLQueue(PLEventQueue* aQueue)
{
  mEventQueue = aQueue;
  NotifyObservers(gActivatedNotification);
  return NS_OK;
}

/* nsISupports interface implementation... */
NS_IMPL_THREADSAFE_ISUPPORTS3(nsEventQueueImpl,
                              nsIEventQueue,
                              nsIEventTarget,
                              nsPIEventQueueChain)

/* nsIEventQueue interface implementation... */

NS_IMETHODIMP
nsEventQueueImpl::StopAcceptingEvents()
{
  // this assertion is bogus.  I should be able to shut down the eldest queue,
  //    as long as there are no younger children


  NS_ASSERTION(mElderQueue || !mYoungerQueue, "attempted to disable eldest queue in chain");
  mAcceptingEvents = PR_FALSE;
  CheckForDeactivation();
#if defined(PR_LOGGING) && defined(DEBUG_danm)
  PR_LOG(gEventQueueLog, PR_LOG_DEBUG,
         ("EventQueue: StopAccepting [queue=%lx, accept=%d, could=%d]",
         (long)mEventQueue,(int)mAcceptingEvents,(int)mCouldHaveEvents));
  ++gEventQueueLogCount;
#endif
  return NS_OK;
}

// utility funtion to send observers a notification
void
nsEventQueueImpl::NotifyObservers(const char *aTopic)
{
  // only send out this notification for native event queues
  if (!PL_IsQueueNative(mEventQueue))
    return;

  // we should not call out to the observer service from background threads!
  NS_ASSERTION(nsIThread::IsMainThread(),
               "Native event queues should only be used on the main thread");

  nsresult rv;
  nsCOMPtr<nsIObserverService> os = do_GetService("@mozilla.org/observer-service;1", &rv);
  if (NS_SUCCEEDED(rv)) {
    nsCOMPtr<nsIEventQueue> kungFuDeathGrip(this);
    nsCOMPtr<nsISupports> us(do_QueryInterface(kungFuDeathGrip));
    os->NotifyObservers(us, aTopic, NULL);
  }
}

void
nsEventQueueImpl::CheckForDeactivation()
{
  if (mCouldHaveEvents && !mAcceptingEvents && !PL_EventAvailable(mEventQueue)) {
    if (PL_IsQueueOnCurrentThread(mEventQueue)) {
      mCouldHaveEvents = PR_FALSE;
      NotifyObservers(gDestroyedNotification);
      NS_RELEASE_THIS(); // balance ADDREF from the constructor
    } else
      NS_ERROR("CheckForDeactivation called from wrong thread!");
  }
}


NS_IMETHODIMP
nsEventQueueImpl::InitEvent(PLEvent* aEvent,
                            void* owner,
                            PLHandleEventProc handler,
                            PLDestroyEventProc destructor)
{
  PL_InitEvent(aEvent, owner, handler, destructor);
  return NS_OK;
}


NS_IMETHODIMP
nsEventQueueImpl::PostEvent(PLEvent* aEvent)
{
  if (!mAcceptingEvents) {
#if defined(PR_LOGGING) && defined(DEBUG_danm)
    PR_LOG(gEventQueueLog, PR_LOG_DEBUG,
           ("EventQueue: Punt posted event [queue=%lx, accept=%d, could=%d]",
         (long)mEventQueue,(int)mAcceptingEvents,(int)mCouldHaveEvents));
  ++gEventQueueLogCount;
#endif
    nsresult rv = NS_ERROR_FAILURE;
    NS_ASSERTION(mElderQueue, "event dropped because event chain is dead");
    if (mElderQueue) {
      nsCOMPtr<nsIEventQueue> elder(do_QueryInterface(mElderQueue));
      if (elder)
        rv = elder->PostEvent(aEvent);
    }
    return rv;
  }
#if defined(PR_LOGGING) && defined(DEBUG_danm)
  PR_LOG(gEventQueueLog, PR_LOG_DEBUG,
         ("EventQueue: Posting event [queue=%lx]", (long)mEventQueue));
  ++gEventQueueLogCount;
#endif
  return PL_PostEvent(mEventQueue, aEvent) == PR_SUCCESS ? NS_OK : NS_ERROR_FAILURE;
}

NS_IMETHODIMP
nsEventQueueImpl::PostSynchronousEvent(PLEvent* aEvent, void** aResult)
{
  if (!mAcceptingEvents) {
#if defined(PR_LOGGING) && defined(DEBUG_danm)
    PR_LOG(gEventQueueLog, PR_LOG_DEBUG,
           ("EventQueue: Punt posted synchronous event [queue=%lx, accept=%d, could=%d]",
         (long)mEventQueue,(int)mAcceptingEvents,(int)mCouldHaveEvents));
  ++gEventQueueLogCount;
#endif
    nsresult rv = NS_ERROR_NO_INTERFACE;
    NS_ASSERTION(mElderQueue, "event dropped because event chain is dead");
    if (mElderQueue) {
      nsCOMPtr<nsIEventQueue> elder(do_QueryInterface(mElderQueue));
      if (elder)
        rv = elder->PostSynchronousEvent(aEvent, aResult);
      return rv;
    }
    return NS_ERROR_ABORT;
  }

#if defined(PR_LOGGING) && defined(DEBUG_danm)
  PR_LOG(gEventQueueLog, PR_LOG_DEBUG,
         ("EventQueue: Posting synchronous event [queue=%lx]", (long)mEventQueue));
  ++gEventQueueLogCount;
#endif
  void* result = PL_PostSynchronousEvent(mEventQueue, aEvent);
  if (aResult)
    *aResult = result;

  return NS_OK;
}

NS_IMETHODIMP
nsEventQueueImpl::EnterMonitor()
{
  PL_ENTER_EVENT_QUEUE_MONITOR(mEventQueue);
  return NS_OK;
}

NS_IMETHODIMP
nsEventQueueImpl::ExitMonitor()
{
  PL_EXIT_EVENT_QUEUE_MONITOR(mEventQueue);
  return NS_OK;
}


NS_IMETHODIMP
nsEventQueueImpl::RevokeEvents(void* owner)
{
  nsCOMPtr<nsIEventQueue> youngest;
  GetYoungest(getter_AddRefs(youngest));
  NS_ASSERTION(youngest, "How could we possibly not have a youngest queue?");
  nsCOMPtr<nsPIEventQueueChain> youngestAsChain(do_QueryInterface(youngest));
  NS_ASSERTION(youngestAsChain, "RevokeEvents won't work; expect crashes");
  return youngestAsChain->RevokeEventsInternal(owner);
}


NS_IMETHODIMP
nsEventQueueImpl::GetPLEventQueue(PLEventQueue** aEventQueue)
{
  if (!mEventQueue)
    return NS_ERROR_NULL_POINTER;

  *aEventQueue = mEventQueue;
  return NS_OK;
}

NS_IMETHODIMP
nsEventQueueImpl::IsOnCurrentThread(PRBool *aResult)
{
    *aResult = PL_IsQueueOnCurrentThread( mEventQueue );
    return NS_OK;
}


NS_IMETHODIMP
nsEventQueueImpl::IsQueueNative(PRBool *aResult)
{
  *aResult = PL_IsQueueNative(mEventQueue);
  return NS_OK;
}

NS_IMETHODIMP
nsEventQueueImpl::PendingEvents(PRBool *aResult)
{
    *aResult = PL_EventAvailable(mEventQueue);
    if (!*aResult && mElderQueue) {
        nsCOMPtr<nsIEventQueue> elder(do_QueryInterface(mElderQueue));
        if (elder)
            return elder->EventAvailable(*aResult);
    }
    return NS_OK;
}


NS_IMETHODIMP
nsEventQueueImpl::ProcessPendingEvents()
{
  PRBool correctThread = PL_IsQueueOnCurrentThread(mEventQueue);

  NS_ASSERTION(correctThread, "attemping to process events on the wrong thread");

  if (!correctThread)
    return NS_ERROR_FAILURE;

  nsresult rv;
  ListenerCaller caller(this, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  
#if defined(PR_LOGGING) && defined(DEBUG_danm)
  ++gEventQueueLogPPLevel;
  if ((gEventQueueLogQueue != mEventQueue || gEventQueueLogThread != PR_GetCurrentThread() ||
       gEventQueueLogCount != gEventQueueLogPPCount) && gEventQueueLogPPLevel == 1) {
    PR_LOG(gEventQueueLog, PR_LOG_DEBUG,
           ("EventQueue: Process pending [queue=%lx, accept=%d, could=%d]",
           (long)mEventQueue,(int)mAcceptingEvents,(int)mCouldHaveEvents));
    gEventQueueLogPPCount = ++gEventQueueLogCount;
    gEventQueueLogQueue = mEventQueue;
    gEventQueueLogThread = PR_GetCurrentThread();
  }
#endif
  PL_ProcessPendingEvents(mEventQueue);

  // if we're no longer accepting events and there are still events in the
  // queue, then process remaining events.
  if (!mAcceptingEvents && PL_EventAvailable(mEventQueue))
      PL_ProcessPendingEvents(mEventQueue);

  CheckForDeactivation();

  if (mElderQueue) {
    nsCOMPtr<nsIEventQueue> elder(do_QueryInterface(mElderQueue));
    if (elder)
      elder->ProcessPendingEvents();
  }
#if defined(PR_LOGGING) && defined(DEBUG_danm)
  --gEventQueueLogPPLevel;
#endif
  return NS_OK;
}

NS_IMETHODIMP
nsEventQueueImpl::EventLoop()
{
  PRBool correctThread = PL_IsQueueOnCurrentThread(mEventQueue);

  NS_ASSERTION(correctThread, "attemping to process events on the wrong thread");

  if (!correctThread)
    return NS_ERROR_FAILURE;

  PL_EventLoop(mEventQueue);
  return NS_OK;
}

NS_IMETHODIMP
nsEventQueueImpl::EventAvailable(PRBool& aResult)
{
  aResult = PL_EventAvailable(mEventQueue);
  return NS_OK;
}

NS_IMETHODIMP
nsEventQueueImpl::GetEvent(PLEvent** aResult)
{
  *aResult = PL_GetEvent(mEventQueue);
  CheckForDeactivation();
  return NS_OK;
}

NS_IMETHODIMP
nsEventQueueImpl::HandleEvent(PLEvent* aEvent)
{
  PRBool correctThread = PL_IsQueueOnCurrentThread(mEventQueue);
  NS_ASSERTION(correctThread, "attemping to process events on the wrong thread");
  if (!correctThread)
    return NS_ERROR_FAILURE;

  nsresult rv;
  ListenerCaller caller(this, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  
#if defined(PR_LOGGING) && defined(DEBUG_danm)
  PR_LOG(gEventQueueLog, PR_LOG_DEBUG,
         ("EventQueue: handle event [queue=%lx, accept=%d, could=%d]",
         (long)mEventQueue,(int)mAcceptingEvents,(int)mCouldHaveEvents));
  ++gEventQueueLogCount;
#endif
  PL_HandleEvent(aEvent);
  return NS_OK;
}

NS_IMETHODIMP
nsEventQueueImpl::WaitForEvent(PLEvent** aResult)
{
  PRBool correctThread = PL_IsQueueOnCurrentThread(mEventQueue);
  NS_ASSERTION(correctThread, "attemping to process events on the wrong thread");
  if (!correctThread)
    return NS_ERROR_FAILURE;

#if defined(PR_LOGGING) && defined(DEBUG_danm)
PR_LOG(gEventQueueLog, PR_LOG_DEBUG,
       ("EventQueue: wait for event [queue=%lx, accept=%d, could=%d]",
       (long)mEventQueue,(int)mAcceptingEvents,(int)mCouldHaveEvents));
++gEventQueueLogCount;
#endif
  *aResult = PL_WaitForEvent(mEventQueue);
  CheckForDeactivation();
  return NS_OK;
}

NS_IMETHODIMP_(PRInt32)
nsEventQueueImpl::GetEventQueueSelectFD()
{
  return PL_GetEventQueueSelectFD(mEventQueue);
}

NS_METHOD
nsEventQueueImpl::Create(nsISupports *aOuter,
                         REFNSIID aIID,
                         void **aResult)
{
  nsEventQueueImpl* evt = new nsEventQueueImpl();
  if (evt == NULL)
    return NS_ERROR_OUT_OF_MEMORY;
  nsresult rv = evt->QueryInterface(aIID, aResult);
  if (NS_FAILED(rv)) {
    delete evt;
  }
  return rv;
}

// ---------------- nsPIEventQueueChain -----------------

NS_IMETHODIMP
nsEventQueueImpl::AppendQueue(nsIEventQueue *aQueue)
{
  nsresult      rv;
  nsCOMPtr<nsIEventQueue> end;
  nsCOMPtr<nsPIEventQueueChain> queueChain(do_QueryInterface(aQueue));

  if (!aQueue)
    return NS_ERROR_NO_INTERFACE;

/* this would be nice
  NS_ASSERTION(aQueue->mYoungerQueue == NULL && aQueue->mElderQueue == NULL,
               "event queue repeatedly appended to queue chain");
*/
  rv = NS_ERROR_NO_INTERFACE;

#ifdef NS_DEBUG
  int depth = 0;
  nsEventQueueImpl *next = this;
  while (next && depth < 100) {
    next = NS_STATIC_CAST(nsEventQueueImpl *, next->mYoungerQueue);
    ++depth;
  }
  if (depth > 5) {
    char warning[80];
    PR_snprintf(warning, sizeof(warning),
      "event queue chain length is %d. this is almost certainly a leak.", depth);
    NS_WARNING(warning);
  }
#endif

  // (be careful doing this outside nsEventQueueService's mEventQMonitor)

  GetYoungest(getter_AddRefs(end));
  nsCOMPtr<nsPIEventQueueChain> endChain(do_QueryInterface(end));
  if (endChain) {
    endChain->SetYounger(queueChain);
    queueChain->SetElder(endChain);
    rv = NS_OK;
  }
  return rv;
}

NS_IMETHODIMP
nsEventQueueImpl::Unlink()
{
  nsCOMPtr<nsPIEventQueueChain> young = mYoungerQueue,
                                old = mElderQueue;

#if defined(PR_LOGGING) && defined(DEBUG_danm)
  PR_LOG(gEventQueueLog, PR_LOG_DEBUG,
         ("EventQueue: unlink [queue=%lx, younger=%lx, elder=%lx]",
         (long)mEventQueue,(long)mYoungerQueue, (long)mElderQueue.get()));
  ++gEventQueueLogCount;
#endif

  // this is probably OK, but shouldn't happen by design, so tell me if it does
  NS_ASSERTION(!mYoungerQueue, "event queue chain broken in middle");

  // break links early in case the Release cascades back onto us
  mYoungerQueue = nsnull;
  mElderQueue = nsnull;

  if (young)
    young->SetElder(old);
  if (old) {
    old->SetYounger(young);
  }
  return NS_OK;
}

NS_IMETHODIMP
nsEventQueueImpl::GetYoungest(nsIEventQueue **aQueue)
{
  if (mYoungerQueue)
    return mYoungerQueue->GetYoungest(aQueue);

  nsIEventQueue *answer = NS_STATIC_CAST(nsIEventQueue *, this);
  NS_ADDREF(answer);
  *aQueue = answer;
  return NS_OK;
}

NS_IMETHODIMP
nsEventQueueImpl::GetYoungestActive(nsIEventQueue **aQueue)
{
  nsCOMPtr<nsIEventQueue> answer;

  if (mYoungerQueue)
    mYoungerQueue->GetYoungestActive(getter_AddRefs(answer));
  if (!answer) {
    if (mAcceptingEvents && mCouldHaveEvents)
      answer = NS_STATIC_CAST(nsIEventQueue *, this);
  }
  *aQueue = answer;
  NS_IF_ADDREF(*aQueue);
  return NS_OK;
}

NS_IMETHODIMP
nsEventQueueImpl::SetYounger(nsPIEventQueueChain *aQueue)
{
  mYoungerQueue = aQueue;
  return NS_OK;
}

NS_IMETHODIMP
nsEventQueueImpl::SetElder(nsPIEventQueueChain *aQueue)
{
  mElderQueue = aQueue;
  return NS_OK;
}

NS_IMETHODIMP
nsEventQueueImpl::GetYounger(nsIEventQueue **aQueue)
{
  if (!mYoungerQueue) {
    *aQueue = nsnull;
    return NS_OK;
  }
  return mYoungerQueue->QueryInterface(NS_GET_IID(nsIEventQueue), (void**)&aQueue);
}

NS_IMETHODIMP
nsEventQueueImpl::GetElder(nsIEventQueue **aQueue)
{
  if (!mElderQueue) {
    *aQueue = nsnull;
    return NS_OK;
  }
  return mElderQueue->QueryInterface(NS_GET_IID(nsIEventQueue), (void**)&aQueue);
}

NS_IMETHODIMP
nsEventQueueImpl::RevokeEventsInternal(void* aOwner)
{
  PL_RevokeEvents(mEventQueue, aOwner);
  if (mElderQueue) {
    mElderQueue->RevokeEventsInternal(aOwner);
  }
  return NS_OK;
}