void
nsAppStartup::CloseAllWindows()
{
  nsCOMPtr<nsIWindowMediator> mediator
    (do_GetService(NS_WINDOWMEDIATOR_CONTRACTID));

  nsCOMPtr<nsISimpleEnumerator> windowEnumerator;

  mediator->GetEnumerator(nsnull, getter_AddRefs(windowEnumerator));

  if (!windowEnumerator)
    return;

  PRBool more;
  while (NS_SUCCEEDED(windowEnumerator->HasMoreElements(&more)) && more) {
    nsCOMPtr<nsISupports> isupports;
    if (NS_FAILED(windowEnumerator->GetNext(getter_AddRefs(isupports))))
      break;

    nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(isupports);
    NS_ASSERTION(window, "not an nsPIDOMWindow");
    if (window)
      window->ForceClose();
  }
}
bool MinimalHistoryEditor::remove(const Call* item)
{
   if (regenFile(item)) {
      mediator()->removeItem(item);
      return true;
   }
   return false;
}
NS_IMETHODIMP
nsAppShellService::UnregisterTopLevelWindow(nsIXULWindow* aWindow)
{
  if (mXPCOMShuttingDown) {
    /* return an error code in order to:
       - avoid doing anything with other member variables while we are in
         the destructor
       - notify the caller not to release the AppShellService after
         unregistering the window
         (we don't want to be deleted twice consecutively to
         mHiddenWindow->Destroy() in our destructor)
    */
    return NS_ERROR_FAILURE;
  }
  
  NS_ENSURE_ARG_POINTER(aWindow);

  if (aWindow == mHiddenWindow) {
    // CreateHiddenWindow() does not register the window, so we're done.
    return NS_OK;
  }

  // tell the window mediator
  nsCOMPtr<nsIWindowMediator> mediator
    ( do_GetService(NS_WINDOWMEDIATOR_CONTRACTID) );
  NS_ASSERTION(mediator, "Couldn't get window mediator. Doing xpcom shutdown?");

  if (mediator)
    mediator->UnregisterWindow(aWindow);
	
  // tell the window watcher
  nsCOMPtr<nsPIWindowWatcher> wwatcher ( do_GetService(NS_WINDOWWATCHER_CONTRACTID) );
  NS_ASSERTION(wwatcher, "Couldn't get windowwatcher, doing xpcom shutdown?");
  if (wwatcher) {
    nsCOMPtr<nsIDocShell> docShell;
    aWindow->GetDocShell(getter_AddRefs(docShell));
    if (docShell) {
      nsCOMPtr<nsIDOMWindow> domWindow(do_GetInterface(docShell));
      if (domWindow)
        wwatcher->RemoveWindow(domWindow);
    }
  }

  return NS_OK;
}
    void TestThreadSafe()
    {
        SCXCoreLib::SCXThreadLockHandle lockH = SCXCoreLib::ThreadLockHandleGet();
        SCXCoreLib::SCXLogMediatorSimple mediator(lockH);
        
        SCXCoreLib::SCXThreadLock lock(lockH);

        SCXCoreLib::SCXLogItem l(L"scxcore.something",
                                 SCXCoreLib::eWarning,
                                 L"something",
                                 SCXSRCLOCATION,
                                 0);
        SCXCoreLib::SCXHandle<TestLogBackend> b;

        CPPUNIT_ASSERT_THROW(mediator.LogThisItem(l), SCXCoreLib::SCXThreadLockHeldException);
        CPPUNIT_ASSERT_THROW(mediator.GetEffectiveSeverity(L"scxcore.something"), SCXCoreLib::SCXThreadLockHeldException);
        CPPUNIT_ASSERT_THROW(mediator.RegisterConsumer(b), SCXCoreLib::SCXThreadLockHeldException);
        CPPUNIT_ASSERT_THROW(mediator.DeRegisterConsumer(b), SCXCoreLib::SCXThreadLockHeldException);
    }
int main()
{
	srand(static_cast<int>(time(0)));


	PSO pso;
	Reentry reentry;
	Mediator mediator(&reentry, &pso);

	unsigned start = time(0);


	pso.tieMediator(&mediator);
	reentry.tieMediator(&mediator);

	pso.calculate();

	unsigned end = time(0);

	Console::instance()->inform("run time")->inform(end-start);

	return 0;
}
/*
 * Register a new top level window (created elsewhere)
 */
NS_IMETHODIMP
nsAppShellService::RegisterTopLevelWindow(nsIXULWindow* aWindow)
{
  // tell the window mediator about the new window
  nsCOMPtr<nsIWindowMediator> mediator
    ( do_GetService(NS_WINDOWMEDIATOR_CONTRACTID) );
  NS_ASSERTION(mediator, "Couldn't get window mediator.");

  if (mediator)
    mediator->RegisterWindow(aWindow);

  // tell the window watcher about the new window
  nsCOMPtr<nsPIWindowWatcher> wwatcher ( do_GetService(NS_WINDOWWATCHER_CONTRACTID) );
  NS_ASSERTION(wwatcher, "No windowwatcher?");
  if (wwatcher) {
    nsCOMPtr<nsIDocShell> docShell;
    aWindow->GetDocShell(getter_AddRefs(docShell));
    NS_ASSERTION(docShell, "Window has no docshell");
    if (docShell) {
      nsCOMPtr<nsIDOMWindow> domWindow(do_GetInterface(docShell));
      NS_ASSERTION(domWindow, "Couldn't get DOM window.");
      if (domWindow)
        wwatcher->AddWindow(domWindow, 0);
    }
  }

  // an ongoing attempt to quit is stopped by a newly opened window
  nsCOMPtr<nsIObserverService> obssvc =
    do_GetService("@mozilla.org/observer-service;1");
  NS_ASSERTION(obssvc, "Couldn't get observer service.");

  if (obssvc)
    obssvc->NotifyObservers(aWindow, "xul-window-registered", nsnull);

  return NS_OK;
}
nsresult nsMessengerOSXIntegration::OnAlertFinished(const PRUnichar * aAlertCookie)
{
  nsresult rv = NS_OK;
  nsCOMPtr<nsIPrefBranch> prefBranch (do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
  NS_ENSURE_SUCCESS(rv, rv);
  
  PRBool bounceDockIcon = PR_FALSE; 
  prefBranch->GetBoolPref("mail.biff.animate_dock_icon", &bounceDockIcon);

  // This will call GetAttention(), which will bounce the dock icon.
  if (!mSuppressBiffIcon)
  {
    nsCOMPtr<nsIWindowMediator> mediator (do_GetService(NS_WINDOWMEDIATOR_CONTRACTID));
    if (bounceDockIcon && mediator)
    {
      nsCOMPtr<nsIDOMWindowInternal> domWindow;
      mediator->GetMostRecentWindow(NS_LITERAL_STRING("mail:3pane").get(), getter_AddRefs(domWindow));
      if (domWindow)
	  {
        nsCOMPtr<nsIDOMChromeWindow> chromeWindow(do_QueryInterface(domWindow));
        chromeWindow->GetAttention();
	  }
    }

    // This will change the dock icon.     
    // If we want to overlay the number of new messages on top of
    // the icon ...
    
    // use OverlayApplicationDockTileImage
    // -- you'll have to pass it a CGImage, and somehow we have to
    // create the CGImage with the numbers. tricky    
    PRInt32 totalNewMessages = CountNewMessages();
    CGContextRef context = ::BeginCGContextForApplicationDockTile();
    
    // Draw a circle.

    ::CGContextBeginPath(context);
    ::CGContextAddArc(context, 95.0, 95.0, 25.0, 0.0, 2 * M_PI, true);
    ::CGContextClosePath(context);

    // use #2fc600 for the color.
    ::CGContextSetRGBFillColor(context, 0.184, 0.776, 0.0, 1);

    //::CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.7);
    ::CGContextFillPath(context);

    // Draw the number.
    nsAutoString total;
    total.AppendInt(totalNewMessages);

    // Use a system font (kThemeUtilityWindowTitleFont)
    ScriptCode sysScript = ::GetScriptManagerVariable(smSysScript);

    Str255 fontName;
    SInt16 fontSize;
    Style fontStyle;
    ::GetThemeFont(kThemeSmallEmphasizedSystemFont, sysScript, fontName,
                   &fontSize, &fontStyle);

    FMFontFamily family = ::FMGetFontFamilyFromName(fontName);
    FMFont fmFont;
    OSStatus err = ::FMGetFontFromFontFamilyInstance(family, fontStyle, &fmFont,
                                                     nsnull);
    if (err != noErr) 
	{
	  NS_WARNING("FMGetFontFromFontFamilyInstance failed");
	  ::EndCGContextForApplicationDockTile(context);
	  return NS_ERROR_FAILURE;
    }

    ATSUStyle style;
    err = ::ATSUCreateStyle(&style);
    if (err != noErr) 
	{
      NS_WARNING("ATSUCreateStyle failed");
	  ::EndCGContextForApplicationDockTile(context);
      return NS_ERROR_FAILURE;
	}
        
    Fixed size = Long2Fix(24);
    RGBColor white = { 0xFFFF, 0xFFFF, 0xFFFF };
    
    ATSUAttributeTag tags[3] = { kATSUFontTag, kATSUSizeTag, kATSUColorTag };
    ByteCount valueSizes[3] = { sizeof(ATSUFontID), sizeof(Fixed),
                                sizeof(RGBColor) };
    ATSUAttributeValuePtr values[3] = { &fmFont, &size, &white };

    err = ::ATSUSetAttributes(style, 3, tags, valueSizes, values);
    if (err != noErr) {
        NS_WARNING("ATSUSetAttributes failed");
        ::ATSUDisposeStyle(style);
        ::EndCGContextForApplicationDockTile(context);

        return NS_ERROR_FAILURE;
      }

    UniCharCount runLengths = kATSUToTextEnd;
    ATSUTextLayout textLayout;
    err = ::ATSUCreateTextLayoutWithTextPtr(total.get(),
                                            kATSUFromTextBeginning,
                                            kATSUToTextEnd, total.Length(), 1,
                                            &runLengths, &style, &textLayout);
    if (err != noErr) 
	{
        NS_WARNING("ATSUCreateTextLayoutWithTextPtr failed");
        ::ATSUDisposeStyle(style);
        ::EndCGContextForApplicationDockTile(context);

        return NS_ERROR_FAILURE;
    }

    ATSUAttributeTag layoutTags[1] = { kATSUCGContextTag };
    ByteCount layoutValueSizes[1] = { sizeof(CGContextRef) };
    ATSUAttributeValuePtr layoutValues[1] = { &context };

    err = ::ATSUSetLayoutControls(textLayout, 1, layoutTags, layoutValueSizes,
                                  layoutValues);
    if (err != noErr) 
	{
        NS_WARNING("ATSUSetLayoutControls failed");
        ::ATSUDisposeStyle(style);
        ::EndCGContextForApplicationDockTile(context);
        return NS_ERROR_FAILURE;
    }

    Rect boundingBox;
    err = ::ATSUMeasureTextImage(textLayout, kATSUFromTextBeginning,
                                 kATSUToTextEnd, Long2Fix(0), Long2Fix(0),
                                 &boundingBox);
    if (err != noErr) 
	{
        NS_WARNING("ATSUMeasureTextImage failed");
        ::ATSUDisposeStyle(style);
        ::EndCGContextForApplicationDockTile(context);
        return NS_ERROR_FAILURE;
    }

    // Center text inside circle
    err = ::ATSUDrawText(textLayout, kATSUFromTextBeginning, kATSUToTextEnd,
                         Long2Fix(90 - (boundingBox.right - boundingBox.left) / 2),
                         Long2Fix(95 - (boundingBox.bottom - boundingBox.top) / 2));

    ::ATSUDisposeStyle(style);
    ::ATSUDisposeTextLayout(textLayout);

    ::CGContextFlush(context);

    ::EndCGContextForApplicationDockTile(context);
    mBiffIconVisible = PR_TRUE;
  }

  mSuppressBiffIcon = PR_FALSE;
  mAlertInProgress = PR_FALSE;
  return NS_OK;
}
NS_IMETHODIMP
nsAppStartup::Quit(PRUint32 aMode)
{
  PRUint32 ferocity = (aMode & 0xF);

  // Quit the application. We will asynchronously call the appshell's
  // Exit() method via nsAppExitEvent to allow one last pass
  // through any events in the queue. This guarantees a tidy cleanup.
  nsresult rv = NS_OK;
  PRBool postedExitEvent = PR_FALSE;

  if (mShuttingDown)
    return NS_OK;

  // If we're considering quitting, we will only do so if:
  if (ferocity == eConsiderQuit) {
    if (mConsiderQuitStopper == 0) {
      // there are no windows...
      ferocity = eAttemptQuit;
    }
#ifdef XP_MACOSX
    else if (mConsiderQuitStopper == 1) {
      // ... or there is only a hiddenWindow left, and it's useless:
      nsCOMPtr<nsIAppShellService> appShell
        (do_GetService(NS_APPSHELLSERVICE_CONTRACTID));

      // Failure shouldn't be fatal, but will abort quit attempt:
      if (!appShell)
        return NS_OK;

      PRBool usefulHiddenWindow;
      appShell->GetApplicationProvidedHiddenWindow(&usefulHiddenWindow);
      nsCOMPtr<nsIXULWindow> hiddenWindow;
      appShell->GetHiddenWindow(getter_AddRefs(hiddenWindow));
      // If the one window is useful, we won't quit:
      if (!hiddenWindow || usefulHiddenWindow)
        return NS_OK;

      ferocity = eAttemptQuit;
    }
#endif
  }

  nsCOMPtr<nsIObserverService> obsService;
  if (ferocity == eAttemptQuit || ferocity == eForceQuit) {

    nsCOMPtr<nsISimpleEnumerator> windowEnumerator;
    nsCOMPtr<nsIWindowMediator> mediator (do_GetService(NS_WINDOWMEDIATOR_CONTRACTID));
    if (mediator) {
      mediator->GetEnumerator(nsnull, getter_AddRefs(windowEnumerator));
      if (windowEnumerator) {
        PRBool more;
        while (windowEnumerator->HasMoreElements(&more), more) {
          nsCOMPtr<nsISupports> window;
          windowEnumerator->GetNext(getter_AddRefs(window));
          nsCOMPtr<nsPIDOMWindow> domWindow(do_QueryInterface(window));
          if (domWindow) {
            if (!domWindow->CanClose())
              return NS_OK;
          }
        }
      }
    }

    mShuttingDown = PR_TRUE;
    if (!mRestart) {
      mRestart = (aMode & eRestart) != 0;
      gRestartMode = (aMode & 0xF0);
    }

    if (mRestart) {
      // Firefox-restarts reuse the process. Process start-time isn't a useful indicator of startup time
      PR_SetEnv(PR_smprintf("MOZ_APP_RESTART=%lld", (PRInt64) PR_Now() / PR_USEC_PER_MSEC));
    }

    obsService = mozilla::services::GetObserverService();

    if (!mAttemptingQuit) {
      mAttemptingQuit = PR_TRUE;
#ifdef XP_MACOSX
      // now even the Mac wants to quit when the last window is closed
      ExitLastWindowClosingSurvivalArea();
#endif
      if (obsService)
        obsService->NotifyObservers(nsnull, "quit-application-granted", nsnull);
    }

    /* Enumerate through each open window and close it. It's important to do
       this before we forcequit because this can control whether we really quit
       at all. e.g. if one of these windows has an unload handler that
       opens a new window. Ugh. I know. */
    CloseAllWindows();

    if (mediator) {
      if (ferocity == eAttemptQuit) {
        ferocity = eForceQuit; // assume success

        /* Were we able to immediately close all windows? if not, eAttemptQuit
           failed. This could happen for a variety of reasons; in fact it's
           very likely. Perhaps we're being called from JS and the window->Close
           method hasn't had a chance to wrap itself up yet. So give up.
           We'll return (with eConsiderQuit) as the remaining windows are
           closed. */
        mediator->GetEnumerator(nsnull, getter_AddRefs(windowEnumerator));
        if (windowEnumerator) {
          PRBool more;
          while (windowEnumerator->HasMoreElements(&more), more) {
            /* we can't quit immediately. we'll try again as the last window
               finally closes. */
            ferocity = eAttemptQuit;
            nsCOMPtr<nsISupports> window;
            windowEnumerator->GetNext(getter_AddRefs(window));
            nsCOMPtr<nsIDOMWindowInternal> domWindow(do_QueryInterface(window));
            if (domWindow) {
              PRBool closed = PR_FALSE;
              domWindow->GetClosed(&closed);
              if (!closed) {
                rv = NS_ERROR_FAILURE;
                break;
              }
            }
          }
        }
      }
    }
  }

  if (ferocity == eForceQuit) {
    // do it!

    // No chance of the shutdown being cancelled from here on; tell people
    // we're shutting down for sure while all services are still available.
    if (obsService) {
      NS_NAMED_LITERAL_STRING(shutdownStr, "shutdown");
      NS_NAMED_LITERAL_STRING(restartStr, "restart");
      obsService->NotifyObservers(nsnull, "quit-application",
        mRestart ? restartStr.get() : shutdownStr.get());
    }

    if (!mRunning) {
      postedExitEvent = PR_TRUE;
    }
    else {
      // no matter what, make sure we send the exit event.  If
      // worst comes to worst, we'll do a leaky shutdown but we WILL
      // shut down. Well, assuming that all *this* stuff works ;-).
      nsCOMPtr<nsIRunnable> event = new nsAppExitEvent(this);
      rv = NS_DispatchToCurrentThread(event);
      if (NS_SUCCEEDED(rv)) {
        postedExitEvent = PR_TRUE;
      }
      else {
        NS_WARNING("failed to dispatch nsAppExitEvent");
      }
    }
  }

  // turn off the reentrancy check flag, but not if we have
  // more asynchronous work to do still.
  if (!postedExitEvent)
    mShuttingDown = PR_FALSE;
  return rv;
}