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.

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 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
/* -*- 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.org 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):
 *   Roland Mainz <Roland.Mainz@informatik.med.uni-giessen.de>
 *   IBM Corp.
 *
 * 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 "nsDeviceContext.h"
#include "nsFont.h"
#include "nsIView.h"
#include "nsGfxCIID.h"
#include "nsVoidArray.h"
#include "nsIFontMetrics.h"
#include "nsHashtable.h"
#include "nsILanguageAtomService.h"
#include "nsIServiceManager.h"
#include "nsUnicharUtils.h"
#include "nsCRT.h"


NS_IMPL_ISUPPORTS3(DeviceContextImpl, nsIDeviceContext, nsIObserver, nsISupportsWeakReference)

DeviceContextImpl::DeviceContextImpl()
{
  mFontCache = nsnull;
  mDevUnitsToAppUnits = 1.0f;
  mAppUnitsToDevUnits = 1.0f;
  mCPixelScale = 1.0f;
  mZoom = 1.0f;
  mWidget = nsnull;
  mFontAliasTable = nsnull;

#ifdef NS_PRINT_PREVIEW
  mUseAltDC = kUseAltDCFor_NONE;
#endif
#ifdef NS_DEBUG
  mInitialized = PR_FALSE;
#endif
}

static PRBool PR_CALLBACK DeleteValue(nsHashKey* aKey, void* aValue, void* closure)
{
  delete ((nsString*)aValue);
  return PR_TRUE;
}

DeviceContextImpl::~DeviceContextImpl()
{
  nsCOMPtr<nsIObserverService> obs(do_GetService("@mozilla.org/observer-service;1"));
  if (obs)
    obs->RemoveObserver(this, "memory-pressure");

  if (nsnull != mFontCache)
  {
    delete mFontCache;
    mFontCache = nsnull;
  }

  if (nsnull != mFontAliasTable) {
    mFontAliasTable->Enumerate(DeleteValue);
    delete mFontAliasTable;
  }

}

NS_IMETHODIMP
DeviceContextImpl::Observe(nsISupports* aSubject, const char* aTopic, const PRUnichar* aSomeData)
{
  if (mFontCache && !nsCRT::strcmp(aTopic, "memory-pressure")) {
    mFontCache->Compact();
  }
  return NS_OK;
}

NS_IMETHODIMP DeviceContextImpl::Init(nsNativeWidget aWidget)
{
  mWidget = aWidget;

  CommonInit();

  return NS_OK;
}

void DeviceContextImpl::CommonInit(void)
{
#ifdef NS_DEBUG
  NS_ASSERTION(!mInitialized, "device context is initialized twice!");
  mInitialized = PR_TRUE;
#endif

  // register as a memory-pressure observer to free font resources
  // in low-memory situations.
  nsCOMPtr<nsIObserverService> obs(do_GetService("@mozilla.org/observer-service;1"));
  if (obs)
    obs->AddObserver(this, "memory-pressure", PR_TRUE);
}

NS_IMETHODIMP DeviceContextImpl::GetCanonicalPixelScale(float &aScale) const
{
  aScale = mCPixelScale;
  return NS_OK;
}

NS_IMETHODIMP DeviceContextImpl::SetCanonicalPixelScale(float aScale)
{
  mCPixelScale = aScale;
  return NS_OK;
}

NS_IMETHODIMP DeviceContextImpl::CreateRenderingContext(nsIView *aView, nsIRenderingContext *&aContext)
{
#ifdef NS_PRINT_PREVIEW
  // AltDC NEVER use widgets to create their DCs
  if (mAltDC && (mUseAltDC & kUseAltDCFor_CREATERC_PAINT)) {
    return mAltDC->CreateRenderingContext(aContext);
  }
#endif

  nsresult            rv;

  aContext = nsnull;
  nsCOMPtr<nsIRenderingContext> pContext;
  rv = CreateRenderingContextInstance(*getter_AddRefs(pContext));
  if (NS_SUCCEEDED(rv)) {
    rv = InitRenderingContext(pContext, aView->GetWidget());
    if (NS_SUCCEEDED(rv)) {
      aContext = pContext;
      NS_ADDREF(aContext);
    }
  }
  
  return rv;
}

NS_IMETHODIMP DeviceContextImpl::CreateRenderingContext(nsIDrawingSurface* aSurface, nsIRenderingContext *&aContext)
{
#ifdef NS_PRINT_PREVIEW
  // AltDC NEVER use widgets to create their DCs
  if (mAltDC && (mUseAltDC & kUseAltDCFor_CREATERC_PAINT)) {
    return mAltDC->CreateRenderingContext(aContext);
  }
#endif /* NS_PRINT_PREVIEW */

  nsresult rv;

  aContext = nsnull;
  nsCOMPtr<nsIRenderingContext> pContext;
  rv = CreateRenderingContextInstance(*getter_AddRefs(pContext));
  if (NS_SUCCEEDED(rv)) {
    rv = InitRenderingContext(pContext, aSurface);
    if (NS_SUCCEEDED(rv)) {
      aContext = pContext;
      NS_ADDREF(aContext);
    }
  }
  
  return rv;
}

NS_IMETHODIMP DeviceContextImpl::CreateRenderingContext(nsIWidget *aWidget, nsIRenderingContext *&aContext)
{
  nsresult rv;

#ifdef NS_PRINT_PREVIEW
  // AltDC NEVER use widgets to create their DCs
  // NOTE: The mAltDC will call it;s own init
  // so we can return here
  if (mAltDC && (mUseAltDC & kUseAltDCFor_CREATERC_REFLOW)) {
    return mAltDC->CreateRenderingContext(aContext);
  }
#endif

  aContext = nsnull;
  nsCOMPtr<nsIRenderingContext> pContext;
  rv = CreateRenderingContextInstance(*getter_AddRefs(pContext));
  if (NS_SUCCEEDED(rv)) {
    rv = InitRenderingContext(pContext, aWidget);
    if (NS_SUCCEEDED(rv)) {
      aContext = pContext;
      NS_ADDREF(aContext);
    }
  }    
  
  return rv;
}

NS_IMETHODIMP DeviceContextImpl::CreateRenderingContextInstance(nsIRenderingContext *&aContext)
{
  static NS_DEFINE_CID(kRenderingContextCID, NS_RENDERING_CONTEXT_CID);

  nsresult rv;
  nsCOMPtr<nsIRenderingContext> pContext = do_CreateInstance(kRenderingContextCID, &rv);
  if (NS_SUCCEEDED(rv)) {
    aContext = pContext;
    NS_ADDREF(aContext);
  }
  return rv;
}

nsresult DeviceContextImpl::InitRenderingContext(nsIRenderingContext *aContext, nsIWidget *aWin)
{
#ifdef NS_PRINT_PREVIEW
  // there are a couple of cases where the kUseAltDCFor_CREATERC_xxx flag has been turned off
  // but we still need to initialize with the Alt DC
  if (mAltDC) {
    return aContext->Init(mAltDC, aWin);
  } else {
    return aContext->Init(this, aWin);
  }
#else
  return aContext->Init(this, aWin);
#endif
}

nsresult DeviceContextImpl::InitRenderingContext(nsIRenderingContext *aContext, nsIDrawingSurface* aSurface)
{
#ifdef NS_PRINT_PREVIEW
  // there are a couple of cases where the kUseAltDCFor_CREATERC_xxx flag has been turned off
  // but we still need to initialize with the Alt DC
  if (mAltDC) {
    return aContext->Init(mAltDC, aSurface);
  } else {
    return aContext->Init(this, aSurface);
  }
#else
  return aContext->Init(this, aSurface);
#endif /* NS_PRINT_PREVIEW */
}

NS_IMETHODIMP DeviceContextImpl::CreateFontCache()
{
  mFontCache = new nsFontCache();
  if (!mFontCache) {
    return NS_ERROR_OUT_OF_MEMORY;
  }
  return mFontCache->Init(this);
}

NS_IMETHODIMP DeviceContextImpl::FontMetricsDeleted(const nsIFontMetrics* aFontMetrics)
{
  if (mFontCache) {
    mFontCache->FontMetricsDeleted(aFontMetrics);
  }
  return NS_OK;
}

void
DeviceContextImpl::GetLocaleLangGroup(void)
{
  if (!mLocaleLangGroup) {
    nsCOMPtr<nsILanguageAtomService> langService;
    langService = do_GetService(NS_LANGUAGEATOMSERVICE_CONTRACTID);
    if (langService) {
      mLocaleLangGroup = langService->GetLocaleLanguageGroup();
    }
    if (!mLocaleLangGroup) {
      mLocaleLangGroup = do_GetAtom("x-western");
    }
  }
}

NS_IMETHODIMP DeviceContextImpl::GetMetricsFor(const nsFont& aFont,
  nsIAtom* aLangGroup, nsIFontMetrics*& aMetrics)
{
#ifdef NS_PRINT_PREVIEW
  // Defer to Alt when there is one
  if (mAltDC != nsnull && (mUseAltDC & kUseAltDCFor_FONTMETRICS)) {
    return mAltDC->GetMetricsFor(aFont, aLangGroup, aMetrics);
  }
#endif

  if (nsnull == mFontCache) {
    nsresult  rv = CreateFontCache();
    if (NS_FAILED(rv)) {
      aMetrics = nsnull;
      return rv;
    }
    // XXX temporary fix for performance problem -- erik
    GetLocaleLangGroup();
  }

  // XXX figure out why aLangGroup is NULL sometimes
  if (!aLangGroup) {
    aLangGroup = mLocaleLangGroup;
  }

  return mFontCache->GetMetricsFor(aFont, aLangGroup, aMetrics);
}

NS_IMETHODIMP DeviceContextImpl::GetMetricsFor(const nsFont& aFont, nsIFontMetrics*& aMetrics)
{
#ifdef NS_PRINT_PREVIEW
  // Defer to Alt when there is one
  if (mAltDC != nsnull && (mUseAltDC & kUseAltDCFor_FONTMETRICS)) {
    return mAltDC->GetMetricsFor(aFont, aMetrics);
  }
#endif

  if (nsnull == mFontCache) {
    nsresult  rv = CreateFontCache();
    if (NS_FAILED(rv)) {
      aMetrics = nsnull;
      return rv;
    }
    // XXX temporary fix for performance problem -- erik
    GetLocaleLangGroup();
  }
  return mFontCache->GetMetricsFor(aFont, mLocaleLangGroup, aMetrics);
}

NS_IMETHODIMP DeviceContextImpl::SetZoom(float aZoom)
{
  mZoom = aZoom;
  return NS_OK;
}

NS_IMETHODIMP DeviceContextImpl::GetZoom(float &aZoom) const
{
  aZoom = mZoom;
  return NS_OK;
}

NS_IMETHODIMP DeviceContextImpl::GetDepth(PRUint32& aDepth)
{
  aDepth = 24;
  return NS_OK;
}

NS_IMETHODIMP DeviceContextImpl::GetPaletteInfo(nsPaletteInfo& aPaletteInfo)
{
  aPaletteInfo.isPaletteDevice = PR_FALSE;
  aPaletteInfo.sizePalette = 0;
  aPaletteInfo.numReserved = 0;
  aPaletteInfo.palette = nsnull;
  return NS_OK;
}

struct FontEnumData {
  FontEnumData(nsIDeviceContext* aDC, nsString& aFaceName)
    : mDC(aDC), mFaceName(aFaceName)
  {}
  nsIDeviceContext* mDC;
  nsString&         mFaceName;
};

static PRBool FontEnumCallback(const nsString& aFamily, PRBool aGeneric, void *aData)
{
  FontEnumData* data = (FontEnumData*)aData;
  // XXX for now, all generic fonts are presumed to exist
  //     we may want to actually check if there's an installed conversion
  if (aGeneric) {
    data->mFaceName = aFamily;
    return PR_FALSE; // found one, stop.
  }
  else {
    nsAutoString  local;
    PRBool        aliased;
    data->mDC->GetLocalFontName(aFamily, local, aliased);
    if (aliased || (NS_SUCCEEDED(data->mDC->CheckFontExistence(local)))) {
      data->mFaceName = local;
      return PR_FALSE; // found one, stop.
    }
  }
  return PR_TRUE; // didn't exist, continue looking
}

NS_IMETHODIMP DeviceContextImpl::FirstExistingFont(const nsFont& aFont, nsString& aFaceName)
{
  FontEnumData  data(this, aFaceName);
  if (aFont.EnumerateFamilies(FontEnumCallback, &data)) {
    return NS_ERROR_FAILURE;  // ran out
  }
  return NS_OK;
}

class FontAliasKey: public nsHashKey 
{
public:
  FontAliasKey(const nsString& aString)
  {mString.Assign(aString);}

  virtual PRUint32 HashCode(void) const;
  virtual PRBool Equals(const nsHashKey *aKey) const;
  virtual nsHashKey *Clone(void) const;

  nsString  mString;
};

PRUint32 FontAliasKey::HashCode(void) const
{
  PRUint32 hash = 0;
  const PRUnichar* string = mString.get();
  PRUnichar ch;
  while ((ch = *string++) != 0) {
    // FYI: hash = hash*37 + ch
    ch = ToUpperCase(ch);
    hash = ((hash << 5) + (hash << 2) + hash) + ch;
  }
  return hash;
}

PRBool FontAliasKey::Equals(const nsHashKey *aKey) const
{
  return mString.Equals(((FontAliasKey*)aKey)->mString, nsCaseInsensitiveStringComparator());
}

nsHashKey* FontAliasKey::Clone(void) const
{
  return new FontAliasKey(mString);
}
nsresult DeviceContextImpl::CreateFontAliasTable()
{
  nsresult result = NS_OK;

  if (nsnull == mFontAliasTable) {
    mFontAliasTable = new nsHashtable();
    if (nsnull != mFontAliasTable) {

      nsAutoString  times;              times.AssignLiteral("Times");
      nsAutoString  timesNewRoman;      timesNewRoman.AssignLiteral("Times New Roman");
      nsAutoString  timesRoman;         timesRoman.AssignLiteral("Times Roman");
      nsAutoString  arial;              arial.AssignLiteral("Arial");
      nsAutoString  helvetica;          helvetica.AssignLiteral("Helvetica");
      nsAutoString  courier;            courier.AssignLiteral("Courier");
      nsAutoString  courierNew;         courierNew.AssignLiteral("Courier New");
      nsAutoString  nullStr;

      AliasFont(times, timesNewRoman, timesRoman, PR_FALSE);
      AliasFont(timesRoman, timesNewRoman, times, PR_FALSE);
      AliasFont(timesNewRoman, timesRoman, times, PR_FALSE);
      AliasFont(arial, helvetica, nullStr, PR_FALSE);
      AliasFont(helvetica, arial, nullStr, PR_FALSE);
      AliasFont(courier, courierNew, nullStr, PR_TRUE);
      AliasFont(courierNew, courier, nullStr, PR_FALSE);
    }
    else {
      result = NS_ERROR_OUT_OF_MEMORY;
    }
  }
  return result;
}

nsresult DeviceContextImpl::AliasFont(const nsString& aFont, 
                                      const nsString& aAlias, const nsString& aAltAlias,
                                      PRBool aForceAlias)
{
  nsresult result = NS_OK;

  if (nsnull != mFontAliasTable) {
    if (aForceAlias || NS_FAILED(CheckFontExistence(aFont))) {
      if (NS_SUCCEEDED(CheckFontExistence(aAlias))) {
        nsString* entry = new nsString(aAlias);
        if (nsnull != entry) {
          FontAliasKey key(aFont);
          mFontAliasTable->Put(&key, entry);
        }
        else {
          result = NS_ERROR_OUT_OF_MEMORY;
        }
      }
      else if (!aAltAlias.IsEmpty() && NS_SUCCEEDED(CheckFontExistence(aAltAlias))) {
        nsString* entry = new nsString(aAltAlias);
        if (nsnull != entry) {
          FontAliasKey key(aFont);
          mFontAliasTable->Put(&key, entry);
        }
        else {
          result = NS_ERROR_OUT_OF_MEMORY;
        }
      }
    }
  }
  else {
    result = NS_ERROR_FAILURE;
  }
  return result;
}

NS_IMETHODIMP DeviceContextImpl::GetLocalFontName(const nsString& aFaceName, nsString& aLocalName,
                                                  PRBool& aAliased)
{
  nsresult result = NS_OK;

  if (nsnull == mFontAliasTable) {
    result = CreateFontAliasTable();
  }

  if (nsnull != mFontAliasTable) {
    FontAliasKey key(aFaceName);
    const nsString* alias = (const nsString*)mFontAliasTable->Get(&key);
    if (nsnull != alias) {
      aLocalName = *alias;
      aAliased = PR_TRUE;
    }
    else {
      aLocalName = aFaceName;
      aAliased = PR_FALSE;
    }
  }
  return result;
}

NS_IMETHODIMP DeviceContextImpl::FlushFontCache(void)
{
  if (nsnull != mFontCache)
    mFontCache->Flush();

  return NS_OK;
}

#ifdef NS_PRINT_PREVIEW
NS_IMETHODIMP DeviceContextImpl::SetAltDevice(nsIDeviceContext* aAltDC)
{
  mAltDC = aAltDC;

  // Can't use it if it isn't there
  if (aAltDC == nsnull) {
    mUseAltDC = kUseAltDCFor_NONE;
  }
  return NS_OK;
}

NS_IMETHODIMP DeviceContextImpl::SetUseAltDC(PRUint8 aValue, PRBool aOn)
{
  if (aOn) {
    mUseAltDC |= aValue;
  } else {
    mUseAltDC &= ~aValue;
  }
  return NS_OK;
}
#endif

/////////////////////////////////////////////////////////////

MOZ_DECL_CTOR_COUNTER(nsFontCache)

nsFontCache::nsFontCache()
{
  MOZ_COUNT_CTOR(nsFontCache);
  mContext = nsnull;
}

nsFontCache::~nsFontCache()
{
  MOZ_COUNT_DTOR(nsFontCache);
  Flush();
}

nsresult
nsFontCache::Init(nsIDeviceContext* aContext)
{
  NS_PRECONDITION(nsnull != aContext, "null ptr");
  // Note: we don't hold a reference to the device context, because it
  // holds a reference to us and we don't want circular references
  mContext = aContext;
  return NS_OK;
}

nsresult
nsFontCache::GetDeviceContext(nsIDeviceContext *&aContext) const
{
  aContext = mContext;
  NS_IF_ADDREF(aContext);
  return NS_OK;
}

nsresult
nsFontCache::GetMetricsFor(const nsFont& aFont, nsIAtom* aLangGroup,
  nsIFontMetrics *&aMetrics)
{
  // First check our cache
  // start from the end, which is where we put the most-recent-used element

  nsIFontMetrics* fm;
  PRInt32 n = mFontMetrics.Count() - 1;
  for (PRInt32 i = n; i >= 0; --i) {
    fm = NS_STATIC_CAST(nsIFontMetrics*, mFontMetrics[i]);
    if (fm->Font().Equals(aFont)) {
      nsCOMPtr<nsIAtom> langGroup;
      fm->GetLangGroup(getter_AddRefs(langGroup));
      if (aLangGroup == langGroup.get()) {
        if (i != n) {
          // promote it to the end of the cache
          mFontMetrics.MoveElement(i, n);
        }
        NS_ADDREF(aMetrics = fm);
        return NS_OK;
      }
    }
  }

  // It's not in the cache. Get font metrics and then cache them.

  aMetrics = nsnull;
  nsresult rv = CreateFontMetricsInstance(&fm);
  if (NS_FAILED(rv)) return rv;
  rv = fm->Init(aFont, aLangGroup, mContext);
  if (NS_SUCCEEDED(rv)) {
    // the mFontMetrics list has the "head" at the end, because append is
    // cheaper than insert
    mFontMetrics.AppendElement(fm);
    aMetrics = fm;
    NS_ADDREF(aMetrics);
    return NS_OK;
  }
  fm->Destroy();
  NS_RELEASE(fm);

  // One reason why Init() fails is because the system is running out of resources. 
  // e.g., on Win95/98 only a very limited number of GDI objects are available.
  // Compact the cache and try again.

  Compact();
  rv = CreateFontMetricsInstance(&fm);
  if (NS_FAILED(rv)) return rv;
  rv = fm->Init(aFont, aLangGroup, mContext);
  if (NS_SUCCEEDED(rv)) {
    mFontMetrics.AppendElement(fm);
    aMetrics = fm;
    NS_ADDREF(aMetrics);
    return NS_OK;
  }
  fm->Destroy();
  NS_RELEASE(fm);

  // could not setup a new one, send an old one (XXX search a "best match"?)

  n = mFontMetrics.Count() - 1; // could have changed in Compact()
  if (n >= 0) {
    aMetrics = NS_STATIC_CAST(nsIFontMetrics*, mFontMetrics[n]);
    NS_ADDREF(aMetrics);
    return NS_OK;
  }

  NS_POSTCONDITION(NS_SUCCEEDED(rv), "font metrics should not be null - bug 136248");
  return rv;
}

/* PostScript and Xprint module may override this method to create 
 * nsIFontMetrics objects with their own classes 
 */
nsresult
nsFontCache::CreateFontMetricsInstance(nsIFontMetrics** fm)
{
  static NS_DEFINE_CID(kFontMetricsCID, NS_FONT_METRICS_CID);
  return CallCreateInstance(kFontMetricsCID, fm);
}

nsresult nsFontCache::FontMetricsDeleted(const nsIFontMetrics* aFontMetrics)
{
  mFontMetrics.RemoveElement((void*)aFontMetrics);
  return NS_OK;
}

nsresult nsFontCache::Compact()
{
  // Need to loop backward because the running element can be removed on the way
  for (PRInt32 i = mFontMetrics.Count()-1; i >= 0; --i) {
    nsIFontMetrics* fm = NS_STATIC_CAST(nsIFontMetrics*, mFontMetrics[i]);
    nsIFontMetrics* oldfm = fm;
    // Destroy() isn't here because we want our device context to be notified
    NS_RELEASE(fm); // this will reset fm to nsnull
    // if the font is really gone, it would have called back in
    // FontMetricsDeleted() and would have removed itself
    if (mFontMetrics.IndexOf(oldfm) >= 0) {
      // nope, the font is still there, so let's hold onto it too
      NS_ADDREF(oldfm);
    }
  }
  return NS_OK;
}

nsresult nsFontCache::Flush()
{
  for (PRInt32 i = mFontMetrics.Count()-1; i >= 0; --i) {
    nsIFontMetrics* fm = NS_STATIC_CAST(nsIFontMetrics*, mFontMetrics[i]);
    // Destroy() will unhook our device context from the fm so that we won't
    // waste time in triggering the notification of FontMetricsDeleted()
    // in the subsequent release
    fm->Destroy();
    NS_RELEASE(fm);
  }

  mFontMetrics.Clear();

  return NS_OK;
}