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

Mercurial (7f134570dc68)

VCS Links

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 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
/* ***** 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.org Code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 2001
 * 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 ***** */

// nsMsgPrintEngine.cpp: provides a DocShell container for use 
// in printing

#include "nscore.h"
#include "nsCOMPtr.h"

#include "nsIComponentManager.h"

#include "nsISupports.h"

#include "nsIURI.h"
#include "nsIDocShell.h"
#include "nsPIDOMWindow.h"
#include "nsIDocumentViewer.h"
#include "nsIPresShell.h"
#include "nsIDocument.h"
#include "nsIMsgMessageService.h"
#include "nsMsgUtils.h"
#include "nsIWebProgress.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIMarkupDocumentViewer.h"
#include "nsMsgPrintEngine.h"
#include "nsMsgBaseCID.h"
#include "nsIDocumentLoader.h"
#include "nsIWidget.h"
#include "nsIXULWindow.h"
#include "nsIPrefService.h"
#include "nsIPrefBranch.h"
#include "nsThreadUtils.h"
#include "nsAutoPtr.h"

// Interfaces Needed
#include "nsIBaseWindow.h"
#include "nsIDocShellTreeOwner.h"
#include "nsIDocShellTreeItem.h"
#include "nsIDocShellTreeNode.h"
#include "nsIWebNavigation.h"
#include "nsIChannel.h"
#include "nsIContentViewerFile.h"
#include "nsIPrintingPromptService.h"
#include "nsServiceManagerUtils.h"

static const char* kPrintingPromptService = "@mozilla.org/embedcomp/printingprompt-service;1";

/////////////////////////////////////////////////////////////////////////
// nsMsgPrintEngine implementation
/////////////////////////////////////////////////////////////////////////

nsMsgPrintEngine::nsMsgPrintEngine() :
  mIsDoingPrintPreview(PR_FALSE),
  mMsgInx(nsIMsgPrintEngine::MNAB_START)
{
  mCurrentlyPrintingURI = -1;
}


nsMsgPrintEngine::~nsMsgPrintEngine()
{
}

// Implement AddRef and Release
NS_IMPL_ISUPPORTS4(nsMsgPrintEngine,
                         nsIMsgPrintEngine, 
                         nsIWebProgressListener, 
                         nsIObserver,
                         nsISupportsWeakReference)

// nsIWebProgressListener implementation
NS_IMETHODIMP
nsMsgPrintEngine::OnStateChange(nsIWebProgress* aWebProgress, 
                   nsIRequest *aRequest, 
                   PRUint32 progressStateFlags, 
                   nsresult aStatus)
{
  nsresult rv = NS_OK;

  // top-level document load data
  if (progressStateFlags & nsIWebProgressListener::STATE_IS_DOCUMENT) {
    if (progressStateFlags & nsIWebProgressListener::STATE_START) {
      // Tell the user we are loading...
      nsString msg;
      GetString(NS_LITERAL_STRING("LoadingMessageToPrint").get(), msg);
      SetStatusMessage(msg);
    }

    if (progressStateFlags & nsIWebProgressListener::STATE_STOP) {
      nsCOMPtr<nsIDocumentLoader> docLoader(do_QueryInterface(aWebProgress));
      if (docLoader) 
      {
        // Check to see if the document DOMWin that is finished loading is the same
        // one as the mail msg that we started to load.
        // We only want to print when the entire msg and all of its attachments
        // have finished loading.
        // The mail msg doc is the last one to receive the STATE_STOP notification
        nsCOMPtr<nsISupports> container;
        docLoader->GetContainer(getter_AddRefs(container));
        nsCOMPtr<nsIDOMWindow> domWindow(do_GetInterface(container));
        if (domWindow.get() != mMsgDOMWin.get()) {
          return NS_OK;
        }
      }
      nsCOMPtr<nsIWebProgressListener> wpl(do_QueryInterface(mPrintPromptService));
      if (wpl) {
        wpl->OnStateChange(nsnull, nsnull, nsIWebProgressListener::STATE_STOP|nsIWebProgressListener::STATE_IS_DOCUMENT, nsnull);
        mPrintProgressListener = nsnull;
        mPrintProgress         = nsnull;
        mPrintProgressParams   = nsnull;
      }

      PRBool isPrintingCancelled = PR_FALSE;
      if (mPrintSettings)
      {
        mPrintSettings->GetIsCancelled(&isPrintingCancelled);
      }
      if (!isPrintingCancelled) {
        // if aWebProgress is a documentloader than the notification from
        // loading the documents. If it is NULL (or not a DocLoader) then it 
        // it coming from Printing
        if (docLoader) {
          // Now, fire off the print operation!
          rv = NS_ERROR_FAILURE;

          // Tell the user the message is loaded...
          nsString msg;
          GetString(NS_LITERAL_STRING("MessageLoaded").get(), msg);
          SetStatusMessage(msg);

          NS_ASSERTION(mDocShell,"can't print, there is no docshell");
          if ( (!mDocShell) || (!aRequest) ) 
          {
            return StartNextPrintOperation();
          }
          nsCOMPtr<nsIChannel> aChannel = do_QueryInterface(aRequest);
          if (!aChannel) return NS_ERROR_FAILURE;

          // Make sure this isn't just "about:blank" finishing....
          nsCOMPtr<nsIURI> originalURI = nsnull;
          if (NS_SUCCEEDED(aChannel->GetOriginalURI(getter_AddRefs(originalURI))) && originalURI)
          {
            nsCAutoString spec;

            if (NS_SUCCEEDED(originalURI->GetSpec(spec)))
            {      
              if (spec.Equals("about:blank"))
              {
                return StartNextPrintOperation();
              }
            }
          }

          // If something bad happens here (menaing we can fire the PLEvent, highly unlikely)
          // we will still ask the msg to print, but if the user "cancels" out of the 
          // print dialog the hidden print window will not be "closed"
          if (!FirePrintEvent()) 
          {
            PrintMsgWindow();
          }
        } else {
          FireStartNextEvent();
          rv = NS_OK;
        }
      } 
      else 
      {
        mWindow->Close();
      }
    }
  }

  return rv;
}

NS_IMETHODIMP
nsMsgPrintEngine::OnProgressChange(nsIWebProgress *aWebProgress,
                                     nsIRequest *aRequest,
                                     PRInt32 aCurSelfProgress,
                                     PRInt32 aMaxSelfProgress,
                                     PRInt32 aCurTotalProgress,
                                     PRInt32 aMaxTotalProgress)
{
    return NS_OK;
}

NS_IMETHODIMP
nsMsgPrintEngine::OnLocationChange(nsIWebProgress* aWebProgress,
                      nsIRequest* aRequest,
                      nsIURI *location)
{
    NS_NOTREACHED("notification excluded in AddProgressListener(...)");
    return NS_OK;
}


NS_IMETHODIMP
nsMsgPrintEngine::OnStatusChange(nsIWebProgress* aWebProgress,
                    nsIRequest* aRequest,
                    nsresult aStatus,
                    const PRUnichar* aMessage)
{
    return NS_OK;
}


NS_IMETHODIMP
nsMsgPrintEngine::OnSecurityChange(nsIWebProgress *aWebProgress, 
                      nsIRequest *aRequest, 
                      PRUint32 state)
{
    NS_NOTREACHED("notification excluded in AddProgressListener(...)");
    return NS_OK;
}

NS_IMETHODIMP    
nsMsgPrintEngine::SetWindow(nsIDOMWindowInternal *aWin)
{
	if (!aWin)
  {
    // It isn't an error to pass in null for aWin, in fact it means we are shutting
    // down and we should start cleaning things up...
		return NS_OK;
  }

  mWindow = aWin;

  nsCOMPtr<nsPIDOMWindow> win( do_QueryInterface(aWin) );
  NS_ENSURE_TRUE(win, NS_ERROR_FAILURE);

  win->GetDocShell()->SetAppType(nsIDocShell::APP_TYPE_MAIL);

  nsCOMPtr<nsIDocShellTreeItem> docShellAsItem =
    do_QueryInterface(win->GetDocShell());
  NS_ENSURE_TRUE(docShellAsItem, NS_ERROR_FAILURE);

  nsCOMPtr<nsIDocShellTreeItem> rootAsItem;
  docShellAsItem->GetSameTypeRootTreeItem(getter_AddRefs(rootAsItem));

  nsCOMPtr<nsIDocShellTreeNode> rootAsNode(do_QueryInterface(rootAsItem));
  NS_ENSURE_TRUE(rootAsNode, NS_ERROR_FAILURE);

  nsCOMPtr<nsIDocShellTreeItem> childItem;
  rootAsNode->FindChildWithName(NS_LITERAL_STRING("content").get(), PR_TRUE,
				PR_FALSE, nsnull, nsnull,
				getter_AddRefs(childItem));

  mDocShell = do_QueryInterface(childItem);

  if(mDocShell)
    SetupObserver();

  return NS_OK;
}

/* void setParentWindow (in nsIDOMWindowInternal ptr); */
NS_IMETHODIMP nsMsgPrintEngine::SetParentWindow(nsIDOMWindowInternal *ptr)
{
  mParentWindow = ptr;
  return NS_OK;
}


NS_IMETHODIMP
nsMsgPrintEngine::ShowWindow(PRBool aShow)
{
  nsresult rv;

  NS_ENSURE_TRUE(mWindow, NS_ERROR_NOT_INITIALIZED);

  nsCOMPtr <nsPIDOMWindow> win = do_QueryInterface(mWindow, &rv);

  NS_ENSURE_SUCCESS(rv,rv);

  nsCOMPtr <nsIDocShellTreeItem> treeItem =
    do_QueryInterface(win->GetDocShell(), &rv);
  NS_ENSURE_SUCCESS(rv,rv);

  nsCOMPtr <nsIDocShellTreeOwner> treeOwner;
  rv = treeItem->GetTreeOwner(getter_AddRefs(treeOwner));
  NS_ENSURE_SUCCESS(rv,rv);
  
  if (treeOwner) {
    // disable (enable) the window
    nsCOMPtr<nsIBaseWindow> baseWindow;
    baseWindow = do_QueryInterface(treeOwner, &rv);
    NS_ENSURE_SUCCESS(rv,rv);

    rv = baseWindow->SetEnabled(aShow);
    NS_ENSURE_SUCCESS(rv,rv);

    // hide or show the window
    baseWindow->SetVisibility(aShow);
  }
  return rv;
}

NS_IMETHODIMP
nsMsgPrintEngine::AddPrintURI(const PRUnichar *aMsgURI)
{
  mURIArray.AppendElement(nsDependentString(aMsgURI));
  return NS_OK;
}

NS_IMETHODIMP
nsMsgPrintEngine::SetPrintURICount(PRInt32 aCount)
{
  mURICount = aCount;
  return NS_OK;
}

NS_IMETHODIMP
nsMsgPrintEngine::StartPrintOperation(nsIPrintSettings* aPS)
{
  NS_ENSURE_ARG_POINTER(aPS);
  mPrintSettings = aPS;

  // Load the about:blank on the tail end...
  nsresult rv = AddPrintURI(NS_LITERAL_STRING("about:blank").get()); 
  if (NS_FAILED(rv)) return rv; 
  return StartNextPrintOperation();
}

//----------------------------------------------------------------------
// Set up to use the "pluggable" Print Progress Dialog
nsresult
nsMsgPrintEngine::ShowProgressDialog(PRBool aIsForPrinting, PRBool& aDoNotify)
{
  nsresult rv;

  // default to not notifying, that if something here goes wrong
  // or we aren't going to show the progress dialog we can straight into 
  // reflowing the doc for printing.
  aDoNotify = PR_FALSE;

  // Assume we can't do progress and then see if we can
  PRBool showProgressDialog = PR_FALSE;

  // if it is already being shown then don't bother to find out if it should be
  // so skip this and leave mShowProgressDialog set to FALSE
  nsCOMPtr<nsIPrefBranch> prefBranch = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
  if (NS_SUCCEEDED(rv)) 
  {
    prefBranch->GetBoolPref("print.show_print_progress", &showProgressDialog);
  }

  // Turning off the showing of Print Progress in Prefs overrides
  // whether the calling PS desire to have it on or off, so only check PS if 
  // prefs says it's ok to be on.
  if (showProgressDialog) 
  {
    mPrintSettings->GetShowPrintProgress(&showProgressDialog);
  }

  // Now open the service to get the progress dialog
  // If we don't get a service, that's ok, then just don't show progress
  if (showProgressDialog) {
    if (!mPrintPromptService) 
    {
      mPrintPromptService = do_GetService(kPrintingPromptService);
    }
    if (mPrintPromptService) 
    {
      nsCOMPtr<nsIDOMWindow> domWin(do_QueryInterface(mParentWindow));
      if (!domWin) 
      {
        domWin = mWindow;
      }

      rv = mPrintPromptService->ShowProgress(domWin, mWebBrowserPrint, mPrintSettings, this, aIsForPrinting,
                                            getter_AddRefs(mPrintProgressListener), 
                                            getter_AddRefs(mPrintProgressParams), 
                                            &aDoNotify);
      if (NS_SUCCEEDED(rv)) {

        showProgressDialog = mPrintProgressListener != nsnull && mPrintProgressParams != nsnull;

        if (showProgressDialog) 
        {
          nsIWebProgressListener* wpl = static_cast<nsIWebProgressListener*>(mPrintProgressListener.get());
          NS_ASSERTION(wpl, "nsIWebProgressListener is NULL!");
          NS_ADDREF(wpl);
          nsString msg;
          if (mIsDoingPrintPreview) {
            GetString(NS_LITERAL_STRING("LoadingMailMsgForPrintPreview").get(), msg);
          } else {
            GetString(NS_LITERAL_STRING("LoadingMailMsgForPrint").get(), msg);
          }
          if (!msg.IsEmpty()) 
            mPrintProgressParams->SetDocTitle(msg.get());
        }
      }
    }
  }
  return rv;
}


NS_IMETHODIMP
nsMsgPrintEngine::StartNextPrintOperation()
{
  nsresult      rv;

  // Only do this the first time through...
  if (mCurrentlyPrintingURI == -1)
    InitializeDisplayCharset();

  mCurrentlyPrintingURI++;

  // First, check if we are at the end of this stuff!
  if (mCurrentlyPrintingURI >= mURIArray.Length())
  {
    // This is the end...dum, dum, dum....my only friend...the end
    mWindow->Close();

    // Tell the user we are done...
    nsString msg;
    GetString(NS_LITERAL_STRING("PrintingComplete").get(), msg);
    SetStatusMessage(msg);
    return NS_OK;
  }

  if (!mDocShell)
    return StartNextPrintOperation();

  const nsString &uri = mURIArray[mCurrentlyPrintingURI];
  rv = FireThatLoadOperationStartup(uri);
  if (NS_FAILED(rv))
    return StartNextPrintOperation();
  else
    return rv;
}

NS_IMETHODIMP    
nsMsgPrintEngine::SetStatusFeedback(nsIMsgStatusFeedback *aFeedback)
{
	mFeedback = aFeedback;
	return NS_OK;
}

#define DATA_URL_PREFIX     "data:"
#define ADDBOOK_URL_PREFIX     "addbook:"

nsresult
nsMsgPrintEngine::FireThatLoadOperationStartup(const nsString& uri)
{
  if (!uri.IsEmpty()) 
    mLoadURI = uri;
  else
    mLoadURI.Truncate();

  PRBool   notify = PR_FALSE;
  nsresult rv     = NS_ERROR_FAILURE;
  // Don't show dialog if we are out of URLs
  //if ( mCurrentlyPrintingURI < mURIArray.Length() && !mIsDoingPrintPreview)
  if ( mCurrentlyPrintingURI < mURIArray.Length())
    rv = ShowProgressDialog(!mIsDoingPrintPreview, notify);
  if (NS_FAILED(rv) || !notify) 
    return FireThatLoadOperation(uri);
  return NS_OK;
}

nsresult
nsMsgPrintEngine::FireThatLoadOperation(const nsString& uri)
{
  nsresult rv;
  
  nsCString uriCStr;
  LossyCopyUTF16toASCII(uri, uriCStr);

  nsCOMPtr <nsIMsgMessageService> messageService;
  // if this is a data: url, skip it, because 
  // we've already got something we can print
  // and we know it is not a message.
  //
  // if this an about:blank url, skip it, because
  // ...
  //
  // if this is an addbook: url, skip it, because
  // we know that isn't a message.
  //
  // if this is a message part (or .eml file on disk)
  // skip it, because we don't want to print the parent message
  // we want to print the part.
  // example:  imap://sspitzer@nsmail-1:143/fetch%3EUID%3E/INBOX%3E180958?part=1.1.2&type=application/x-message-display&filename=test"
  if (!StringBeginsWith(uriCStr, NS_LITERAL_CSTRING(DATA_URL_PREFIX)) &&
      !StringBeginsWith(uriCStr, NS_LITERAL_CSTRING(ADDBOOK_URL_PREFIX)) &&
      !uriCStr.EqualsLiteral("about:blank") && 
      uriCStr.Find(NS_LITERAL_CSTRING("type=application/x-message-display")) == -1) {
    rv = GetMessageServiceFromURI(uriCStr, getter_AddRefs(messageService));
  }

  if (NS_SUCCEEDED(rv) && messageService)
    rv = messageService->DisplayMessageForPrinting(uriCStr.get(), mDocShell, nsnull, nsnull, nsnull);
  //If it's not something we know about, then just load try loading it directly.
  else
  {
    nsCOMPtr<nsIWebNavigation> webNav(do_QueryInterface(mDocShell));
    if (webNav)
      rv = webNav->LoadURI(uri.get(),                        // URI string
                           nsIWebNavigation::LOAD_FLAGS_NONE, // Load flags
                           nsnull,                            // Referring URI
                           nsnull,                            // Post data
                           nsnull);                           // Extra headers
  }
  return rv;
}

void
nsMsgPrintEngine::InitializeDisplayCharset()
{
  // libmime always converts to UTF-8 (both HTML and XML)
  if (mDocShell) 
  {
    nsCOMPtr<nsIContentViewer> cv;
    mDocShell->GetContentViewer(getter_AddRefs(cv));
    if (cv) 
    {
      nsCOMPtr<nsIMarkupDocumentViewer> muDV = do_QueryInterface(cv);
      if (muDV) 
      {
        muDV->SetForceCharacterSet(NS_LITERAL_CSTRING("UTF-8"));
      }
    }
  }
}

void
nsMsgPrintEngine::SetupObserver()
{
  if (!mDocShell)
    return;

  if (mDocShell)
  {
    nsCOMPtr<nsIWebProgress> progress(do_GetInterface(mDocShell));
    NS_ASSERTION(progress, "we were expecting a nsIWebProgress");
    if (progress) 
    {
      (void) progress->AddProgressListener((nsIWebProgressListener *)this,
                                        nsIWebProgress::NOTIFY_STATE_DOCUMENT);
    }

    // Cache a pointer to the mail message's DOMWindow 
    // so later we know when we can print when the 
    // document "loaded" msgs com thru via the Progress listener
    mMsgDOMWin = do_GetInterface(mDocShell);
  }
}

nsresult
nsMsgPrintEngine::SetStatusMessage(const nsString& aMsgString)
{
  if ( (!mFeedback) || (aMsgString.IsEmpty()) )
    return NS_OK;

  mFeedback->ShowStatusString(aMsgString);
  return NS_OK;
}

#define MESSENGER_STRING_URL       "chrome://messenger/locale/messenger.properties"

void
nsMsgPrintEngine::GetString(const PRUnichar *aStringName, nsString& outStr)
{
  nsresult    res = NS_OK;
  outStr.Truncate();

  if (!mStringBundle)
  {
    static const char propertyURL[] = MESSENGER_STRING_URL;

    nsCOMPtr<nsIStringBundleService> sBundleService = 
             do_GetService(NS_STRINGBUNDLE_CONTRACTID, &res); 
    if (NS_SUCCEEDED(res) && (nsnull != sBundleService)) 
      res = sBundleService->CreateBundle(propertyURL, getter_AddRefs(mStringBundle));
  }

  if (mStringBundle)
    res = mStringBundle->GetStringFromName(aStringName, getter_Copies(outStr));
  return;
}

//-----------------------------------------------------------
void
nsMsgPrintEngine::PrintMsgWindow()
{
  const char* kMsgKeys[] = {"PrintingMessage",  "PrintPreviewMessage",
                            "PrintingContact",  "PrintPreviewContact",
                            "PrintingAddrBook", "PrintPreviewAddrBook"};

  mDocShell->GetContentViewer(getter_AddRefs(mContentViewer));  
  if (mContentViewer) 
  {
    mWebBrowserPrint = do_QueryInterface(mContentViewer);
    if (mWebBrowserPrint) 
    {
      if (!mPrintSettings) 
      {
        mWebBrowserPrint->GetGlobalPrintSettings(getter_AddRefs(mPrintSettings));
      }
      
      // fix for bug #118887 and bug #176016
      // don't show the actual url when printing mail messages or addressbook cards.
      // for mail, it can review the salt.  for addrbook, it's a data:// url, which
      // means nothing to the end user.
      // needs to be " " and not "" or nsnull, otherwise, we'll still print the url
      mPrintSettings->SetDocURL(NS_LITERAL_STRING(" ").get());

      nsresult rv = NS_ERROR_FAILURE;
      if (mIsDoingPrintPreview) 
      {
        if (mStartupPPObs) {
          rv = mStartupPPObs->Observe(nsnull, nsnull, nsnull);
        }
      } 
      else 
      {
        mPrintSettings->SetPrintSilent(mCurrentlyPrintingURI != 0);
        nsCOMPtr<nsIContentViewerFile> contentViewerFile(do_QueryInterface(mWebBrowserPrint));
        if (contentViewerFile && mParentWindow) 
        {
          rv = contentViewerFile->PrintWithParent(mParentWindow, mPrintSettings, (nsIWebProgressListener *)this);
        } 
        else 
        {
          rv = mWebBrowserPrint->Print(mPrintSettings, (nsIWebProgressListener *)this);
        }
      }

      if (NS_FAILED(rv))
      {
        mWebBrowserPrint = nsnull;
        mContentViewer = nsnull;
        PRBool isPrintingCancelled = PR_FALSE;
        if (mPrintSettings)
        {
          mPrintSettings->GetIsCancelled(&isPrintingCancelled);
        }
        if (!isPrintingCancelled) 
        {
          StartNextPrintOperation();
        } 
        else 
        {
          mWindow->Close();
        }
      }
      else
      {
        // Tell the user we started printing...
        nsString msg;
        GetString(NS_ConvertASCIItoUTF16(kMsgKeys[mMsgInx]).get(), msg);
        SetStatusMessage(msg);
      }
    }
  }
}

//---------------------------------------------------------------
//-- Event Notification
//---------------------------------------------------------------

//---------------------------------------------------------------
class nsPrintMsgWindowEvent : public nsRunnable
{
public:
  nsPrintMsgWindowEvent(nsMsgPrintEngine *mpe)
    : mMsgPrintEngine(mpe)
  {}

  NS_IMETHOD Run()
  {
    if (mMsgPrintEngine) 
      mMsgPrintEngine->PrintMsgWindow();
    return NS_OK;
  }

private:
  nsRefPtr<nsMsgPrintEngine> mMsgPrintEngine;
};

//-----------------------------------------------------------
class nsStartNextPrintOpEvent : public nsRunnable
{
public:
  nsStartNextPrintOpEvent(nsMsgPrintEngine *mpe)
    : mMsgPrintEngine(mpe)
  {}

  NS_IMETHOD Run()
  {
    if (mMsgPrintEngine) 
      mMsgPrintEngine->StartNextPrintOperation();
    return NS_OK;
  }

private:
  nsRefPtr<nsMsgPrintEngine> mMsgPrintEngine;
};

//-----------------------------------------------------------
PRBool
nsMsgPrintEngine::FirePrintEvent()
{
  nsCOMPtr<nsIRunnable> event = new nsPrintMsgWindowEvent(this);
  return NS_SUCCEEDED(NS_DispatchToCurrentThread(event));
}

//-----------------------------------------------------------
PRBool
nsMsgPrintEngine::FireStartNextEvent()
{
  nsCOMPtr<nsIRunnable> event = new nsStartNextPrintOpEvent(this);
  return NS_DispatchToCurrentThread(event);
}

/* void setStartupPPObserver (in nsIObserver startupPPObs); */
NS_IMETHODIMP nsMsgPrintEngine::SetStartupPPObserver(nsIObserver *startupPPObs)
{
  mStartupPPObs = startupPPObs;
  return NS_OK;
}

/* attribute boolean doPrintPreview; */
NS_IMETHODIMP nsMsgPrintEngine::GetDoPrintPreview(PRBool *aDoPrintPreview)
{
  NS_ENSURE_ARG_POINTER(aDoPrintPreview);
  *aDoPrintPreview = mIsDoingPrintPreview;
  return NS_OK;
}
NS_IMETHODIMP nsMsgPrintEngine::SetDoPrintPreview(PRBool aDoPrintPreview)
{
  mIsDoingPrintPreview = aDoPrintPreview;
  return NS_OK;
}

/* void setMsgType (in long aMsgType); */
NS_IMETHODIMP nsMsgPrintEngine::SetMsgType(PRInt32 aMsgType)
{
  if (mMsgInx >= nsIMsgPrintEngine::MNAB_START && mMsgInx < nsIMsgPrintEngine::MNAB_END) 
  {
    mMsgInx = aMsgType;
    return NS_OK;
  }
  return NS_ERROR_FAILURE;
}

/*=============== nsIObserver Interface ======================*/
NS_IMETHODIMP nsMsgPrintEngine::Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData)
{
  return FireThatLoadOperation(mLoadURI);
}