Beispiel #1
0
NS_IMETHODIMP
nsWindowsHooks::SetImageAsWallpaper(nsIDOMElement* aElement, PRBool aUseBackground)
{
  nsresult rv;
  
  nsCOMPtr<gfxIImageFrame> gfxFrame;
  if (aUseBackground) {
    // XXX write background loading stuff!
  } else {
    nsCOMPtr<nsIImageLoadingContent> imageContent = do_QueryInterface(aElement, &rv);
    if (!imageContent) return rv;
    
    // get the image container
    nsCOMPtr<imgIRequest> request;
    rv = imageContent->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
                                  getter_AddRefs(request));
    if (!request) return rv;
    nsCOMPtr<imgIContainer> container;
    rv = request->GetImage(getter_AddRefs(container));
    if (!container)
      return NS_ERROR_FAILURE;
    
    // get the current frame, which holds the image data
    container->GetCurrentFrame(getter_AddRefs(gfxFrame));
  }  
  
  if (!gfxFrame)
    return NS_ERROR_FAILURE;

  // get the profile root directory
  nsCOMPtr<nsIFile> file;
  rv = NS_GetSpecialDirectory(NS_APP_APPLICATION_REGISTRY_DIR,
                              getter_AddRefs(file));
  NS_ENSURE_SUCCESS(rv, rv);
  
  // get the product brand name from localized strings
  nsXPIDLString brandName, fileLeafName;
  nsCOMPtr<nsIStringBundleService> bundleService =
           do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
  NS_ENSURE_TRUE(bundleService, rv);

  // get the product brand name from localized strings
  nsCOMPtr<nsIStringBundle> bundle;
  rv = bundleService->CreateBundle("chrome://branding/locale/brand.properties",
                                   getter_AddRefs(bundle));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = bundle->GetStringFromName(NS_LITERAL_STRING("brandShortName").get(),
                                 getter_Copies(brandName));
  NS_ENSURE_SUCCESS(rv, rv);

  // get the file leaf name from localized strings (e.g. "%S Wallpaper.bmp")
  rv = bundleService->CreateBundle("chrome://global-platform/locale/nsWindowsHooks.properties",
                                   getter_AddRefs(bundle));
  NS_ENSURE_SUCCESS(rv, rv);

  const PRUnichar* stringArray[] = { brandName.get() };

  rv = bundle->FormatStringFromName(NS_LITERAL_STRING("wallpaperFile").get(),
                                    stringArray, NS_ARRAY_LENGTH(stringArray),
                                    getter_Copies(fileLeafName));
  NS_ENSURE_SUCCESS(rv, rv);
  
  // eventually, the path is %APPDATA%\Mozilla\Mozilla Wallpaper.bmp
  fileLeafName.AppendLiteral(".bmp");
  rv = file->Append(fileLeafName);
  NS_ENSURE_SUCCESS(rv, rv);

  // write the bitmap to the target file
  rv = WriteBitmap(file, gfxFrame);
  NS_ENSURE_SUCCESS(rv, rv);

  // set it as the system wallpaper
  nsCAutoString nativePath;
  rv = file->GetNativePath(nativePath);
  NS_ENSURE_SUCCESS(rv, rv);
  
  ::SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (PVOID) nativePath.get(),
                         SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);

  return rv;
}
Beispiel #2
0
void
test_UTFStrings()
{
    nsCOMPtr<mozIStorageConnection> db(getMemoryDatabase());

    // Create table with a single string column.
    (void)db->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
                                   "CREATE TABLE test (str STRING)"
                               ));

    // Create statements to INSERT and SELECT the string.
    nsCOMPtr<mozIStorageStatement> insert, select;
    (void)db->CreateStatement(NS_LITERAL_CSTRING(
                                  "INSERT INTO test (str) VALUES (?1)"
                              ), getter_AddRefs(insert));
    (void)db->CreateStatement(NS_LITERAL_CSTRING(
                                  "SELECT str FROM test"
                              ), getter_AddRefs(select));

    // Roundtrip a UTF8 string through the table, using UTF8 input and output.
    static const char sCharArray[] =
        "I'm a \xc3\xbb\xc3\xbc\xc3\xa2\xc3\xa4\xc3\xa7 UTF8 string!";
    nsCAutoString insertedUTF8(sCharArray, NS_ARRAY_LENGTH(sCharArray) - 1);
    do_check_true(insertedUTF8.Length() == NS_ARRAY_LENGTH(sCharArray) - 1);
    NS_ConvertUTF8toUTF16 insertedUTF16(insertedUTF8);
    do_check_true(insertedUTF8 == NS_ConvertUTF16toUTF8(insertedUTF16));
    {
        mozStorageStatementScoper scoper(insert);
        bool hasResult;
        do_check_true(NS_SUCCEEDED(insert->BindUTF8StringByIndex(0, insertedUTF8)));
        do_check_true(NS_SUCCEEDED(insert->ExecuteStep(&hasResult)));
        do_check_false(hasResult);
    }

    {
        nsCAutoString result;

        mozStorageStatementScoper scoper(select);
        bool hasResult;
        do_check_true(NS_SUCCEEDED(select->ExecuteStep(&hasResult)));
        do_check_true(hasResult);
        do_check_true(NS_SUCCEEDED(select->GetUTF8String(0, result)));

        do_check_true(result == insertedUTF8);
    }

    // Use UTF8 input and UTF16 output.
    {
        nsAutoString result;

        mozStorageStatementScoper scoper(select);
        bool hasResult;
        do_check_true(NS_SUCCEEDED(select->ExecuteStep(&hasResult)));
        do_check_true(hasResult);
        do_check_true(NS_SUCCEEDED(select->GetString(0, result)));

        do_check_true(result == insertedUTF16);
    }

    (void)db->ExecuteSimpleSQL(NS_LITERAL_CSTRING("DELETE FROM test"));

    // Roundtrip the same string using UTF16 input and UTF8 output.
    {
        mozStorageStatementScoper scoper(insert);
        bool hasResult;
        do_check_true(NS_SUCCEEDED(insert->BindStringByIndex(0, insertedUTF16)));
        do_check_true(NS_SUCCEEDED(insert->ExecuteStep(&hasResult)));
        do_check_false(hasResult);
    }

    {
        nsCAutoString result;

        mozStorageStatementScoper scoper(select);
        bool hasResult;
        do_check_true(NS_SUCCEEDED(select->ExecuteStep(&hasResult)));
        do_check_true(hasResult);
        do_check_true(NS_SUCCEEDED(select->GetUTF8String(0, result)));

        do_check_true(result == insertedUTF8);
    }

    // Use UTF16 input and UTF16 output.
    {
        nsAutoString result;

        mozStorageStatementScoper scoper(select);
        bool hasResult;
        do_check_true(NS_SUCCEEDED(select->ExecuteStep(&hasResult)));
        do_check_true(hasResult);
        do_check_true(NS_SUCCEEDED(select->GetString(0, result)));

        do_check_true(result == insertedUTF16);
    }

    (void)db->ExecuteSimpleSQL(NS_LITERAL_CSTRING("DELETE FROM test"));
}
nsresult
nsAbManager::ExportDirectoryToDelimitedText(nsIAbDirectory *aDirectory, const char *aDelim, PRUint32 aDelimLen, nsILocalFile *aLocalFile)
{
  nsCOMPtr <nsISimpleEnumerator> cardsEnumerator;
  nsCOMPtr <nsIAbCard> card;

  nsresult rv;

  nsCOMPtr <nsIOutputStream> outputStream;
  rv = MsgNewBufferedFileOutputStream(getter_AddRefs(outputStream),
                                      aLocalFile,
                                      PR_CREATE_FILE | PR_WRONLY | PR_TRUNCATE,
                                      0664);

  // the desired file may be read only
  if (NS_FAILED(rv))
    return rv;

  PRUint32 i;
  PRUint32 writeCount;
  PRUint32 length;

  nsCOMPtr<nsIStringBundleService> bundleService = do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIStringBundle> bundle;
  rv = bundleService->CreateBundle("chrome://messenger/locale/importMsgs.properties", getter_AddRefs(bundle));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCString revisedName;
  nsString columnName;

  for (i = 0; i < NS_ARRAY_LENGTH(EXPORT_ATTRIBUTES_TABLE); i++) {
    if (EXPORT_ATTRIBUTES_TABLE[i].plainTextStringID != 0) {

      // We don't need to truncate the string here as getter_Copies will
      // do that for us.
      if (NS_FAILED(bundle->GetStringFromID(EXPORT_ATTRIBUTES_TABLE[i].plainTextStringID, getter_Copies(columnName))))
        columnName.AppendInt(EXPORT_ATTRIBUTES_TABLE[i].plainTextStringID);

      rv = nsMsgI18NConvertFromUnicode(nsMsgI18NFileSystemCharset(),
                                       columnName, revisedName);
      NS_ENSURE_SUCCESS(rv,rv);

      rv = outputStream->Write(revisedName.get(),
                               revisedName.Length(),
                               &writeCount);
      NS_ENSURE_SUCCESS(rv,rv);

      if (revisedName.Length() != writeCount)
        return NS_ERROR_FAILURE;

      if (i < NS_ARRAY_LENGTH(EXPORT_ATTRIBUTES_TABLE) - 1) {
        rv = outputStream->Write(aDelim, aDelimLen, &writeCount);
        NS_ENSURE_SUCCESS(rv,rv);

        if (aDelimLen != writeCount)
          return NS_ERROR_FAILURE;
      }
    }
  }
  rv = outputStream->Write(MSG_LINEBREAK, MSG_LINEBREAK_LEN, &writeCount);
  NS_ENSURE_SUCCESS(rv,rv);
  if (MSG_LINEBREAK_LEN != writeCount)
    return NS_ERROR_FAILURE;

  rv = aDirectory->GetChildCards(getter_AddRefs(cardsEnumerator));
  if (NS_SUCCEEDED(rv) && cardsEnumerator) {
    nsCOMPtr<nsISupports> item;
    bool more;
    while (NS_SUCCEEDED(cardsEnumerator->HasMoreElements(&more)) && more) {
      rv = cardsEnumerator->GetNext(getter_AddRefs(item));
      if (NS_SUCCEEDED(rv)) {
        nsCOMPtr <nsIAbCard> card = do_QueryInterface(item, &rv);
        NS_ENSURE_SUCCESS(rv,rv);

        bool isMailList;
        rv = card->GetIsMailList(&isMailList);
        NS_ENSURE_SUCCESS(rv,rv);


        if (isMailList) {
          // .tab, .txt and .csv aren't able to export mailing lists
          // use LDIF for that.
        }
        else {
          nsString value;
          nsCString valueCStr;

          for (i = 0; i < NS_ARRAY_LENGTH(EXPORT_ATTRIBUTES_TABLE); i++) {
            if (EXPORT_ATTRIBUTES_TABLE[i].plainTextStringID != 0) {
              rv = card->GetPropertyAsAString(EXPORT_ATTRIBUTES_TABLE[i].abPropertyName, value);
              if (NS_FAILED(rv))
                value.Truncate();

              // If a string contains at least one comma, tab or double quote then
              // we need to quote the entire string. Also if double quote is part
              // of the string we need to quote the double quote(s) as well.
              nsAutoString newValue(value);
              bool needsQuotes = false;
              if(newValue.FindChar('"') != -1)
              {
                needsQuotes = PR_TRUE;
                
                PRInt32 match = 0;
                PRUint32 offset = 0;
                nsString oldSubstr = NS_LITERAL_STRING("\"");
                nsString newSubstr = NS_LITERAL_STRING("\"\""); 
                while (offset < newValue.Length()) {
                    match = newValue.Find(oldSubstr, offset);
                    if (match == -1)
                        break;

                    newValue.Replace(offset + match, oldSubstr.Length(), newSubstr);
                    offset += (match + newSubstr.Length());
                }
              }
              if (!needsQuotes && (newValue.FindChar(',') != -1 || newValue.FindChar('\x09') != -1))
                needsQuotes = PR_TRUE;

              // Make sure we quote if containing CR/LF.
              if (newValue.FindChar('\r') != -1 ||
                  newValue.FindChar('\n') != -1)
                  needsQuotes = PR_TRUE;

              if (needsQuotes)
              {
                newValue.Insert(NS_LITERAL_STRING("\""), 0);
                newValue.AppendLiteral("\"");
              }

              rv = nsMsgI18NConvertFromUnicode(nsMsgI18NFileSystemCharset(),
                                               newValue, valueCStr);
              NS_ENSURE_SUCCESS(rv,rv);

              if (NS_FAILED(rv)) {
                NS_ERROR("failed to convert string to system charset.  use LDIF");
                valueCStr = "?";
              }

              length = valueCStr.Length();
              if (length) {
                rv = outputStream->Write(valueCStr.get(), length, &writeCount);
                NS_ENSURE_SUCCESS(rv,rv);
                if (length != writeCount)
                  return NS_ERROR_FAILURE;
              }
              valueCStr = "";
            }
            else {
              // something we don't support for the current export
              // for example, .tab doesn't export preferred html format
              continue; // go to next field
            }

            if (i < NS_ARRAY_LENGTH(EXPORT_ATTRIBUTES_TABLE) - 1) {
              rv = outputStream->Write(aDelim, aDelimLen, &writeCount);
              NS_ENSURE_SUCCESS(rv,rv);
              if (aDelimLen != writeCount)
                return NS_ERROR_FAILURE;
            }
          }

          // write out the linebreak that separates the cards
          rv = outputStream->Write(MSG_LINEBREAK, MSG_LINEBREAK_LEN, &writeCount);
          NS_ENSURE_SUCCESS(rv,rv);
          if (MSG_LINEBREAK_LEN != writeCount)
            return NS_ERROR_FAILURE;
        }
      }
    }
  }

  rv = outputStream->Flush();
  NS_ENSURE_SUCCESS(rv,rv);

  rv = outputStream->Close();
  NS_ENSURE_SUCCESS(rv,rv);
  return NS_OK;
}
nsSVGElement::IntegerAttributesInfo
nsSVGFilterElement::GetIntegerInfo()
{
  return IntegerAttributesInfo(mIntegerAttributes, sIntegerInfo,
                               NS_ARRAY_LENGTH(sIntegerInfo));
}
nsSVGElement::StringAttributesInfo
nsSVGFilterElement::GetStringInfo()
{
  return StringAttributesInfo(mStringAttributes, sStringInfo,
                              NS_ARRAY_LENGTH(sStringInfo));
}
void nsCSSPseudoClasses::AddRefAtoms()
{
  NS_RegisterStaticAtoms(CSSPseudoClasses_info,
                         NS_ARRAY_LENGTH(CSSPseudoClasses_info));
}
Beispiel #7
0
NS_IMETHODIMP
nsMozIconURI::SetSpec(const nsACString &aSpec)
{
  nsresult rv;
  nsCOMPtr<nsIIOService> ioService (do_GetService(NS_IOSERVICE_CONTRACTID, &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCAutoString scheme;
  rv = ioService->ExtractScheme(aSpec, scheme);
  NS_ENSURE_SUCCESS(rv, rv);

  if (strcmp("moz-icon", scheme.get()) != 0) 
    return NS_ERROR_MALFORMED_URI;

  nsCAutoString sizeString;
  nsCAutoString stateString;
  nsCAutoString mozIconPath(aSpec);

  // guaranteed to exist!
  const char *path = strchr(mozIconPath.get(), ':') + 1;
  const char *question = strchr(mozIconPath.get(), NS_MOZ_ICON_DELIMITER);

  if (!question) // no size or content type specified
  {
    mDummyFilePath.Assign(path);
  }
  else
  {
    mDummyFilePath.Assign(Substring(path, question));

    // fill in any size and content type values...
    extractAttributeValue(question, "size=", sizeString);
    extractAttributeValue(question, "state=", stateString);
    extractAttributeValue(question, "contentType=", mContentType);
  }

  if (!sizeString.IsEmpty())
  {
    const char *sizeStr = sizeString.get();
    for (PRUint32 i = 0; i < NS_ARRAY_LENGTH(kSizeStrings); i++)
    {
      if (PL_strcasecmp(sizeStr, kSizeStrings[i]) == 0)
      {
        mIconSize = i;
        break;
      }
    }
  }

  if (!stateString.IsEmpty())
  {
    const char *stateStr = stateString.get();
    for (PRUint32 i = 0; i < NS_ARRAY_LENGTH(kStateStrings); i++)
    {
      if (PL_strcasecmp(stateStr, kStateStrings[i]) == 0)
      {
        mIconState = i;
        break;
      }
    }
  }

  // Okay now we have a bit of a hack here...filePath can have three forms:
  // (1) file://<some valid platform specific file url>
  // (2) //<some dummy file with an extension>
  // (3) stock/<icon-identifier>
  // We need to determine which case we are and behave accordingly...
  if (mDummyFilePath.Length() > 2)
  {
    if (!strncmp("//stock/", mDummyFilePath.get(), 8))
    {
      // we have a stock icon
      mStockIcon = Substring(mDummyFilePath, 8);
    }
    else
    {
      if (!strncmp("//", mDummyFilePath.get(), 2))// must not have a url here..
      {
        // in this case the string looks like //somefile.html or // somefile.extension. So throw away the "//" part
        // and remember the rest in mDummyFilePath
        mDummyFilePath.Cut(0, 2); // cut the first 2 bytes....
      }
      if (!strncmp("file://", mDummyFilePath.get(), 7))
      { 
        // we have a file url, let the IOService normalize it
        nsCOMPtr<nsIURI> tmpURI;
        rv = ioService->NewURI(mDummyFilePath, nsnull, nsnull, getter_AddRefs(tmpURI));
        if (NS_SUCCEEDED(rv) && tmpURI)
        {
          mFileIcon = tmpURI;
        }
      }
      if (!sizeString.IsEmpty())
      {
        PRInt32 sizeValue = atoi(sizeString.get());
        // if the size value we got back is > 0 then use it
        if (sizeValue)
          mSize = sizeValue;
      }
    }
  }
  else
    rv = NS_ERROR_MALFORMED_URI; // they didn't include a file path...
  return rv;
}
void
nsClipboard::SelectionGetEvent(GtkClipboard     *aClipboard,
                               GtkSelectionData *aSelectionData)
{
    // Someone has asked us to hand them something.  The first thing
    // that we want to do is see if that something includes text.  If
    // it does, try to give it text/unicode after converting it to
    // utf-8.

    PRInt32 whichClipboard;

    // which clipboard?
    if (aSelectionData->selection == GDK_SELECTION_PRIMARY)
        whichClipboard = kSelectionClipboard;
    else if (aSelectionData->selection == GDK_SELECTION_CLIPBOARD)
        whichClipboard = kGlobalClipboard;
    else
        return; // THAT AIN'T NO CLIPBOARD I EVER HEARD OF

    nsCOMPtr<nsITransferable> trans = GetTransferable(whichClipboard);
    if (!trans) {
      // We have nothing to serve
#ifdef DEBUG_CLIPBOARD
      printf("nsClipboard::SelectionGetEvent() - %s clipboard is empty!\n",
             whichClipboard == kSelectionClipboard ? "Selection" : "Global");
#endif
      return;
    }

    nsresult rv;
    nsCOMPtr<nsISupports> item;
    PRUint32 len;

    // Check to see if the selection data includes any of the string
    // types that we support.
    if (aSelectionData->target == gdk_atom_intern ("STRING", FALSE) ||
        aSelectionData->target == gdk_atom_intern ("TEXT", FALSE) ||
        aSelectionData->target == gdk_atom_intern ("COMPOUND_TEXT", FALSE) ||
        aSelectionData->target == gdk_atom_intern ("UTF8_STRING", FALSE)) {
        // Try to convert our internal type into a text string.  Get
        // the transferable for this clipboard and try to get the
        // text/unicode type for it.
        rv = trans->GetTransferData("text/unicode", getter_AddRefs(item),
                                    &len);
        if (!item || NS_FAILED(rv))
            return;
        
        nsCOMPtr<nsISupportsString> wideString;
        wideString = do_QueryInterface(item);
        if (!wideString)
            return;

        nsAutoString ucs2string;
        wideString->GetData(ucs2string);
        char *utf8string = ToNewUTF8String(ucs2string);
        if (!utf8string)
            return;
        
        gtk_selection_data_set_text (aSelectionData, utf8string,
                                     strlen(utf8string));

        nsMemory::Free(utf8string);
        return;
    }

    // Check to see if the selection data is an image type
    if (gtk_targets_include_image(&aSelectionData->target, 1, TRUE)) {
        // Look through our transfer data for the image
        static const char* const imageMimeTypes[] = {
            kNativeImageMime, kPNGImageMime, kJPEGImageMime, kGIFImageMime };
        nsCOMPtr<nsISupports> item;
        PRUint32 len;
        nsCOMPtr<nsISupportsInterfacePointer> ptrPrimitive;
        for (PRUint32 i = 0; !ptrPrimitive && i < NS_ARRAY_LENGTH(imageMimeTypes); i++) {
            rv = trans->GetTransferData(imageMimeTypes[i], getter_AddRefs(item), &len);
            ptrPrimitive = do_QueryInterface(item);
        }
        if (!ptrPrimitive)
            return;

        nsCOMPtr<nsISupports> primitiveData;
        ptrPrimitive->GetData(getter_AddRefs(primitiveData));
        nsCOMPtr<imgIContainer> image(do_QueryInterface(primitiveData));
        if (!image) // Not getting an image for an image mime type!?
            return;

        GdkPixbuf* pixbuf = nsImageToPixbuf::ImageToPixbuf(image);
        if (!pixbuf)
            return;

        gtk_selection_data_set_pixbuf(aSelectionData, pixbuf);
        g_object_unref(pixbuf);
        return;
    }

    // Try to match up the selection data target to something our
    // transferable provides.
    gchar *target_name = gdk_atom_name(aSelectionData->target);
    if (!target_name)
        return;

    rv = trans->GetTransferData(target_name, getter_AddRefs(item), &len);
    // nothing found?
    if (!item || NS_FAILED(rv)) {
        g_free(target_name);
        return;
    }

    void *primitive_data = nsnull;
    nsPrimitiveHelpers::CreateDataFromPrimitive(target_name, item,
                                                &primitive_data, len);

    if (primitive_data) {
        // Check to see if the selection data is text/html
        if (aSelectionData->target == gdk_atom_intern (kHTMLMime, FALSE)) {
            /*
             * "text/html" can be encoded UCS2. It is recommended that
             * documents transmitted as UCS2 always begin with a ZERO-WIDTH
             * NON-BREAKING SPACE character (hexadecimal FEFF, also called
             * Byte Order Mark (BOM)). Adding BOM can help other app to
             * detect mozilla use UCS2 encoding when copy-paste.
             */
            guchar *buffer = (guchar *)
                    nsMemory::Alloc((len * sizeof(guchar)) + sizeof(PRUnichar));
            if (!buffer)
                return;
            PRUnichar prefix = 0xFEFF;
            memcpy(buffer, &prefix, sizeof(prefix));
            memcpy(buffer + sizeof(prefix), primitive_data, len);
            nsMemory::Free((guchar *)primitive_data);
            primitive_data = (guchar *)buffer;
            len += sizeof(prefix);
        }
  
        gtk_selection_data_set(aSelectionData, aSelectionData->target,
                               8, /* 8 bits in a unit */
                               (const guchar *)primitive_data, len);
        nsMemory::Free(primitive_data);
    }

    g_free(target_name);
                           
}
Beispiel #9
0
  page really needs chrome privileges. Security review is required
  before adding new map entries with dropChromePrivs == PR_FALSE.
 */
static RedirEntry kRedirMap[] = {
    { "credits", "http://www.mozilla.org/credits/", PR_TRUE },
    { "mozilla", "chrome://global/content/mozilla.xhtml", PR_TRUE },
    { "plugins", "chrome://global/content/plugins.html", PR_FALSE },
    { "config", "chrome://global/content/config.xul", PR_FALSE },
    { "logo", "chrome://global/content/logo.gif", PR_TRUE },
    { "buildconfig", "chrome://global/content/buildconfig.html", PR_TRUE },
    { "license", "chrome://global/content/license.html", PR_TRUE },
    { "licence", "chrome://global/content/license.html", PR_TRUE },
    { "about", "chrome://global/content/aboutAbout.html", PR_FALSE },
    { "neterror", "chrome://global/content/netError.xhtml", PR_TRUE }
};
static const int kRedirTotal = NS_ARRAY_LENGTH(kRedirMap);

NS_IMETHODIMP
nsAboutRedirector::NewChannel(nsIURI *aURI, nsIChannel **result)
{
    NS_ENSURE_ARG_POINTER(aURI);
    NS_ASSERTION(result, "must not be null");

    nsresult rv;

    nsCAutoString path;
    rv = NS_GetAboutModuleName(aURI, path);
    if (NS_FAILED(rv))
        return rv;

    nsCOMPtr<nsIIOService> ioService = do_GetIOService(&rv);
    eNameOkFromChildren,
    eNoValue,
    eActivateAction, // XXX: should expose second 'expand/collapse' action based
                     // on states
    kNoReqStates,
    {&nsAccessibilityAtoms::aria_selected, kBoolState, nsIAccessibleStates::STATE_SELECTED | nsIAccessibleStates::STATE_SELECTABLE},
    {&nsAccessibilityAtoms::aria_selected, "false", nsIAccessibleStates::STATE_SELECTABLE},
    {&nsAccessibilityAtoms::aria_expanded, kBoolState, nsIAccessibleStates::STATE_EXPANDED},
    {&nsAccessibilityAtoms::aria_expanded, "false", nsIAccessibleStates::STATE_COLLAPSED},
    {&nsAccessibilityAtoms::aria_checked, kBoolState, nsIAccessibleStates::STATE_CHECKED | nsIAccessibleStates::STATE_CHECKABLE},
    {&nsAccessibilityAtoms::aria_checked, "mixed", nsIAccessibleStates::STATE_MIXED | nsIAccessibleStates::STATE_CHECKABLE},
    {&nsAccessibilityAtoms::aria_checked, "false", nsIAccessibleStates::STATE_CHECKABLE},
  },
};

PRUint32 nsARIAMap::gWAIRoleMapLength = NS_ARRAY_LENGTH(nsARIAMap::gWAIRoleMap);

nsRoleMapEntry nsARIAMap::gLandmarkRoleMap = {
  "",
  nsIAccessibleRole::ROLE_NOTHING,
  eNameLabelOrTitle,
  eNoValue,
  eNoAction,
  kNoReqStates,
  kEndEntry
};

nsRoleMapEntry nsARIAMap::gEmptyRoleMap = {
  "",
  nsIAccessibleRole::ROLE_NOTHING,
  eNameLabelOrTitle,
#include "nsCUPSShim.h"
#include "prlink.h"


// List of symbols to find in libcups. Must match symAddr[] defined in Init().
// Making this an array of arrays instead of pointers allows storing the
// whole thing in read-only memory.
static const char gSymName[][sizeof("cupsPrintFile")] = {
    { "cupsAddOption" },
    { "cupsFreeDests" },
    { "cupsGetDest" },
    { "cupsGetDests" },
    { "cupsPrintFile" },
    { "cupsTempFd" },
};
static const int gSymNameCt = NS_ARRAY_LENGTH(gSymName);


bool
nsCUPSShim::Init()
{
    mCupsLib = PR_LoadLibrary("libcups.so.2");
    if (!mCupsLib)
        return false;

    // List of symbol pointers. Must match gSymName[] defined above.
    void **symAddr[] = {
        (void **)&mCupsAddOption,
        (void **)&mCupsFreeDests,
        (void **)&mCupsGetDest,
        (void **)&mCupsGetDests,
// Create a CTFontRef, with the Common Ligatures feature disabled
CTFontRef
gfxCoreTextShaper::CreateCTFontWithDisabledLigatures(CGFloat aSize)
{
    if (sDisableLigaturesDescriptor == NULL) {
        // initialize cached descriptor to turn off the Common Ligatures feature
        SInt16 val = kLigaturesType;
        CFNumberRef ligaturesType =
            ::CFNumberCreate(kCFAllocatorDefault,
                             kCFNumberSInt16Type,
                             &val);
        val = kCommonLigaturesOffSelector;
        CFNumberRef commonLigaturesOffSelector =
            ::CFNumberCreate(kCFAllocatorDefault,
                             kCFNumberSInt16Type,
                             &val);

        const CFTypeRef keys[]   = { kCTFontFeatureTypeIdentifierKey,
                                     kCTFontFeatureSelectorIdentifierKey };
        const CFTypeRef values[] = { ligaturesType,
                                     commonLigaturesOffSelector };
        CFDictionaryRef featureSettingDict =
            ::CFDictionaryCreate(kCFAllocatorDefault,
                                 (const void **) keys,
                                 (const void **) values,
                                 NS_ARRAY_LENGTH(keys),
                                 &kCFTypeDictionaryKeyCallBacks,
                                 &kCFTypeDictionaryValueCallBacks);
        ::CFRelease(ligaturesType);
        ::CFRelease(commonLigaturesOffSelector);

        CFArrayRef featuresArray =
            ::CFArrayCreate(kCFAllocatorDefault,
                            (const void **) &featureSettingDict,
                            1,
                            &kCFTypeArrayCallBacks);
        ::CFRelease(featureSettingDict);

        CFDictionaryRef attributesDict =
            ::CFDictionaryCreate(kCFAllocatorDefault,
                                 (const void **) &kCTFontFeatureSettingsAttribute,
                                 (const void **) &featuresArray,
                                 1, // count of keys & values
                                 &kCFTypeDictionaryKeyCallBacks,
                                 &kCFTypeDictionaryValueCallBacks);
        ::CFRelease(featuresArray);

        sDisableLigaturesDescriptor =
            ::CTFontDescriptorCreateCopyWithAttributes(GetDefaultFeaturesDescriptor(),
                                                       attributesDict);
        ::CFRelease(attributesDict);
    }

    if (gfxMacPlatformFontList::UseATSFontEntry()) {
        ATSFontEntry *fe = static_cast<ATSFontEntry*>(mFont->GetFontEntry());
        return ::CTFontCreateWithPlatformFont(fe->GetATSFontRef(), aSize, NULL,
                                              sDisableLigaturesDescriptor);
    }

    gfxMacFont *f = static_cast<gfxMacFont*>(mFont);
    return ::CTFontCreateWithGraphicsFont(f->GetCGFontRef(), aSize, NULL,
                                          sDisableLigaturesDescriptor);
}
// Construct the font attribute descriptor that we'll apply by default when creating a CTFontRef.
// This will turn off line-edge swashes by default, because we don't know the actual line breaks
// when doing glyph shaping.
void
gfxCoreTextShaper::CreateDefaultFeaturesDescriptor()
{
    if (sDefaultFeaturesDescriptor != NULL) {
        return;
    }

    SInt16 val = kSmartSwashType;
    CFNumberRef swashesType =
        ::CFNumberCreate(kCFAllocatorDefault,
                         kCFNumberSInt16Type,
                         &val);
    val = kLineInitialSwashesOffSelector;
    CFNumberRef lineInitialsOffSelector =
        ::CFNumberCreate(kCFAllocatorDefault,
                         kCFNumberSInt16Type,
                         &val);

    CFTypeRef keys[]   = { kCTFontFeatureTypeIdentifierKey,
                           kCTFontFeatureSelectorIdentifierKey };
    CFTypeRef values[] = { swashesType,
                           lineInitialsOffSelector };
    CFDictionaryRef featureSettings[2];
    featureSettings[0] =
        ::CFDictionaryCreate(kCFAllocatorDefault,
                             (const void **) keys,
                             (const void **) values,
                             NS_ARRAY_LENGTH(keys),
                             &kCFTypeDictionaryKeyCallBacks,
                             &kCFTypeDictionaryValueCallBacks);
    ::CFRelease(lineInitialsOffSelector);

    val = kLineFinalSwashesOffSelector;
    CFNumberRef lineFinalsOffSelector =
        ::CFNumberCreate(kCFAllocatorDefault,
                         kCFNumberSInt16Type,
                         &val);
    values[1] = lineFinalsOffSelector;
    featureSettings[1] =
        ::CFDictionaryCreate(kCFAllocatorDefault,
                             (const void **) keys,
                             (const void **) values,
                             NS_ARRAY_LENGTH(keys),
                             &kCFTypeDictionaryKeyCallBacks,
                             &kCFTypeDictionaryValueCallBacks);
    ::CFRelease(lineFinalsOffSelector);
    ::CFRelease(swashesType);

    CFArrayRef featuresArray =
        ::CFArrayCreate(kCFAllocatorDefault,
                        (const void **) featureSettings,
                        NS_ARRAY_LENGTH(featureSettings),
                        &kCFTypeArrayCallBacks);
    ::CFRelease(featureSettings[0]);
    ::CFRelease(featureSettings[1]);

    const CFTypeRef attrKeys[]   = { kCTFontFeatureSettingsAttribute };
    const CFTypeRef attrValues[] = { featuresArray };
    CFDictionaryRef attributesDict =
        ::CFDictionaryCreate(kCFAllocatorDefault,
                             (const void **) attrKeys,
                             (const void **) attrValues,
                             NS_ARRAY_LENGTH(attrKeys),
                             &kCFTypeDictionaryKeyCallBacks,
                             &kCFTypeDictionaryValueCallBacks);
    ::CFRelease(featuresArray);

    sDefaultFeaturesDescriptor =
        ::CTFontDescriptorCreateWithAttributes(attributesDict);
    ::CFRelease(attributesDict);
}
/******************************
 *  InitializeJavaGlobals
 ******************************/
PRBool
InitializeJavaGlobals(JNIEnv *env)
{
  if (gJavaXPCOMInitialized)
    return PR_TRUE;

  // Save pointer to JavaVM, which is valid across threads.
  jint rc = env->GetJavaVM(&gCachedJVM);
  if (rc != 0) {
    NS_WARNING("Failed to get JavaVM");
    goto init_error;
  }

  jclass clazz;
  if (!(clazz = env->FindClass("java/lang/System")) ||
      !(systemClass = (jclass) env->NewGlobalRef(clazz)) ||
      !(hashCodeMID = env->GetStaticMethodID(clazz, "identityHashCode",
                                             "(Ljava/lang/Object;)I")))
  {
    NS_WARNING("Problem creating java.lang.System globals");
    goto init_error;
  }

  if (!(clazz = env->FindClass("java/lang/Boolean")) ||
      !(booleanClass = (jclass) env->NewGlobalRef(clazz)) ||
      !(booleanValueMID = env->GetMethodID(clazz, "booleanValue", "()Z")) ||
      !(booleanInitMID = env->GetMethodID(clazz, "<init>", "(Z)V")))
  {
    NS_WARNING("Problem creating java.lang.Boolean globals");
    goto init_error;
  }

  if (!(clazz = env->FindClass("java/lang/Character")) ||
      !(charClass = (jclass) env->NewGlobalRef(clazz)) ||
      !(charValueMID = env->GetMethodID(clazz, "charValue", "()C")) ||
      !(charInitMID = env->GetMethodID(clazz, "<init>", "(C)V")))
  {
    NS_WARNING("Problem creating java.lang.Character globals");
    goto init_error;
  }

  if (!(clazz = env->FindClass("java/lang/Byte")) ||
      !(byteClass = (jclass) env->NewGlobalRef(clazz)) ||
      !(byteValueMID = env->GetMethodID(clazz, "byteValue", "()B")) ||
      !(byteInitMID = env->GetMethodID(clazz, "<init>", "(B)V")))
  {
    NS_WARNING("Problem creating java.lang.Byte globals");
    goto init_error;
  }

  if (!(clazz = env->FindClass("java/lang/Short")) ||
      !(shortClass = (jclass) env->NewGlobalRef(clazz)) ||
      !(shortValueMID = env->GetMethodID(clazz, "shortValue", "()S")) ||
      !(shortInitMID = env->GetMethodID(clazz, "<init>", "(S)V")))
  {
    NS_WARNING("Problem creating java.lang.Short globals");
    goto init_error;
  }

  if (!(clazz = env->FindClass("java/lang/Integer")) ||
      !(intClass = (jclass) env->NewGlobalRef(clazz)) ||
      !(intValueMID = env->GetMethodID(clazz, "intValue", "()I")) ||
      !(intInitMID = env->GetMethodID(clazz, "<init>", "(I)V")))
  {
    NS_WARNING("Problem creating java.lang.Integer globals");
    goto init_error;
  }

  if (!(clazz = env->FindClass("java/lang/Long")) ||
      !(longClass = (jclass) env->NewGlobalRef(clazz)) ||
      !(longValueMID = env->GetMethodID(clazz, "longValue", "()J")) ||
      !(longInitMID = env->GetMethodID(clazz, "<init>", "(J)V")))
  {
    NS_WARNING("Problem creating java.lang.Long globals");
    goto init_error;
  }

  if (!(clazz = env->FindClass("java/lang/Float")) ||
      !(floatClass = (jclass) env->NewGlobalRef(clazz)) ||
      !(floatValueMID = env->GetMethodID(clazz, "floatValue", "()F")) ||
      !(floatInitMID = env->GetMethodID(clazz, "<init>", "(F)V")))
  {
    NS_WARNING("Problem creating java.lang.Float globals");
    goto init_error;
  }

  if (!(clazz = env->FindClass("java/lang/Double")) ||
      !(doubleClass = (jclass) env->NewGlobalRef(clazz)) ||
      !(doubleValueMID = env->GetMethodID(clazz, "doubleValue", "()D")) ||
      !(doubleInitMID = env->GetMethodID(clazz, "<init>", "(D)V")))
  {
    NS_WARNING("Problem creating java.lang.Double globals");
    goto init_error;
  }

  if (!(clazz = env->FindClass("java/lang/String")) ||
      !(stringClass = (jclass) env->NewGlobalRef(clazz)))
  {
    NS_WARNING("Problem creating java.lang.String globals");
    goto init_error;
  }

  if (!(clazz = env->FindClass("org/mozilla/interfaces/nsISupports")) ||
      !(nsISupportsClass = (jclass) env->NewGlobalRef(clazz)))
  {
    NS_WARNING("Problem creating org.mozilla.interfaces.nsISupports globals");
    goto init_error;
  }

  if (!(clazz = env->FindClass("org/mozilla/xpcom/XPCOMException")) ||
      !(xpcomExceptionClass = (jclass) env->NewGlobalRef(clazz)))
  {
    NS_WARNING("Problem creating org.mozilla.xpcom.XPCOMException globals");
    goto init_error;
  }

  if (!(clazz = env->FindClass("org/mozilla/xpcom/internal/XPCOMJavaProxy")) ||
      !(xpcomJavaProxyClass = (jclass) env->NewGlobalRef(clazz)) ||
      !(createProxyMID = env->GetStaticMethodID(clazz, "createProxy",
                                   "(Ljava/lang/Class;J)Ljava/lang/Object;")) ||
      !(isXPCOMJavaProxyMID = env->GetStaticMethodID(clazz, "isXPCOMJavaProxy",
                                                    "(Ljava/lang/Object;)Z")) ||
      !(getNativeXPCOMInstMID = env->GetStaticMethodID(xpcomJavaProxyClass,
                                                       "getNativeXPCOMInstance",
                                                       "(Ljava/lang/Object;)J")))
  {
    NS_WARNING("Problem creating org.mozilla.xpcom.internal.XPCOMJavaProxy globals");
    goto init_error;
  }

  if (!(clazz = env->FindClass("java/lang/ref/WeakReference")) ||
      !(weakReferenceClass = (jclass) env->NewGlobalRef(clazz)) ||
      !(weakReferenceConstructorMID = env->GetMethodID(weakReferenceClass, 
                                           "<init>","(Ljava/lang/Object;)V")) ||
      !(getReferentMID = env->GetMethodID(weakReferenceClass,
                                          "get", "()Ljava/lang/Object;")) ||
      !(clearReferentMID = env->GetMethodID(weakReferenceClass, 
                                            "clear", "()V")))
  {
    NS_WARNING("Problem creating java.lang.ref.WeakReference globals");
    goto init_error;
  }

  if (!(clazz = env->FindClass("org/mozilla/xpcom/internal/JavaXPCOMMethods")) ||
      !(javaXPCOMUtilsClass = (jclass) env->NewGlobalRef(clazz)) ||
      !(findClassInLoaderMID = env->GetStaticMethodID(clazz,
                    "findClassInLoader",
                    "(Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Class;")))
  {
    NS_WARNING("Problem creating org.mozilla.xpcom.internal.JavaXPCOMMethods globals");
    goto init_error;
  }

#ifdef DEBUG_JAVAXPCOM
  if (!(clazz = env->FindClass("java/lang/Class")) ||
      !(getNameMID = env->GetMethodID(clazz, "getName","()Ljava/lang/String;")))
  {
    NS_WARNING("Problem creating java.lang.Class globals");
    goto init_error;
  }

  if (!(proxyToStringMID = env->GetStaticMethodID(xpcomJavaProxyClass,
                                                  "proxyToString",
                                     "(Ljava/lang/Object;)Ljava/lang/String;")))
  {
    NS_WARNING("Problem creating proxyToString global");
    goto init_error;
  }
#endif

  gNativeToJavaProxyMap = new NativeToJavaProxyMap();
  if (!gNativeToJavaProxyMap || NS_FAILED(gNativeToJavaProxyMap->Init())) {
    NS_WARNING("Problem creating NativeToJavaProxyMap");
    goto init_error;
  }
  gJavaToXPTCStubMap = new JavaToXPTCStubMap();
  if (!gJavaToXPTCStubMap || NS_FAILED(gJavaToXPTCStubMap->Init())) {
    NS_WARNING("Problem creating JavaToXPTCStubMap");
    goto init_error;
  }

  {
    nsresult rv = NS_OK;
    PRUint32 size = NS_ARRAY_LENGTH(kJavaKeywords);
    gJavaKeywords = new nsTHashtable<nsDepCharHashKey>();
    if (!gJavaKeywords || NS_FAILED(gJavaKeywords->Init(size))) {
      NS_WARNING("Failed to init JavaKeywords HashSet");
      goto init_error;
    }
    for (PRUint32 i = 0; i < size && NS_SUCCEEDED(rv); i++) {
      if (!gJavaKeywords->PutEntry(kJavaKeywords[i])) {
        rv = NS_ERROR_OUT_OF_MEMORY;
      }
    }
    if (NS_FAILED(rv)) {
      NS_WARNING("Failed to populate JavaKeywords hash");
      goto init_error;
    }
  }

  gJavaXPCOMLock = PR_NewLock();
  gJavaXPCOMInitialized = PR_TRUE;
  return PR_TRUE;

init_error:
  // If we encounter an error during initialization, then free any globals that
  // were allocated, and return false.
  FreeJavaGlobals(env);
  return PR_FALSE;
}
nsresult
nsPluginDirServiceProvider::GetPLIDDirectoriesWithHKEY(HKEY aKey, nsCOMArray<nsILocalFile> &aDirs)
{
  WCHAR subkey[_MAX_PATH] = L"Software\\MozillaPlugins";
  HKEY baseloc;

  if (ERROR_SUCCESS != ::RegOpenKeyExW(aKey, subkey, 0, KEY_READ, &baseloc))
    return NS_ERROR_FAILURE;

  DWORD index = 0;
  DWORD subkeylen = _MAX_PATH;
  FILETIME modTime;
  while (ERROR_SUCCESS == ::RegEnumKeyExW(baseloc, index++, subkey, &subkeylen,
                                          NULL, NULL, NULL, &modTime)) {
    subkeylen = _MAX_PATH;
    HKEY keyloc;

    if (ERROR_SUCCESS == ::RegOpenKeyExW(baseloc, subkey, 0, KEY_QUERY_VALUE,
                                         &keyloc)) {
      DWORD type;
      WCHAR path[_MAX_PATH];
      DWORD pathlen = NS_ARRAY_LENGTH(path);

      if (ERROR_SUCCESS == ::RegQueryValueExW(keyloc, L"Path", NULL, &type,
                                              (LPBYTE)&path, &pathlen)) {
        nsCOMPtr<nsILocalFile> localFile;
        if (NS_SUCCEEDED(NS_NewLocalFile(nsDependentString(path), PR_TRUE,
                                         getter_AddRefs(localFile))) &&
            localFile)
        {
          // Some vendors use a path directly to the DLL so chop off
          // the filename
          PRBool isDir = PR_FALSE;
          if (NS_SUCCEEDED(localFile->IsDirectory(&isDir)) && !isDir) {
            nsCOMPtr<nsIFile> temp;
            localFile->GetParent(getter_AddRefs(temp));
            if (temp)
              localFile = do_QueryInterface(temp);
          }

          // Now we check to make sure it's actually on disk and
          // To see if we already have this directory in the array
          PRBool isFileThere = PR_FALSE;
          PRBool isDupEntry = PR_FALSE;
          if (NS_SUCCEEDED(localFile->Exists(&isFileThere)) && isFileThere) {
            PRInt32 c = aDirs.Count();
            for (PRInt32 i = 0; i < c; i++) {
              nsIFile *dup = static_cast<nsIFile*>(aDirs[i]);
              if (dup &&
                  NS_SUCCEEDED(dup->Equals(localFile, &isDupEntry)) &&
                  isDupEntry) {
                break;
              }
            }

            if (!isDupEntry) {
              aDirs.AppendObject(localFile);
            }
          }
        }
      }
      ::RegCloseKey(keyloc);
    }
  }
  ::RegCloseKey(baseloc);
  return NS_OK;
}
nsresult
nsDirIndexParser::ParseFormat(const char* aFormatStr) {
  // Parse a "200" format line, and remember the fields and their
  // ordering in mFormat. Multiple 200 lines stomp on each other.

  delete[] mFormat;

  // Lets find out how many elements we have.
  // easier to do this then realloc
  const char* pos = aFormatStr;
  unsigned int num = 0;
  do {
    while (*pos && nsCRT::IsAsciiSpace(PRUnichar(*pos)))
      ++pos;
    
    ++num;
    // There are a maximum of six allowed header fields (doubled plus
    // terminator, just in case) -- Bug 443299
    if (num > (2 * NS_ARRAY_LENGTH(gFieldTable)))
      return NS_ERROR_UNEXPECTED;

    if (! *pos)
      break;

    while (*pos && !nsCRT::IsAsciiSpace(PRUnichar(*pos)))
      ++pos;

  } while (*pos);

  mFormat = new int[num+1];
  // Prevent NULL Deref - Bug 443299 
  if (mFormat == nsnull)
    return NS_ERROR_OUT_OF_MEMORY;
  mFormat[num] = -1;
  
  int formatNum=0;
  do {
    while (*aFormatStr && nsCRT::IsAsciiSpace(PRUnichar(*aFormatStr)))
      ++aFormatStr;
    
    if (! *aFormatStr)
      break;

    nsCAutoString name;
    PRInt32     len = 0;
    while (aFormatStr[len] && !nsCRT::IsAsciiSpace(PRUnichar(aFormatStr[len])))
      ++len;
    name.SetCapacity(len + 1);
    name.Append(aFormatStr, len);
    aFormatStr += len;
    
    // Okay, we're gonna monkey with the nsStr. Bold!
    name.SetLength(nsUnescapeCount(name.BeginWriting()));

    // All tokens are case-insensitive - http://www.mozilla.org/projects/netlib/dirindexformat.html
    if (name.LowerCaseEqualsLiteral("description"))
      mHasDescription = PR_TRUE;
    
    for (Field* i = gFieldTable; i->mName; ++i) {
      if (name.EqualsIgnoreCase(i->mName)) {
        mFormat[formatNum] = i->mType;
        ++formatNum;
        break;
      }
    }

  } while (*aFormatStr);
  
  return NS_OK;
}
    XPINSTALL_MODULES                        \
    JSDEBUGGER_MODULES                       \
    MODULE(BOOT)                             \
    MODULE(NSS)                              \
    MODULE(nsAutoConfigModule)               \
    SYSTEMPREF_MODULES                       \
    SPELLCHECK_MODULE                        \
    XMLEXTRAS_MODULE                         \
    LAYOUT_DEBUG_MODULE                      \
    UNIXPROXY_MODULE                         \
    /* end of list */

#define MODULE(_name) \
NSGETMODULE_ENTRY_POINT(_name) (nsIComponentManager*, nsIFile*, nsIModule**);

XUL_MODULES

#undef MODULE

#define MODULE(_name) { #_name, NSGETMODULE(_name) },

/**
 * The nsStaticModuleInfo
 */
static nsStaticModuleInfo const gStaticModuleInfo[] = {
    XUL_MODULES
};

nsStaticModuleInfo const *const kPStaticModules = gStaticModuleInfo;
PRUint32 const kStaticModuleCount = NS_ARRAY_LENGTH(gStaticModuleInfo);
    "mp3",
    "m4a",
    "m4p",
    "jpg",
    "gif",
    "tif",
    "m4v",
    "mov",
    "mp4",
    "aif",
    "wav",
    "aa",
    "aac"
};
PRUint32 sbIPDSupportedMediaListLength =
           NS_ARRAY_LENGTH(sbIPDSupportedMediaList);
const char *sbIPDSupportedAudioMediaList[] =
{
    "mp3",
    "m4a",
    "m4p",
    "mp4",
    "aif",
    "wav",
    "aa",
    "aac"
};
PRUint32 sbIPDSupportedAudioMediaListLength =
           NS_ARRAY_LENGTH(sbIPDSupportedAudioMediaList);

PRBool nsCSSPseudoClasses::IsPseudoClass(nsIAtom *aAtom)
{
  return nsAtomListUtils::IsMember(aAtom,CSSPseudoClasses_info,
                                   NS_ARRAY_LENGTH(CSSPseudoClasses_info));
}
Beispiel #20
0
void KeyboardLayout::LoadLayout (HKL aLayout)
{
#ifndef WINCE
  PRUint32 shiftState;
  BYTE kbdState [256];
  BYTE originalKbdState [256];
  PRUint16 shiftStatesWithDeadKeys = 0;     // Bitfield with all shift states that have at least one dead-key.
  PRUint16 shiftStatesWithBaseChars = 0;    // Bitfield with all shift states that produce any possible dead-key base characters.

  memset (kbdState, 0, sizeof (kbdState));

  mActiveDeadKey = -1;
  mNumOfChars = 0;
  mKeyboardLayout = aLayout;

  ReleaseDeadKeyTables ();

  ::GetKeyboardState (originalKbdState);

  // For each shift state gather all printable characters that are produced
  // for normal case when no any dead-key is active.
  
  for (shiftState = 0; shiftState < 16; shiftState++)
  {
    SetShiftState (kbdState, shiftState);

    for (PRUint32 virtualKey = 0; virtualKey < 256; virtualKey++)
    {
      PRInt32 vki = GetKeyIndex (virtualKey);
      if (vki < 0)
        continue;

      NS_ASSERTION (vki < NS_ARRAY_LENGTH (mVirtualKeys), "invalid index"); 

      PRUint16 uniChars [5];
      PRInt32 rv;

      rv = ::ToUnicodeEx (virtualKey, 0, kbdState, (LPWSTR)uniChars, NS_ARRAY_LENGTH (uniChars), 0, mKeyboardLayout);

      if (rv < 0)   // dead-key
      {      
        shiftStatesWithDeadKeys |= 1 << shiftState;
        
        // Repeat dead-key to deactivate it and get its character representation.
        PRUint16 deadChar [2];

        rv = ::ToUnicodeEx (virtualKey, 0, kbdState, (LPWSTR)deadChar, NS_ARRAY_LENGTH (deadChar), 0, mKeyboardLayout);

        NS_ASSERTION (rv == 2, "Expecting twice repeated dead-key character");

        mVirtualKeys [vki].SetDeadChar (shiftState, deadChar [0]);
      } else
      {
        if (rv == 1)  // dead-key can pair only with exactly one base character.
          shiftStatesWithBaseChars |= 1 << shiftState;

        mVirtualKeys [vki].SetNormalChars (shiftState, uniChars, rv);
      }
    }
  }

  
  // Now process each dead-key to find all its base characters and resulting composite characters.

  for (shiftState = 0; shiftState < 16; shiftState++)
  {
    if (!(shiftStatesWithDeadKeys & (1 << shiftState)))
      continue;

    SetShiftState (kbdState, shiftState);

    for (PRUint32 virtualKey = 0; virtualKey < 256; virtualKey++)
    {
      PRInt32 vki = GetKeyIndex (virtualKey);
  
      if (vki >= 0 && mVirtualKeys [vki].IsDeadKey (shiftState))
      {      
        DeadKeyEntry deadKeyArray [256];

        PRInt32 n = GetDeadKeyCombinations (virtualKey, kbdState, shiftStatesWithBaseChars, 
                                            deadKeyArray, NS_ARRAY_LENGTH (deadKeyArray));

        const DeadKeyTable* dkt = mVirtualKeys [vki].MatchingDeadKeyTable (deadKeyArray, n);
          
        if (!dkt)
          dkt = AddDeadKeyTable (deadKeyArray, n);
        
        mVirtualKeys [vki].AttachDeadKeyTable (shiftState, dkt);
      }
    }
  }

  ::SetKeyboardState (originalKbdState);
#endif
}
Beispiel #21
0
nsSVGElement::LengthAttributesInfo
nsSVGFilterElement::GetLengthInfo()
{
  return LengthAttributesInfo(mLengthAttributes, sLengthInfo,
                              NS_ARRAY_LENGTH(sLengthInfo));
}
Beispiel #22
0
PRUint32 KeyboardLayout::GetDeadKeyCombinations (PRUint8 aDeadKey, const PBYTE aDeadKeyKbdState,
                                                 PRUint16 aShiftStatesWithBaseChars,
                                                 DeadKeyEntry* aDeadKeyArray, PRUint32 aMaxEntries)
{
  PRBool deadKeyActive = PR_FALSE;
  PRUint32 entries = 0;
  BYTE kbdState [256];
  
  memset (kbdState, 0, sizeof (kbdState));
  
  for (PRUint32 shiftState = 0; shiftState < 16; shiftState++)
  {
    if (!(aShiftStatesWithBaseChars & (1 << shiftState)))
      continue;

    SetShiftState (kbdState, shiftState);

    for (PRUint32 virtualKey = 0; virtualKey < 256; virtualKey++)
    {
      PRInt32 vki = GetKeyIndex (virtualKey);
      
      // Dead-key can pair only with such key that produces exactly one base character.
      if (vki >= 0 && mVirtualKeys [vki].GetNativeUniChars (shiftState) == 1)
      {
        // Ensure dead-key is in active state, when it swallows entered character and waits for the next pressed key.
        if (!deadKeyActive)
          deadKeyActive = EnsureDeadKeyActive (PR_TRUE, aDeadKey, aDeadKeyKbdState);

        // Depending on the character the followed the dead-key, the keyboard driver can produce
        // one composite character, or a dead-key character followed by a second character.
        PRUint16 compositeChars [5];
        PRInt32 rv;

        rv = ::ToUnicodeEx (virtualKey, 0, kbdState, (LPWSTR)compositeChars, NS_ARRAY_LENGTH (compositeChars), 0, mKeyboardLayout);

        switch (rv)
        {
          case 0:
            // This key combination does not produce any characters. The dead-key is still in active state.
            break;

          case 1:
          {
            // Exactly one composite character produced. Now, when dead-key is not active, repeat the last
            // character one more time to determine the base character.
            PRUint16 baseChars [5];

            rv = ::ToUnicodeEx (virtualKey, 0, kbdState, (LPWSTR)baseChars, NS_ARRAY_LENGTH (baseChars), 0, mKeyboardLayout);

            NS_ASSERTION (rv == 1, "One base character expected");

            if (rv == 1 && entries < aMaxEntries)
              if (AddDeadKeyEntry (baseChars [0], compositeChars [0], aDeadKeyArray, entries))
                entries++;
            
            deadKeyActive = PR_FALSE;
            break;
          }

          default:
            // 1. Unexpected dead-key. Dead-key chaining is not supported.
            // 2. More than one character generated. This is not a valid dead-key and base character combination.
            deadKeyActive = PR_FALSE;
            break;
        }
      }
    }
  }

  if (deadKeyActive)
    deadKeyActive = EnsureDeadKeyActive (PR_FALSE, aDeadKey, aDeadKeyKbdState);

  NS_QuickSort (aDeadKeyArray, entries, sizeof (DeadKeyEntry), CompareDeadKeyEntries, nsnull);

  return entries;
}
Beispiel #23
0
nsSVGElement::EnumAttributesInfo
nsSVGFilterElement::GetEnumInfo()
{
  return EnumAttributesInfo(mEnumAttributes, sEnumInfo,
                            NS_ARRAY_LENGTH(sEnumInfo));
}
int
registerFunctions(sqlite3 *aDB)
{
    struct Functions {
        const char *zName;
        int nArg;
        int enc;
        void *pContext;
        void (*xFunc)(::sqlite3_context*, int, sqlite3_value**);
    };

    Functions functions[] = {
        {   "lower",
            1,
            SQLITE_UTF16,
            0,
            caseFunction
        },
        {   "lower",
            1,
            SQLITE_UTF8,
            0,
            caseFunction
        },
        {   "upper",
            1,
            SQLITE_UTF16,
            (void*)1,
            caseFunction
        },
        {   "upper",
            1,
            SQLITE_UTF8,
            (void*)1,
            caseFunction
        },

        {   "like",
            2,
            SQLITE_UTF16,
            0,
            likeFunction
        },
        {   "like",
            2,
            SQLITE_UTF8,
            0,
            likeFunction
        },
        {   "like",
            3,
            SQLITE_UTF16,
            0,
            likeFunction
        },
        {   "like",
            3,
            SQLITE_UTF8,
            0,
            likeFunction
        },

        {   "levenshteinDistance",
            2,
            SQLITE_UTF16,
            0,
            levenshteinDistanceFunction
        },
        {   "levenshteinDistance",
            2,
            SQLITE_UTF8,
            0,
            levenshteinDistanceFunction
        },
    };

    int rv = SQLITE_OK;
    for (size_t i = 0; SQLITE_OK == rv && i < NS_ARRAY_LENGTH(functions); ++i) {
        struct Functions *p = &functions[i];
        rv = ::sqlite3_create_function(aDB, p->zName, p->nArg, p->enc, p->pContext,
                                       p->xFunc, NULL, NULL);
    }

    return rv;
}
Beispiel #25
0
  {nsIMsgFilterList::attribNone,      ""},
  {nsIMsgFilterList::attribVersion,    "version"},
  {nsIMsgFilterList::attribLogging,    "logging"},
  {nsIMsgFilterList::attribName,      "name"},
  {nsIMsgFilterList::attribEnabled,    "enabled"},
  {nsIMsgFilterList::attribDescription,  "description"},
  {nsIMsgFilterList::attribType,      "type"},
  {nsIMsgFilterList::attribScriptFile,  "scriptName"},
  {nsIMsgFilterList::attribAction,    "action"},
  {nsIMsgFilterList::attribActionValue,  "actionValue"},
  {nsIMsgFilterList::attribCondition,    "condition"},
  {nsIMsgFilterList::attribCustomId,  "customId"},
};

static const unsigned int sNumFilterFileAttribTable =
  NS_ARRAY_LENGTH(FilterFileAttribTable);

// If we want to buffer file IO, wrap it in here.
char nsMsgFilterList::ReadChar(nsIInputStream *aStream)
{
  char  newChar;
  uint32_t bytesRead;
  nsresult rv = aStream->Read(&newChar, 1, &bytesRead);
  if (NS_FAILED(rv) || !bytesRead)
    return -1;
  uint64_t bytesAvailable;
  rv = aStream->Available(&bytesAvailable);
  if (NS_FAILED(rv))
    return -1;
  else
  {
Beispiel #26
0
// in gfxFontConstants.h (e.g. NS_FONT_VARIANT_EAST_ASIAN_JIS78)

// NS_FONT_VARIANT_EAST_ASIAN_xxx values
const gfxFontFeature eastAsianDefaults[] = {
  { TRUETYPE_TAG('j','p','7','8'), 1 },
  { TRUETYPE_TAG('j','p','8','3'), 1 },
  { TRUETYPE_TAG('j','p','9','0'), 1 },
  { TRUETYPE_TAG('j','p','0','4'), 1 },
  { TRUETYPE_TAG('s','m','p','l'), 1 },
  { TRUETYPE_TAG('t','r','a','d'), 1 },
  { TRUETYPE_TAG('f','w','i','d'), 1 },
  { TRUETYPE_TAG('p','w','i','d'), 1 },
  { TRUETYPE_TAG('r','u','b','y'), 1 }
};

PR_STATIC_ASSERT(NS_ARRAY_LENGTH(eastAsianDefaults) ==
                 eFeatureEastAsian_numFeatures);

// NS_FONT_VARIANT_LIGATURES_xxx values
const gfxFontFeature ligDefaults[] = {
  { TRUETYPE_TAG('l','i','g','a'), 1 },
  { TRUETYPE_TAG('l','i','g','a'), 0 },
  { TRUETYPE_TAG('d','l','i','g'), 1 },
  { TRUETYPE_TAG('d','l','i','g'), 0 },
  { TRUETYPE_TAG('h','l','i','g'), 1 },
  { TRUETYPE_TAG('h','l','i','g'), 0 },
  { TRUETYPE_TAG('c','a','l','t'), 1 },
  { TRUETYPE_TAG('c','a','l','t'), 0 }
};

PR_STATIC_ASSERT(NS_ARRAY_LENGTH(ligDefaults) ==
void TestDistVersion() {
  printf("Starting distribution.ini version tests...\n");
  
  int result = _mkdir("../distribution");
  check(result == 0 || errno == EEXIST,
        "Failed to create distribution directory: %d\n", errno);

  FILE* f = NULL;
  
  for (unsigned int i = 0; i < NS_ARRAY_LENGTH(DIST_TEST_DATA); ++i) {
    fprintf(stdout, "======================================================\n");
    fprintf(stdout, "Test case %u: old %s new %s expected %s\n",
            i, DIST_TEST_DATA[i].oldVersion, DIST_TEST_DATA[i].newVersion,
            DIST_TEST_DATA[i].shouldSucceed ? "yes" : "no");
    // put in dummy application.ini files :/
    f = fopen("../application.ini", "w");
    check(f != NULL, "Failed to write old application.ini");
    fprintf(f, "[app]\nbuildid=0\n");
    fclose(f);
    f = fopen("application.ini", "w");
    check(f != NULL, "Failed to write new application.ini");
    fprintf(f, "[app]\nbuildid=0\n");
    fclose(f);

    // write out the test data
    if (DIST_TEST_DATA[i].oldVersion) {
      f = fopen("../distribution/test.ini", "w");
      check(f != NULL, "Failed to write old data file");
      fprintf(f, "[global]\nversion=%s\nid=old\n", DIST_TEST_DATA[i].oldVersion);
      fclose(f);
    } else {
      // no old version
      _unlink("../distribution/test.ini");
    }
    if (DIST_TEST_DATA[i].newVersion) {
      f = fopen("test.ini", "w");
      check(f != NULL, "Failed to write new data file");
      fprintf(f, "[global]\nversion=%s\nid=new\n", DIST_TEST_DATA[i].newVersion);
      fclose(f);
    } else {
      // no new version
      _unlink("test.ini");
    }

    fflush(stdout); fflush(stderr);
    #ifdef XP_WIN
      result = system("..\\disthelper.exe test tests\\test.ini");
    #else
      result = system("../disthelper test tests/test.ini");
    #endif /* XP_WIN */
    check(result != -1, "Failed to execute disthelper: %08x\n", errno);
    
    IniFile_t data;
    result = ReadIniFile(_T("../distribution/test.ini"), data);
    check(result == DH_ERROR_OK ||
            (!DIST_TEST_DATA[i].shouldSucceed &&
             (!DIST_TEST_DATA[i].oldVersion || !DIST_TEST_DATA[i].newVersion)),
          "Failed to read output (testcase #%i)", i);
    if (DIST_TEST_DATA[i].shouldSucceed) {
      check(data["global"]["version"].compare(DIST_TEST_DATA[i].newVersion) == 0 &&
              data["global"]["id"].compare("new") == 0,
            "Unexpectedly did not copy new data: %s -> %s result %s (%s)",
            DIST_TEST_DATA[i].oldVersion,
            DIST_TEST_DATA[i].newVersion,
            data["global"]["version"].c_str(),
            data["global"]["id"].c_str());
    } else if (DIST_TEST_DATA[i].oldVersion){
      check(data["global"]["version"].compare(DIST_TEST_DATA[i].oldVersion) == 0 &&
              data["global"]["id"].compare("old") == 0,
            "Unexpectedly overwrote old data: %s -> %s result %s (%s)",
            DIST_TEST_DATA[i].oldVersion,
            DIST_TEST_DATA[i].newVersion,
            data["global"]["version"].c_str(),
            data["global"]["id"].c_str());
    } else {
      // the act of finding the strings for dumping causes the condition to change
      if (data["global"].find("version") != data["global"].end()) {
        check(data["global"].find("version") == data["global"].end(),
              "Unexpectedly overwrote missing data: (null) -> %s result %s (%s)",
              DIST_TEST_DATA[i].newVersion,
              data["global"]["version"].c_str(),
              data["global"]["id"].c_str());
      }
    }
  }
  printf("TestDistVersion: PASS\n");
}
NS_IMETHODIMP
nsPluginDirServiceProvider::GetFile(const char *charProp, PRBool *persistant,
                                    nsIFile **_retval)
{
  nsCOMPtr<nsILocalFile>  localFile;
  nsresult rv = NS_ERROR_FAILURE;

  NS_ENSURE_ARG(charProp);

  *_retval = nsnull;
  *persistant = PR_FALSE;

  nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
  if (!prefs)
    return NS_ERROR_FAILURE;

  if (nsCRT::strcmp(charProp, NS_WIN_4DOTX_SCAN_KEY) == 0) {
    // Check our prefs to see if scanning the 4.x folder has been
    // explictly overriden failure to get the pref is okay, we'll do
    // what we've been doing -- a filtered scan
    PRBool bScan4x;
    if (NS_SUCCEEDED(prefs->GetBoolPref(NS_WIN_4DOTX_SCAN_KEY, &bScan4x)) &&
        !bScan4x) {
      return NS_ERROR_FAILURE;
    }

    // Look for the plugin folder that the user has in their
    // Communicator 4x install
    HKEY keyloc;
    long result;
    DWORD type;
    WCHAR szKey[_MAX_PATH] = L"Software\\Netscape\\Netscape Navigator";
    WCHAR path[_MAX_PATH];

    result = ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, szKey, 0, KEY_READ, &keyloc);

    if (result == ERROR_SUCCESS) {
      WCHAR current_version[80];
      DWORD length = NS_ARRAY_LENGTH(current_version);

      result = ::RegQueryValueExW(keyloc, L"CurrentVersion", NULL, &type,
                                  (LPBYTE)&current_version, &length);

      ::RegCloseKey(keyloc);
      wcscat(szKey, L"\\");
      wcscat(szKey, current_version);
      wcscat(szKey, L"\\Main");
      result = ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, szKey, 0, KEY_READ, &keyloc);

      if (result == ERROR_SUCCESS) {
        DWORD pathlen = NS_ARRAY_LENGTH(path);

        result = ::RegQueryValueExW(keyloc, L"Plugins Directory", NULL, &type,
                                   (LPBYTE)&path, &pathlen);
        if (result == ERROR_SUCCESS) {
          rv = NS_NewLocalFile(nsDependentString(path),
                               PR_TRUE, getter_AddRefs(localFile));
        }

        ::RegCloseKey(keyloc);
      }
    }
  } else if (nsCRT::strcmp(charProp, NS_WIN_JRE_SCAN_KEY) == 0) {
    nsXPIDLCString strVer;
    if (NS_FAILED(prefs->GetCharPref(charProp, getter_Copies(strVer))))
      return NS_ERROR_FAILURE;
    verBlock minVer;
    TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer);

    // Look for the Java OJI plugin via the JRE install path
    HKEY baseloc;
    HKEY keyloc;
    HKEY entryloc;
    FILETIME modTime;
    DWORD type;
    DWORD index = 0;
    DWORD numChars = _MAX_PATH;
    DWORD pathlen;
    verBlock maxVer;
    ClearVersion(&maxVer);
    WCHAR curKey[_MAX_PATH] = L"Software\\JavaSoft\\Java Runtime Environment";
    WCHAR path[_MAX_PATH];
    // Add + 15 to prevent buffer overrun when adding \bin (+ optionally
    // \new_plugin)
#define JAVA_PATH_SIZE _MAX_PATH + 15
    WCHAR newestPath[JAVA_PATH_SIZE];
    const WCHAR mozPath[_MAX_PATH] = L"Software\\mozilla.org\\Mozilla";
    WCHAR browserJavaVersion[_MAX_PATH];

    newestPath[0] = 0;
    LONG result = ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, curKey, 0, KEY_READ,
                                  &baseloc);
    if (ERROR_SUCCESS != result)
      return NS_ERROR_FAILURE;

    // Look for "BrowserJavaVersion"
    if (ERROR_SUCCESS != ::RegQueryValueExW(baseloc, L"BrowserJavaVersion", NULL,
                                            NULL, (LPBYTE)&browserJavaVersion,
                                            &numChars))
      browserJavaVersion[0] = 0;

    // We must enumerate through the keys because what if there is
    // more than one version?
    do {
      path[0] = 0;
      numChars = _MAX_PATH;
      pathlen = NS_ARRAY_LENGTH(path);
      result = ::RegEnumKeyExW(baseloc, index, curKey, &numChars, NULL, NULL,
                               NULL, &modTime);
      index++;

      // Skip major.minor as it always points to latest in its family
      numChars = 0;
      for (WCHAR *p = curKey; *p; p++) {
        if (*p == '.') {
          numChars++;
        }
      }
      if (numChars < 2)
        continue;

      if (ERROR_SUCCESS == result) {
        if (ERROR_SUCCESS == ::RegOpenKeyExW(baseloc, curKey, 0,
                                             KEY_QUERY_VALUE, &keyloc)) {
          // We have a sub key
          if (ERROR_SUCCESS == ::RegQueryValueExW(keyloc, L"JavaHome", NULL,
                                                  &type, (LPBYTE)&path,
                                                  &pathlen)) {
            verBlock curVer;
            TranslateVersionStr(curKey, &curVer);
            if (CompareVersion(curVer, minVer) >= 0) {
              if (!wcsncmp(browserJavaVersion, curKey, _MAX_PATH)) {
                wcscpy(newestPath, path);
                ::RegCloseKey(keyloc);
                break;
              }

              if (CompareVersion(curVer, maxVer) >= 0) {
                wcscpy(newestPath, path);
                CopyVersion(&maxVer, &curVer);
              }
            }
          }
          ::RegCloseKey(keyloc);
        }
      }
    } while (ERROR_SUCCESS == result);

    ::RegCloseKey(baseloc);

    static const WCHAR kMozillaVersion[] = NS_L(MOZILLA_VERSION);

    // If nothing is found, then don't add \bin dir and don't set
    // CurrentVersion for Mozilla
    if (newestPath[0] != 0) {
      if (ERROR_SUCCESS == ::RegCreateKeyExW(HKEY_LOCAL_MACHINE, mozPath, 0,
                                             NULL, REG_OPTION_NON_VOLATILE,
                                             KEY_SET_VALUE|KEY_QUERY_VALUE,
                                             NULL, &entryloc, NULL)) {
        if (ERROR_SUCCESS != ::RegQueryValueExW(entryloc, L"CurrentVersion", 0,
                                               NULL, NULL, NULL)) {
          ::RegSetValueExW(entryloc, L"CurrentVersion", 0, REG_SZ,
                           (const BYTE*) kMozillaVersion,
                           NS_ARRAY_LENGTH(kMozillaVersion));
        }
        ::RegCloseKey(entryloc);
      }

      wcscat(newestPath, L"\\bin");

      // See whether the "new_plugin" directory exists
      WCHAR tmpPath[JAVA_PATH_SIZE];
      nsCOMPtr<nsILocalFile> tmpFile;

      wcscpy(tmpPath, newestPath);
      wcscat(tmpPath, L"\\new_plugin");
      rv = NS_NewLocalFile(nsDependentString(tmpPath),
                           PR_TRUE, getter_AddRefs(tmpFile));
      if (NS_SUCCEEDED(rv) && tmpFile) {
        PRBool exists = PR_FALSE;
        PRBool isDir = PR_FALSE;
        if (NS_SUCCEEDED(tmpFile->Exists(&exists)) && exists &&
            NS_SUCCEEDED(tmpFile->IsDirectory(&isDir)) && isDir) {
          // Assume we're supposed to use this as the search
          // directory for the Java Plug-In instead of the normal
          // one
          wcscpy(newestPath, tmpPath);
        }
      }

      rv = NS_NewLocalFile(nsDependentString(newestPath),
                           PR_TRUE, getter_AddRefs(localFile));
    }
  } else if (nsCRT::strcmp(charProp, NS_WIN_QUICKTIME_SCAN_KEY) == 0) {
    nsXPIDLCString strVer;
    if (NS_FAILED(prefs->GetCharPref(charProp, getter_Copies(strVer))))
      return NS_ERROR_FAILURE;
    verBlock minVer;
    TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer);

    // Look for the Quicktime system installation plugins directory
    HKEY keyloc;
    long result;
    DWORD type;
    verBlock qtVer;
    ClearVersion(&qtVer);
    WCHAR path[_MAX_PATH];
    DWORD pathlen = NS_ARRAY_LENGTH(path);

    // First we need to check the version of Quicktime via checking
    // the EXE's version table
    if (ERROR_SUCCESS == ::RegOpenKeyExW(HKEY_LOCAL_MACHINE,
                                         L"software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\QuickTimePlayer.exe",
                                         0, KEY_READ, &keyloc)) {
      if (ERROR_SUCCESS == ::RegQueryValueExW(keyloc, NULL, NULL, &type,
                                              (LPBYTE)&path, &pathlen)) {
        GetFileVersion(path, &qtVer);
      }
      ::RegCloseKey(keyloc);
    }
    if (CompareVersion(qtVer, minVer) < 0)
      return rv;

    if (ERROR_SUCCESS == ::RegOpenKeyExW(HKEY_LOCAL_MACHINE,
                                         L"software\\Apple Computer, Inc.\\QuickTime",
                                        0, KEY_READ, &keyloc)) {
      DWORD pathlen = NS_ARRAY_LENGTH(path);

      result = ::RegQueryValueExW(keyloc, L"InstallDir", NULL, &type,
                                  (LPBYTE)&path, &pathlen);
      wcscat(path, L"\\Plugins");
      if (result == ERROR_SUCCESS)
        rv = NS_NewLocalFile(nsDependentString(path), PR_TRUE,
                             getter_AddRefs(localFile));
      ::RegCloseKey(keyloc);
    }
  } else if (nsCRT::strcmp(charProp, NS_WIN_WMP_SCAN_KEY) == 0) {
    nsXPIDLCString strVer;
    if (NS_FAILED(prefs->GetCharPref(charProp, getter_Copies(strVer))))
      return NS_ERROR_FAILURE;
    verBlock minVer;
    TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer);

    // Look for Windows Media Player system installation plugins directory
    HKEY keyloc;
    DWORD type;
    verBlock wmpVer;
    ClearVersion(&wmpVer);
    WCHAR path[_MAX_PATH];
    DWORD pathlen = NS_ARRAY_LENGTH(path);

    // First we need to check the version of WMP
    if (ERROR_SUCCESS == ::RegOpenKeyExW(HKEY_LOCAL_MACHINE,
                                         L"software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\wmplayer.exe",
                                         0, KEY_READ, &keyloc)) {
      if (ERROR_SUCCESS == ::RegQueryValueExW(keyloc, NULL, NULL, &type,
                                              (LPBYTE)&path, &pathlen)) {
        GetFileVersion(path, &wmpVer);
      }
      ::RegCloseKey(keyloc);
    }
    if (CompareVersion(wmpVer, minVer) < 0)
      return rv;

    if (ERROR_SUCCESS == ::RegOpenKeyExW(HKEY_LOCAL_MACHINE,
                                         L"software\\Microsoft\\MediaPlayer", 0,
                                         KEY_READ, &keyloc)) {
      if (ERROR_SUCCESS == ::RegQueryValueExW(keyloc, L"Installation Directory",
                                             NULL, &type, (LPBYTE)&path,
                                             &pathlen)) {
        rv = NS_NewLocalFile(nsDependentString(path), PR_TRUE,
                             getter_AddRefs(localFile));
      }

      ::RegCloseKey(keyloc);
    }
  } else if (nsCRT::strcmp(charProp, NS_WIN_ACROBAT_SCAN_KEY) == 0) {
    nsXPIDLCString strVer;
    if (NS_FAILED(prefs->GetCharPref(charProp, getter_Copies(strVer)))) {
      return NS_ERROR_FAILURE;
    }

    verBlock minVer;
    TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer);

    // Look for Adobe Acrobat system installation plugins directory
    HKEY baseloc;
    HKEY keyloc;
    FILETIME modTime;
    DWORD type;
    DWORD index = 0;
    DWORD numChars = _MAX_PATH;
    DWORD pathlen;
    verBlock maxVer;
    ClearVersion(&maxVer);
    WCHAR curKey[_MAX_PATH] = L"software\\Adobe\\Acrobat Reader";
    WCHAR path[_MAX_PATH];
    // Add + 8 to prevent buffer overrun when adding \browser
    WCHAR newestPath[_MAX_PATH + 8];

    newestPath[0] = 0;
    if (ERROR_SUCCESS != ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, curKey, 0,
                                         KEY_READ, &baseloc)) {
      wcscpy(curKey, L"software\\Adobe\\Adobe Acrobat");
      if (ERROR_SUCCESS != ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, curKey, 0,
                                           KEY_READ, &baseloc)) {
        return NS_ERROR_FAILURE;
      }
    }

    // We must enumerate through the keys because what if there is
    // more than one version?
    LONG result = ERROR_SUCCESS;
    while (ERROR_SUCCESS == result) {
      path[0] = 0;
      numChars = _MAX_PATH;
      pathlen = NS_ARRAY_LENGTH(path);
      result = ::RegEnumKeyExW(baseloc, index, curKey, &numChars, NULL, NULL,
                               NULL, &modTime);
      index++;

      if (ERROR_SUCCESS == result) {
        verBlock curVer;
        TranslateVersionStr(curKey, &curVer);
        wcscat(curKey, L"\\InstallPath");
        if (ERROR_SUCCESS == ::RegOpenKeyExW(baseloc, curKey, 0,
                                             KEY_QUERY_VALUE, &keyloc)) {
          // We have a sub key
          if (ERROR_SUCCESS == ::RegQueryValueExW(keyloc, NULL, NULL, &type,
                                                  (LPBYTE)&path, &pathlen)) {
            if (CompareVersion(curVer, maxVer) >= 0 &&
                CompareVersion(curVer, minVer) >= 0) {
              wcscpy(newestPath, path);
              CopyVersion(&maxVer, &curVer);
            }
          }

          ::RegCloseKey(keyloc);
        }
      }
    }

    ::RegCloseKey(baseloc);

    if (newestPath[0] != 0) {
      wcscat(newestPath, L"\\browser");
      rv = NS_NewLocalFile(nsDependentString(newestPath), PR_TRUE,
                           getter_AddRefs(localFile));
    }

  }

  if (localFile && NS_SUCCEEDED(rv))
    return CallQueryInterface(localFile, _retval);

  return rv;
}
Beispiel #29
0
nsresult
nsAbManager::ExportDirectoryToLDIF(nsIAbDirectory *aDirectory, nsILocalFile *aLocalFile)
{
  nsCOMPtr <nsISimpleEnumerator> cardsEnumerator;
  nsCOMPtr <nsIAbCard> card;

  nsresult rv;

  nsCOMPtr <nsIOutputStream> outputStream;
  rv = MsgNewBufferedFileOutputStream(getter_AddRefs(outputStream),
                                      aLocalFile,
                                      PR_CREATE_FILE | PR_WRONLY | PR_TRUNCATE,
                                      0664);

  // the desired file may be read only
  if (NS_FAILED(rv))
    return rv;

  // Get the default attribute map for ldap. We use the default attribute
  // map rather than one for a specific server because if people want an
  // ldif export using a servers specific schema, then they can use ldapsearch
  nsCOMPtr<nsIAbLDAPAttributeMapService> mapSrv =
    do_GetService("@mozilla.org/addressbook/ldap-attribute-map-service;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIAbLDAPAttributeMap> attrMap;
  rv = mapSrv->GetMapForPrefBranch(NS_LITERAL_CSTRING("ldap_2.servers.default.attrmap"),
                                   getter_AddRefs(attrMap));
  NS_ENSURE_SUCCESS(rv, rv);

  PRUint32 i;
  PRUint32 writeCount;
  PRUint32 length;

  rv = aDirectory->GetChildCards(getter_AddRefs(cardsEnumerator));
  if (NS_SUCCEEDED(rv) && cardsEnumerator) {
    nsCOMPtr<nsISupports> item;
    bool more;
    while (NS_SUCCEEDED(cardsEnumerator->HasMoreElements(&more)) && more) {
      rv = cardsEnumerator->GetNext(getter_AddRefs(item));
      if (NS_SUCCEEDED(rv)) {
        nsCOMPtr <nsIAbCard> card = do_QueryInterface(item, &rv);
        NS_ENSURE_SUCCESS(rv,rv);

        bool isMailList;
        rv = card->GetIsMailList(&isMailList);
        NS_ENSURE_SUCCESS(rv,rv);

        if (isMailList) {
          nsCString mailListCStr;

          rv = AppendLDIFForMailList(card, attrMap, mailListCStr);
          NS_ENSURE_SUCCESS(rv,rv);

          length = mailListCStr.Length();
          rv = outputStream->Write(mailListCStr.get(), length, &writeCount);
          NS_ENSURE_SUCCESS(rv,rv);
          if (length != writeCount)
            return NS_ERROR_FAILURE;
        }
        else {
          nsString value;
          nsCString valueCStr;

          rv = AppendBasicLDIFForCard(card, attrMap, valueCStr);
          NS_ENSURE_SUCCESS(rv,rv);

          length = valueCStr.Length();
          rv = outputStream->Write(valueCStr.get(), length, &writeCount);
          NS_ENSURE_SUCCESS(rv,rv);
          if (length != writeCount)
            return NS_ERROR_FAILURE;

          valueCStr.Truncate();

          nsCAutoString ldapAttribute;

          for (i = 0; i < NS_ARRAY_LENGTH(EXPORT_ATTRIBUTES_TABLE); i++) {
            if (NS_SUCCEEDED(attrMap->GetFirstAttribute(nsDependentCString(EXPORT_ATTRIBUTES_TABLE[i].abPropertyName),
                                                        ldapAttribute)) &&
                !ldapAttribute.IsEmpty()) {

              rv = card->GetPropertyAsAString(EXPORT_ATTRIBUTES_TABLE[i].abPropertyName, value);
              if (NS_FAILED(rv))
                value.Truncate();

              if (!PL_strcmp(EXPORT_ATTRIBUTES_TABLE[i].abPropertyName, kPreferMailFormatProperty)) {
                if (value.EqualsLiteral("html"))
                  value.AssignLiteral("true");
                else if (value.EqualsLiteral("plaintext"))
                  value.AssignLiteral("false");
                else
                  value.Truncate(); // unknown.
              }

              if (!value.IsEmpty()) {
                rv = AppendProperty(ldapAttribute.get(), value.get(), valueCStr);
                NS_ENSURE_SUCCESS(rv,rv);

                valueCStr += MSG_LINEBREAK;
              }
              else
                valueCStr.Truncate();

              length = valueCStr.Length();
              if (length) {
                rv = outputStream->Write(valueCStr.get(), length, &writeCount);
                NS_ENSURE_SUCCESS(rv,rv);
                if (length != writeCount)
                  return NS_ERROR_FAILURE;
              }
              valueCStr.Truncate();
            }
            else {
              // something we don't support yet
              // ldif doesn't export multiple addresses
            }
          }

          // write out the linebreak that separates the cards
          rv = outputStream->Write(MSG_LINEBREAK, MSG_LINEBREAK_LEN, &writeCount);
          NS_ENSURE_SUCCESS(rv,rv);
          if (MSG_LINEBREAK_LEN != writeCount)
            return NS_ERROR_FAILURE;
        }
      }
    }
  }

  rv = outputStream->Flush();
  NS_ENSURE_SUCCESS(rv,rv);

  rv = outputStream->Close();
  NS_ENSURE_SUCCESS(rv,rv);
  return NS_OK;
}
nsSVGElement::LengthAttributesInfo
nsSVGRadialGradientElement::GetLengthInfo()
{
  return LengthAttributesInfo(mLengthAttributes, sLengthInfo,
                              NS_ARRAY_LENGTH(sLengthInfo));
}