コード例 #1
0
void
nsAbAutoCompleteSession::AddToResult(const PRUnichar* pNickNameStr,
                                     const PRUnichar* pDisplayNameStr,
                                     const PRUnichar* pFirstNameStr,
                                     const PRUnichar* pLastNameStr,
                                     const PRUnichar* pEmailStr,
                                     const PRUnichar* pNotesStr,
                                     const PRUnichar* pDirName,
                                     PRUint32 aPopularityIndex,
                                     PRBool bIsMailList, PRBool pDefaultMatch,
                                     nsIAutoCompleteResults* results)
{
    nsresult rv;
    PRUnichar* fullAddrStr = nsnull;

    if (pDefaultMatch)
    {
        if (mDefaultDomain[0] == 0)
            return;

        nsAutoString aStr(pDisplayNameStr);
        if (aStr.FindChar('@') == kNotFound)
        {
            aStr.Append(PRUnichar('@'));
            aStr += mDefaultDomain;
        }
        fullAddrStr = ToNewUnicode(aStr);
    }
    else
    {
        if (mParser)
        {
            nsXPIDLCString fullAddress;
            nsXPIDLCString utf8Email;
            if (bIsMailList)
            {
                if (pNotesStr && pNotesStr[0] != 0)
                    utf8Email.Adopt(ToNewUTF8String(nsDependentString(pNotesStr)));
                else
                    utf8Email.Adopt(ToNewUTF8String(nsDependentString(pDisplayNameStr)));
            }
            else
                utf8Email.Adopt(ToNewUTF8String(nsDependentString(pEmailStr)));

            mParser->MakeFullAddress(nsnull, NS_ConvertUCS2toUTF8(pDisplayNameStr).get(),
                                     utf8Email, getter_Copies(fullAddress));
            if (!fullAddress.IsEmpty())
            {
                /* We need to convert back the result from UTF-8 to Unicode */
                fullAddrStr = nsCRT::strdup(NS_ConvertUTF8toUCS2(fullAddress.get()).get());
            }
        }

        if (!fullAddrStr)
        {
            //oops, parser problem! I will try to do my best...
            const PRUnichar * pStr = nsnull;
            if (bIsMailList)
            {
                if (pNotesStr && pNotesStr[0] != 0)
                    pStr = pNotesStr;
                else
                    pStr = pDisplayNameStr;
            }
            else
                pStr = pEmailStr;
            // check this so we do not get a bogus entry "someName <>"
            if (pStr && pStr[0] != 0) {
                nsAutoString aStr(pDisplayNameStr);
                aStr.AppendLiteral(" <");
                aStr += pStr;
                aStr.AppendLiteral(">");
                fullAddrStr = ToNewUnicode(aStr);
            }
            else
                fullAddrStr = nsnull;
        }
    }

    if (fullAddrStr && ! ItsADuplicate(fullAddrStr, aPopularityIndex, results))
    {
        nsCOMPtr<nsIAutoCompleteItem> newItem = do_CreateInstance(NS_AUTOCOMPLETEITEM_CONTRACTID, &rv);
        if (NS_SUCCEEDED(rv))
        {
            nsAbAutoCompleteParam *param = new nsAbAutoCompleteParam(pNickNameStr, pDisplayNameStr, pFirstNameStr, pLastNameStr, pEmailStr, pNotesStr, pDirName, aPopularityIndex, bIsMailList);
            NS_IF_ADDREF(param);
            newItem->SetParam(param);
            NS_IF_RELEASE(param);

            // how to process the comment column, if at all.  this value
            // comes from "mail.autoComplete.commentColumn", or, if that
            // doesn't exist, defaults to 0
            //
            // 0 = none
            // 1 = name of addressbook this card came from
            // 2 = other per-addressbook format (currrently unused here)
            //
            if (mAutoCompleteCommentColumn == 1) {
                rv = newItem->SetComment(pDirName);
                if (NS_FAILED(rv)) {
                    NS_WARNING("nsAbAutoCompleteSession::AddToResult():"
                               " newItem->SetComment() failed\n");
                }
            }

            // if this isn't a default match, set the class name so we can style
            // this cell with the local addressbook icon (or whatever)
            //
            rv = newItem->SetClassName(pDefaultMatch ? "default-match" :
                                       "local-abook");
            if (NS_FAILED(rv)) {
                NS_WARNING("nsAbAutoCompleteSession::AddToResult():"
                           " newItem->SetClassName() failed\n");
            }

            newItem->SetValue(nsDependentString(fullAddrStr));
            nsCOMPtr<nsISupportsArray> array;
            rv = results->GetItems(getter_AddRefs(array));
            if (NS_SUCCEEDED(rv))
            {
                PRUint32 nbrOfItems;
                rv = array->Count(&nbrOfItems);

                PRInt32 insertPosition = 0;

                for (; insertPosition < nbrOfItems && !pDefaultMatch; insertPosition++)
                {
                    nsCOMPtr<nsISupports> currentItemParams;
                    nsCOMPtr<nsIAutoCompleteItem> resultItem;
                    nsresult rv = array->QueryElementAt(insertPosition, NS_GET_IID(nsIAutoCompleteItem),
                                                        getter_AddRefs(resultItem));
                    if (NS_FAILED(rv))
                        continue;
                    rv = resultItem->GetParam(getter_AddRefs(currentItemParams));
                    if (NS_FAILED(rv))
                        continue;

                    param = (nsAbAutoCompleteParam *)(void *)currentItemParams;
                    if (aPopularityIndex > param->mPopularityIndex) // sort the search results by popularity index
                        break;
                }

                rv = array->InsertElementAt(newItem, insertPosition);
            }
        }
    }
    PR_Free(fullAddrStr);
}
コード例 #2
0
NS_IMETHODIMP ImportAddressImpl::GetSampleData(PRInt32 index, bool *pFound, PRUnichar **pStr)
{
  NS_PRECONDITION(pFound != nsnull, "null ptr");
  NS_PRECONDITION(pStr != nsnull, "null ptr");
  if (!pFound || !pStr)
    return NS_ERROR_NULL_POINTER;

  if (!m_fileLoc) {
    IMPORT_LOG0("*** Error, called GetSampleData before SetSampleLocation\n");
    return NS_ERROR_FAILURE;
  }

  nsresult rv;
  *pStr = nsnull;
  PRUnichar term = 0;

  if (!m_haveDelim) {
    rv = m_text.DetermineDelim(m_fileLoc);
    NS_ENSURE_SUCCESS(rv, rv);
    m_haveDelim = true;
    m_delim = m_text.GetDelim();
  }

  bool fileExists;
  rv = m_fileLoc->Exists(&fileExists);
  NS_ENSURE_SUCCESS(rv, rv);

  if (!fileExists) {
    *pFound = false;
    *pStr = NS_strdup(&term);
    return NS_OK;
  }

  nsCString line;
  rv = nsTextAddress::ReadRecordNumber(m_fileLoc, line, index);
  if (NS_SUCCEEDED(rv)) {
    nsString str;
    nsCString field;
    nsString uField;
    PRInt32 fNum = 0;
    while (nsTextAddress::GetField(line.get(), line.Length(), fNum, field, m_delim)) {
      if (fNum)
        str.Append(PRUnichar('\n'));
      SanitizeSampleData(field);
      rv = nsMsgI18NConvertToUnicode(nsMsgI18NFileSystemCharset(),
                                     field, uField);

      str.Append(uField);
      fNum++;
      field.Truncate();
    }

    *pStr = ToNewUnicode(str);
    *pFound = true;

    /* IMPORT_LOG1("Sample data: %S\n", str.get()); */
  }
  else {
    *pFound = false;
    *pStr = NS_strdup(&term);
  }

  return NS_OK;
}
コード例 #3
0
NS_IMETHODIMP
nsFileView::SetFilter(const nsAString& aFilterString)
{
  PRUint32 filterCount = mCurrentFilters.Length();
  for (PRUint32 i = 0; i < filterCount; ++i)
    NS_Free(mCurrentFilters[i]);
  mCurrentFilters.Clear();

  nsAString::const_iterator start, iter, end;
  aFilterString.BeginReading(iter);
  aFilterString.EndReading(end);

  while (true) {
    // skip over delimiters
    while (iter != end && (*iter == ';' || *iter == ' '))
      ++iter;

    if (iter == end)
      break;

    start = iter; // start of a filter

    // we know this is neither ';' nor ' ', skip to next char
    ++iter;

    // find next delimiter or end of string
    while (iter != end && (*iter != ';' && *iter != ' '))
      ++iter;

    PRUnichar* filter = ToNewUnicode(Substring(start, iter));
    if (!filter)
      return NS_ERROR_OUT_OF_MEMORY;

    if (!mCurrentFilters.AppendElement(filter)) {
      NS_Free(filter);
      return NS_ERROR_OUT_OF_MEMORY;
    }

    if (iter == end)
      break;

    ++iter; // we know this is either ';' or ' ', skip to next char
  }

  if (mTree) {
    mTree->BeginUpdateBatch();
    PRUint32 count;
    mDirList->Count(&count);
    mTree->RowCountChanged(count, count - mTotalRows);
  }

  mFilteredFiles->Clear();

  FilterFiles();

  SortArray(mFilteredFiles);
  if (mReverseSort)
    ReverseArray(mFilteredFiles);

  if (mTree)
    mTree->EndUpdateBatch();

  return NS_OK;
}
コード例 #4
0
NS_IMETHODIMP nsImportFieldMap::GetFieldValue(nsIAbCard *card, PRInt32 fieldNum, PRUnichar **_retval)
{
  if (!_retval || !card)
    return NS_ERROR_NULL_POINTER;

  if (fieldNum == -1) {
    PRUnichar c = 0;
    *_retval = NS_strdup(&c);
    return NS_OK;
  }

  if ((fieldNum < 0) || (fieldNum >= m_mozFieldCount))
    return( NS_ERROR_FAILURE);

  // ARRGGG!!! Lots of typing again
  // get the field from the card
  nsresult rv;
  nsAutoString value;

  switch (fieldNum) {
  case 0:
    rv = card->GetFirstName(value);
    break;
  case 1:
    rv = card->GetLastName(value);
    break;
  case 2:
    rv = card->GetDisplayName(value);
    break;
  case 3:
    rv = card->GetPropertyAsAString(kNicknameProperty, value);
    break;
  case 4:
    rv = card->GetPrimaryEmail(value);
    break;
  case 5:
    rv = card->GetPropertyAsAString(k2ndEmailProperty, value);
    break;
  case 6:
    rv = card->GetPropertyAsAString(kWorkPhoneProperty, value);
    break;
  case 7:
    rv = card->GetPropertyAsAString(kHomePhoneProperty, value);
    break;
  case 8:
    rv = card->GetPropertyAsAString(kFaxProperty, value);
    break;
  case 9:
    rv = card->GetPropertyAsAString(kPagerProperty, value);
    break;
  case 10:
    rv = card->GetPropertyAsAString(kCellularProperty, value);
    break;
  case 11:
    rv = card->GetPropertyAsAString(kHomeAddressProperty, value);
    break;
  case 12:
    rv = card->GetPropertyAsAString(kHomeAddress2Property, value);
    break;
  case 13:
    rv = card->GetPropertyAsAString(kHomeCityProperty, value);
    break;
  case 14:
    rv = card->GetPropertyAsAString(kHomeStateProperty, value);
    break;
  case 15:
    rv = card->GetPropertyAsAString(kHomeZipCodeProperty, value);
    break;
  case 16:
    rv = card->GetPropertyAsAString(kHomeCountryProperty, value);
    break;
  case 17:
    rv = card->GetPropertyAsAString(kWorkAddressProperty, value);
    break;
  case 18:
    rv = card->GetPropertyAsAString(kWorkAddress2Property, value);
    break;
  case 19:
    rv = card->GetPropertyAsAString(kWorkCityProperty, value);
    break;
  case 20:
    rv = card->GetPropertyAsAString(kWorkStateProperty, value);
    break;
  case 21:
    rv = card->GetPropertyAsAString(kWorkZipCodeProperty, value);
    break;
  case 22:
    rv = card->GetPropertyAsAString(kWorkCountryProperty, value);
    break;
  case 23:
    rv = card->GetPropertyAsAString(kJobTitleProperty, value);
    break;
  case 24:
    rv = card->GetPropertyAsAString(kDepartmentProperty, value);
    break;
  case 25:
    rv = card->GetPropertyAsAString(kCompanyProperty, value);
    break;
  case 26:
    rv = card->GetPropertyAsAString(kWorkWebPageProperty, value);
    break;
  case 27:
    rv = card->GetPropertyAsAString(kHomeWebPageProperty, value);
    break;
  case 28:
    rv = card->GetPropertyAsAString(kBirthYearProperty, value);
    break;
  case 29:
    rv = card->GetPropertyAsAString(kBirthMonthProperty, value);
    break;
  case 30:
    rv = card->GetPropertyAsAString(kBirthDayProperty, value);
    break;
  case 31:
    rv = card->GetPropertyAsAString(kCustom1Property, value);
    break;
  case 32:
    rv = card->GetPropertyAsAString(kCustom2Property, value);
    break;
  case 33:
    rv = card->GetPropertyAsAString(kCustom3Property, value);
    break;
  case 34:
    rv = card->GetPropertyAsAString(kCustom4Property, value);
    break;
  case 35:
    rv = card->GetPropertyAsAString(kNotesProperty, value);
    break;
  case 36:
    rv = card->GetPropertyAsAString(kScreenNameProperty, value);
    break;
  default:
    /* Get the field description, and add it as an anonymous attr? */
    /* OR WHAT???? */
    {
      rv = NS_ERROR_FAILURE;
    }
  }
  if (rv == NS_ERROR_NOT_AVAILABLE)
    value = EmptyString();

  *_retval = ToNewUnicode(value);

  return rv;
}
コード例 #5
0
NS_StringCloneData(const nsAString& aStr)
{
  return ToNewUnicode(aStr);
}
コード例 #6
0
// The feed version of nsContentUtils::CreateContextualFragment It
// creates a fragment, but doesn't go to all the effort to preserve
// context like innerHTML does, because feed DOMs shouldn't have that.
NS_IMETHODIMP
nsScriptableUnescapeHTML::ParseFragment(const nsAString &aFragment,
                                        PRBool aIsXML,
                                        nsIURI* aBaseURI,
                                        nsIDOMElement* aContextElement,
                                        nsIDOMDocumentFragment** aReturn)
{
  NS_ENSURE_ARG(aContextElement);
  *aReturn = nsnull;

  nsresult rv;
  nsCOMPtr<nsIParser> parser = do_CreateInstance(kCParserCID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIDocument> document;
  nsCOMPtr<nsIDOMDocument> domDocument;
  nsCOMPtr<nsIDOMNode> contextNode;
  contextNode = do_QueryInterface(aContextElement);
  contextNode->GetOwnerDocument(getter_AddRefs(domDocument));
  document = do_QueryInterface(domDocument);
  NS_ENSURE_TRUE(document, NS_ERROR_NOT_AVAILABLE);
  
  // stop scripts
  nsCOMPtr<nsIScriptLoader> loader;
  PRBool scripts_enabled = PR_FALSE;
  if (document) {
    loader = document->GetScriptLoader();
    if (loader) {
      loader->GetEnabled(&scripts_enabled);
    }
  }
  if (scripts_enabled) {
    loader->SetEnabled(PR_FALSE);
  }

  // Wrap things in a div or body for parsing, but it won't show up in
  // the fragment.
  nsVoidArray tagStack;
  nsCAutoString base, spec;
  if (aIsXML) {
    // XHTML
    if (aBaseURI) {
      base.Append(NS_LITERAL_CSTRING(XHTML_DIV_TAG));
      base.Append(NS_LITERAL_CSTRING(" xml:base=\""));
      aBaseURI->GetSpec(spec);
      // nsEscapeHTML is good enough, because we only need to get
      // quotes, ampersands, and angle brackets
      char* escapedSpec = nsEscapeHTML(spec.get());
      if (escapedSpec)
        base += escapedSpec;
      NS_Free(escapedSpec);
      base.Append(NS_LITERAL_CSTRING("\""));
      tagStack.AppendElement(ToNewUnicode(base));
    }  else {
      tagStack.AppendElement(ToNewUnicode(NS_LITERAL_CSTRING(XHTML_DIV_TAG)));
    }
  } else {
    // HTML
    tagStack.AppendElement(ToNewUnicode(NS_LITERAL_CSTRING(HTML_BODY_TAG)));
    if (aBaseURI) {
      base.Append(NS_LITERAL_CSTRING((HTML_BASE_TAG)));
      base.Append(NS_LITERAL_CSTRING(" href=\""));
      aBaseURI->GetSpec(spec);
      base = base + spec;
      base.Append(NS_LITERAL_CSTRING("\""));
      tagStack.AppendElement(ToNewUnicode(base));
    }
  }

  if (NS_SUCCEEDED(rv)) {
    nsCAutoString contentType;
    nsDTDMode mode;
    nsCOMPtr<nsIFragmentContentSink> sink;
    if (aIsXML) {
      mode = eDTDMode_full_standards;
      contentType = NS_LITERAL_CSTRING("application/xhtml+xml");
      sink = do_CreateInstance(NS_XHTMLPARANOIDFRAGMENTSINK_CONTRACTID);
    } else {
      mode = eDTDMode_fragment;
      contentType = NS_LITERAL_CSTRING("text/html");
      sink = do_CreateInstance(NS_HTMLPARANOIDFRAGMENTSINK_CONTRACTID);
    }
    if (sink) {
      sink->SetTargetDocument(document);
      nsCOMPtr<nsIContentSink> contentsink(do_QueryInterface(sink));
      parser->SetContentSink(contentsink);
      rv = parser->ParseFragment(aFragment, nsnull, tagStack,
                                 aIsXML, contentType, mode);
      if (NS_SUCCEEDED(rv))
        rv = sink->GetFragment(aReturn);

    } else {
      rv = NS_ERROR_FAILURE;
    }
  }

  // from nsContentUtils XXX Ick! Delete strings we allocated above.
  PRInt32 count = tagStack.Count();
  for (PRInt32 i = 0; i < count; i++) {
    PRUnichar* str = (PRUnichar*)tagStack.ElementAt(i);
    if (str)
      NS_Free(str);
  }

  if (scripts_enabled)
      loader->SetEnabled(PR_TRUE);
  
  return rv;
}
コード例 #7
0
/* attribute wstring toFileName; */
NS_IMETHODIMP nsPrintSettings::GetToFileName(PRUnichar * *aToFileName)
{
    //NS_ENSURE_ARG_POINTER(aToFileName);
    *aToFileName = ToNewUnicode(mToFileName);
    return NS_OK;
}
コード例 #8
0
NS_IMETHODIMP nsMsgMailView::GetMailViewName(PRUnichar ** aMailViewName)
{
    *aMailViewName = ToNewUnicode(mName); 
    return NS_OK;
}
コード例 #9
0
/**
 * This function is called when username or password are requested from user.
 * This function is called in main thread as async request from dbus.
 * @param mount_op mount operation
 * @param message message to show to user
 * @param default_user preffered user
 * @param default_domain domain name
 * @param flags what type of information is required
 * @param user_data nsIChannel
 */
static void
mount_operation_ask_password (GMountOperation   *mount_op,
                              const char        *message,
                              const char        *default_user,
                              const char        *default_domain,
                              GAskPasswordFlags flags,
                              gpointer          user_data)
{
  nsIChannel *channel = (nsIChannel *) user_data;
  if (!channel) {
    g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED);
    return;
  }
  // We can't handle request for domain
  if (flags & G_ASK_PASSWORD_NEED_DOMAIN) {
    g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED);
    return;
  }

  nsCOMPtr<nsIAuthPrompt> prompt;
  NS_QueryNotificationCallbacks(channel, prompt);

  // If no auth prompt, then give up.  We could failover to using the
  // WindowWatcher service, but that might defeat a consumer's purposeful
  // attempt to disable authentication (for whatever reason).
  if (!prompt) {
    g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED);
    return;
  }
  // Parse out the host and port...
  nsCOMPtr<nsIURI> uri;
  channel->GetURI(getter_AddRefs(uri));
  if (!uri) {
    g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED);
    return;
  }

  nsAutoCString scheme, hostPort;
  uri->GetScheme(scheme);
  uri->GetHostPort(hostPort);

  // It doesn't make sense for either of these strings to be empty.  What kind
  // of funky URI is this?
  if (scheme.IsEmpty() || hostPort.IsEmpty()) {
    g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED);
    return;
  }
  // Construct the single signon key.  Altering the value of this key will
  // cause people's remembered passwords to be forgotten.  Think carefully
  // before changing the way this key is constructed.
  nsAutoString key, realm;

  NS_ConvertUTF8toUTF16 dispHost(scheme);
  dispHost.AppendLiteral("://");
  dispHost.Append(NS_ConvertUTF8toUTF16(hostPort));

  key = dispHost;
  if (*default_domain != '\0')
  {
    // We assume the realm string is ASCII.  That might be a bogus assumption,
    // but we have no idea what encoding GnomeVFS is using, so for now we'll
    // limit ourselves to ISO-Latin-1.  XXX What is a better solution?
    realm.Append('"');
    realm.Append(NS_ConvertASCIItoUTF16(default_domain));
    realm.Append('"');
    key.Append(' ');
    key.Append(realm);
  }
  // Construct the message string...
  //
  // We use Necko's string bundle here.  This code really should be encapsulated
  // behind some Necko API, after all this code is based closely on the code in
  // nsHttpChannel.cpp.
  nsCOMPtr<nsIStringBundleService> bundleSvc =
      do_GetService(NS_STRINGBUNDLE_CONTRACTID);
  if (!bundleSvc) {
    g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED);
    return;
  }
  nsCOMPtr<nsIStringBundle> bundle;
  bundleSvc->CreateBundle("chrome://global/locale/commonDialogs.properties",
                          getter_AddRefs(bundle));
  if (!bundle) {
    g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED);
    return;
  }
  nsAutoString nsmessage;

  if (flags & G_ASK_PASSWORD_NEED_PASSWORD) {
    if (flags & G_ASK_PASSWORD_NEED_USERNAME) {
      if (!realm.IsEmpty()) {
        const char16_t *strings[] = { realm.get(), dispHost.get() };
        bundle->FormatStringFromName(MOZ_UTF16("EnterLoginForRealm"),
                                     strings, 2, getter_Copies(nsmessage));
      } else {
        const char16_t *strings[] = { dispHost.get() };
        bundle->FormatStringFromName(MOZ_UTF16("EnterUserPasswordFor"),
                                     strings, 1, getter_Copies(nsmessage));
      }
    } else {
      NS_ConvertUTF8toUTF16 userName(default_user);
      const char16_t *strings[] = { userName.get(), dispHost.get() };
      bundle->FormatStringFromName(MOZ_UTF16("EnterPasswordFor"),
                                   strings, 2, getter_Copies(nsmessage));
    }
  } else {
    g_warning("Unknown mount operation request (flags: %x)", flags);
  }

  if (nsmessage.IsEmpty()) {
    g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED);
    return;
  }
  // Prompt the user...
  nsresult rv;
  bool retval = false;
  char16_t *user = nullptr, *pass = nullptr;
  if (default_user) {
    // user will be freed by PromptUsernameAndPassword
    user = ToNewUnicode(NS_ConvertUTF8toUTF16(default_user));
  }
  if (flags & G_ASK_PASSWORD_NEED_USERNAME) {
    rv = prompt->PromptUsernameAndPassword(nullptr, nsmessage.get(),
                                           key.get(),
                                           nsIAuthPrompt::SAVE_PASSWORD_PERMANENTLY,
                                           &user, &pass, &retval);
  } else {
    rv = prompt->PromptPassword(nullptr, nsmessage.get(),
                                key.get(),
                                nsIAuthPrompt::SAVE_PASSWORD_PERMANENTLY,
                                &pass, &retval);
  }
  if (NS_FAILED(rv) || !retval) {  //  was || user == '\0' || pass == '\0'
    g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED);
    return;
  }
  /* GIO should accept UTF8 */
  g_mount_operation_set_username(mount_op, NS_ConvertUTF16toUTF8(user).get());
  g_mount_operation_set_password(mount_op, NS_ConvertUTF16toUTF8(pass).get());
  nsMemory::Free(user);
  nsMemory::Free(pass);
  g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_HANDLED);
}
コード例 #10
0
//------------------------------------------------------------------
// helper
static PRUnichar * GetDefaultPrinterNameFromGlobalPrinters()
{
  nsAutoString printerName;
  GlobalPrinters::GetInstance()->GetDefaultPrinterName(printerName);
  return ToNewUnicode(printerName);
}
コード例 #11
0
/* attribute wstring message; */
NS_IMETHODIMP nsMsgProcessReport::GetMessage(PRUnichar * *aMessage)
{
  NS_ENSURE_ARG_POINTER(aMessage);
  *aMessage = ToNewUnicode(mMessage);
  return NS_OK;
}
コード例 #12
0
NS_IMETHODIMP
EmbedWindow::GetTitle(PRUnichar **aTitle)
{
  *aTitle = ToNewUnicode(mTitle);
  return NS_OK;
}
コード例 #13
0
// This method is called during the creation of a new window.
NS_IMETHODIMP
nsMsgCompFields::SplitRecipients(const nsAString &aRecipients,
                                 bool aEmailAddressOnly,
                                 PRUint32 *aLength,
                                 PRUnichar*** aResult)
{
  NS_ENSURE_ARG_POINTER(aLength);
  NS_ENSURE_ARG_POINTER(aResult);

  *aLength = 0;
  *aResult = nsnull;

  nsresult rv;
  nsCOMPtr<nsIMsgHeaderParser> parser =
    do_GetService(NS_MAILNEWS_MIME_HEADER_PARSER_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIMimeConverter> converter =
    do_GetService(NS_MIME_CONVERTER_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  char * names;
  char * addresses;
  PRUint32 numAddresses;

  rv = parser->ParseHeaderAddresses(NS_ConvertUTF16toUTF8(aRecipients).get(),
                                    &names, &addresses, &numAddresses);
  if (NS_SUCCEEDED(rv))
  {
    PRUint32 i = 0;
    char * pNames = names;
    char * pAddresses = addresses;
    PRUnichar** result = (PRUnichar**) NS_Alloc(sizeof(PRUnichar*) * numAddresses);
    if (!result)
      return NS_ERROR_OUT_OF_MEMORY;

    for (i = 0; i < numAddresses; ++i)
    {
      nsCString fullAddress;
      nsAutoString recipient;
      if (!aEmailAddressOnly)
      {
        nsCString decodedName;
        converter->DecodeMimeHeaderToCharPtr(pNames, GetCharacterSet(),
                                             false, true,
                                             getter_Copies(decodedName));
        rv = parser->MakeFullAddressString((!decodedName.IsEmpty() ?
                                            decodedName.get() : pNames),
                                           pAddresses,
                                           getter_Copies(fullAddress));
      }
      if (NS_SUCCEEDED(rv) && !aEmailAddressOnly)
        rv = ConvertToUnicode("UTF-8", fullAddress, recipient);
      else
        rv = ConvertToUnicode("UTF-8", nsDependentCString(pAddresses), recipient);
      if (NS_FAILED(rv))
        break;

      result[i] = ToNewUnicode(recipient);
      if (!result[i])
      {
        rv = NS_ERROR_OUT_OF_MEMORY;
        break;
      }

      pNames += PL_strlen(pNames) + 1;
      pAddresses += PL_strlen(pAddresses) + 1;
    }

    if (NS_FAILED(rv))
    {
      NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(i, result);
    }
    else
    {
      *aResult = result;
      *aLength = numAddresses;
    }

    PR_FREEIF(names);
    PR_FREEIF(addresses);
  }

  return rv;
}
コード例 #14
0
ファイル: nsAcceptLang.cpp プロジェクト: rn10950/RetroZilla
/* wstring getAcceptLangFromLocale (in wstring aLocale); */
NS_IMETHODIMP
nsAcceptLang::GetAcceptLangFromLocale(const PRUnichar *aLocale, PRUnichar **_retval)
{
  nsDependentString lc_name(aLocale);
  if (lc_name.Length() <=0) {
#ifdef DEBUG
    printf("nsAcceptLang::GetAcceptLangFromLocale: aLocale is empty!");
#endif
    // TODO: don't return; instead, use system locale: lc_name=...
    return NS_ERROR_FAILURE;
  }

  nsresult res;

	nsCOMPtr<nsIStringBundleService> sBundleService = 
	         do_GetService(kStringBundleServiceCID, &res);
 	if (NS_FAILED(res) || (nsnull == sBundleService)) {
    return NS_ERROR_FAILURE;
  }

  nsCOMPtr<nsIStringBundle> bundle;
#if 1
  res = sBundleService->CreateBundle("resource://gre/res/language.properties",
                                     getter_AddRefs(bundle));
#else
  res = sBundleService->CreateBundle("chrome://global/locale/languageNames.properties",
                                     getter_AddRefs(bundle));
#endif
  PRUnichar *ptrv = nsnull;
  nsAutoString  lc_tmp(aLocale);
  NS_NAMED_LITERAL_STRING(sAccept, ".accept");
  NS_NAMED_LITERAL_STRING(sTrue, "true");

  ToLowerCase(lc_tmp);
  lc_tmp.Append(sAccept);
  if (NS_OK == (res = bundle->GetStringFromName(lc_tmp.get(), &ptrv))) {
    if (sTrue.Equals(ptrv)) {
      // valid name already
      *_retval = ToNewUnicode(lc_name);
      return res;
    }
  }

  /* not in languageNames.properties; lang only?
   */
  PRInt32  dash = lc_tmp.FindChar('-');
  nsAutoString lang;
  nsAutoString country;
  if (dash > 0) {
    /* lang-country
     */
    PRInt32 count = 0;
    count = lc_tmp.Left(lang, dash);
    count = lc_tmp.Right(country, (lc_tmp.Length()-dash-1));
    /* ja-JP -> ja*/
  }
  else {
    /* ja ?? en-JP 
       en-JP ->ja (how about product locale or syste, locale ???)
       ja-EN ->ja
    */
    lang = lc_name;
  }
  
  // lang always in lower case; don't convert
  *_retval = ToNewUnicode(lang);
  lang.Append(sAccept);
  if (NS_OK == (res = bundle->GetStringFromName(lang.get(), &ptrv))) {

    if (sTrue.Equals(ptrv)) {
      /* lang is accepted */
      return res;
    }
  }

  /* unsupported lang */
  *_retval = nsnull;
  return NS_ERROR_FAILURE;
}
コード例 #15
0
ファイル: nsClipboard.cpp プロジェクト: lofter2011/Icefox
PRBool nsClipboard::GetClipboardDataByID(ULONG ulFormatID, const char *aFlavor)
{
  PVOID pDataMem;
  PRUint32 NumOfBytes;
  PRBool TempBufAllocated = PR_FALSE;

  PVOID pClipboardData = reinterpret_cast<PVOID>(WinQueryClipbrdData( 0, ulFormatID ));

  if (!pClipboardData) 
    return PR_FALSE;

  if (strstr( aFlavor, "text/" ))  // All text/.. flavors are null-terminated
  {
    pDataMem = pClipboardData;

    if (ulFormatID == CF_TEXT)     // CF_TEXT is one byte character set
    {
      PRUint32 NumOfChars = strlen( static_cast<char*>(pDataMem) );
      NumOfBytes = NumOfChars;

      if (!strcmp( aFlavor, kUnicodeMime ))  // Asked for unicode, but only plain text available.  Convert it!
      {
        nsAutoChar16Buffer buffer;
        PRInt32 bufLength;
        MultiByteToWideChar(0, static_cast<char*>(pDataMem), NumOfChars,
                            buffer, bufLength);
        pDataMem = ToNewUnicode(nsDependentString(buffer.Elements()));
        TempBufAllocated = PR_TRUE;
        NumOfBytes = bufLength * sizeof(UniChar);
      }

    }
    else                           // All other text/.. flavors are in unicode
    {
      PRUint32 NumOfChars = UniStrlen( static_cast<UniChar*>(pDataMem) );
      NumOfBytes = NumOfChars * sizeof(UniChar);
      PVOID pTempBuf = nsMemory::Alloc(NumOfBytes);
      memcpy(pTempBuf, pDataMem, NumOfBytes);
      pDataMem = pTempBuf;
      TempBufAllocated = PR_TRUE;
    }

    // DOM wants LF only, so convert from CRLF
    nsLinebreakHelpers::ConvertPlatformToDOMLinebreaks( aFlavor, &pDataMem,   // pDataMem could be reallocated !!
                                                        reinterpret_cast<PRInt32*>(&NumOfBytes) );  // yuck

  }
  else                             // Assume rest of flavors are binary data
  {
    if (ulFormatID == CF_BITMAP)
    {
      if (!strcmp( aFlavor, kJPEGImageMime ))
      {
        // OS2TODO  Convert bitmap to jpg
#ifdef DEBUG
        printf( "nsClipboard:: No JPG found on clipboard; need to convert BMP\n");
#endif
      }
      else if (!strcmp( aFlavor, kGIFImageMime ))
      {
        // OS2TODO  Convert bitmap to gif
#ifdef DEBUG
        printf( "nsClipboard:: No GIF found on clipboard; need to convert BMP\n");
#endif
      }
      else if (!strcmp( aFlavor, kPNGImageMime ))
      {
        // OS2TODO  Convert bitmap to png
#ifdef DEBUG
        printf( "nsClipboard:: No PNG found on clipboard; need to convert BMP\n");
#endif
      }
    }
    else
    {
      pDataMem = static_cast<PBYTE>(pClipboardData) + sizeof(PRUint32);
      NumOfBytes = *(static_cast<PRUint32*>(pClipboardData));
    }
  }

  nsCOMPtr<nsISupports> genericDataWrapper;
  nsPrimitiveHelpers::CreatePrimitiveForData( aFlavor, pDataMem, NumOfBytes, getter_AddRefs(genericDataWrapper) );
#ifdef DEBUG
  nsresult errCode =
#endif
  mTransferable->SetTransferData( aFlavor, genericDataWrapper, NumOfBytes );
#ifdef DEBUG
  if (errCode != NS_OK)
    printf( "nsClipboard:: Error setting data into transferable\n" );
#endif

  if (TempBufAllocated)
    nsMemory::Free(pDataMem);

  return PR_TRUE;
}
コード例 #16
0
ファイル: bfenumerate-impl.cpp プロジェクト: mss/bonjourfoxy
CBFENUMERATE::CBFENUMERATE()
{
    Log(ToNewUnicode(NS_LITERAL_STRING("Enumerate Component Created")));
}
コード例 #17
0
NS_IMETHODIMP nsCertPicker::PickByUsage(nsIInterfaceRequestor *ctx, 
                                        const PRUnichar *selectedNickname, 
                                        PRInt32 certUsage, 
                                        bool allowInvalid, 
                                        bool allowDuplicateNicknames, 
                                        bool *canceled, 
                                        nsIX509Cert **_retval)
{
  nsNSSShutDownPreventionLock locker;
  PRInt32 selectedIndex = -1;
  bool selectionFound = false;
  PRUnichar **certNicknameList = nsnull;
  PRUnichar **certDetailsList = nsnull;
  CERTCertListNode* node = nsnull;
  nsresult rv = NS_OK;

  {
    // Iterate over all certs. This assures that user is logged in to all hardware tokens.
    CERTCertList *allcerts = nsnull;
    nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext();
    allcerts = PK11_ListCerts(PK11CertListUnique, ctx);
    CERT_DestroyCertList(allcerts);
  }

  /* find all user certs that are valid and for SSL */
  /* note that we are allowing expired certs in this list */

  CERTCertList *certList = 
    CERT_FindUserCertsByUsage(CERT_GetDefaultCertDB(), 
                              (SECCertUsage)certUsage,
                              !allowDuplicateNicknames,
                              !allowInvalid,
                              ctx);
  CERTCertListCleaner clc(certList);

  if (!certList) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  CERTCertNicknames *nicknames = getNSSCertNicknamesFromCertList(certList);

  CERTCertNicknamesCleaner cnc(nicknames);

  if (!nicknames) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  certNicknameList = (PRUnichar **)nsMemory::Alloc(sizeof(PRUnichar *) * nicknames->numnicknames);
  certDetailsList = (PRUnichar **)nsMemory::Alloc(sizeof(PRUnichar *) * nicknames->numnicknames);

  if (!certNicknameList || !certDetailsList) {
    nsMemory::Free(certNicknameList);
    nsMemory::Free(certDetailsList);
    return NS_ERROR_OUT_OF_MEMORY;
  }

  PRInt32 CertsToUse;

  for (CertsToUse = 0, node = CERT_LIST_HEAD(certList);
       !CERT_LIST_END(node, certList) && CertsToUse < nicknames->numnicknames;
       node = CERT_LIST_NEXT(node)
      )
  {
    nsNSSCertificate *tempCert = nsNSSCertificate::Create(node->cert);

    if (tempCert) {

      // XXX we really should be using an nsCOMPtr instead of manually add-refing,
      // but nsNSSCertificate does not have a default constructor.

      NS_ADDREF(tempCert);

      nsAutoString i_nickname(NS_ConvertUTF8toUTF16(nicknames->nicknames[CertsToUse]));
      nsAutoString nickWithSerial;
      nsAutoString details;

      if (!selectionFound) {
        if (i_nickname == nsDependentString(selectedNickname)) {
          selectedIndex = CertsToUse;
          selectionFound = PR_TRUE;
        }
      }

      if (NS_SUCCEEDED(tempCert->FormatUIStrings(i_nickname, nickWithSerial, details))) {
        certNicknameList[CertsToUse] = ToNewUnicode(nickWithSerial);
        certDetailsList[CertsToUse] = ToNewUnicode(details);
      }
      else {
        certNicknameList[CertsToUse] = nsnull;
        certDetailsList[CertsToUse] = nsnull;
      }

      NS_RELEASE(tempCert);

      ++CertsToUse;
    }
  }

  if (CertsToUse) {
    nsICertPickDialogs *dialogs = nsnull;
    rv = getNSSDialogs((void**)&dialogs, 
      NS_GET_IID(nsICertPickDialogs), 
      NS_CERTPICKDIALOGS_CONTRACTID);

    if (NS_SUCCEEDED(rv)) {
      nsPSMUITracker tracker;
      if (tracker.isUIForbidden()) {
        rv = NS_ERROR_NOT_AVAILABLE;
      }
      else {
        /* Throw up the cert picker dialog and get back the index of the selected cert */
        rv = dialogs->PickCertificate(ctx,
          (const PRUnichar**)certNicknameList, (const PRUnichar**)certDetailsList,
          CertsToUse, &selectedIndex, canceled);
      }

      NS_RELEASE(dialogs);
    }
  }

  PRInt32 i;
  for (i = 0; i < CertsToUse; ++i) {
    nsMemory::Free(certNicknameList[i]);
    nsMemory::Free(certDetailsList[i]);
  }
  nsMemory::Free(certNicknameList);
  nsMemory::Free(certDetailsList);
  
  if (!CertsToUse) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  if (NS_SUCCEEDED(rv) && !*canceled) {
    for (i = 0, node = CERT_LIST_HEAD(certList);
         !CERT_LIST_END(node, certList);
         ++i, node = CERT_LIST_NEXT(node)) {

      if (i == selectedIndex) {
        nsNSSCertificate *cert = nsNSSCertificate::Create(node->cert);
        if (!cert) {
          rv = NS_ERROR_OUT_OF_MEMORY;
          break;
        }

        nsIX509Cert *x509 = 0;
        nsresult rv = cert->QueryInterface(NS_GET_IID(nsIX509Cert), (void**)&x509);
        if (NS_FAILED(rv)) {
          break;
        }

        NS_ADDREF(x509);
        *_retval = x509;
        NS_RELEASE(cert);
        break;
      }
    }
  }

  return rv;
}
コード例 #18
0
ファイル: bfenumerate-impl.cpp プロジェクト: mss/bonjourfoxy
CBFENUMERATE::~CBFENUMERATE()
{
    if (mTimer) mTimer->Cancel();
    DNSServiceRefDeallocate(mSdRef);
    Log(ToNewUnicode(NS_LITERAL_STRING("Enumerate Component Destroyed")));
}
コード例 #19
0
/* attribute wstring printCommand; */
NS_IMETHODIMP nsPrintSettings::GetPrintCommand(PRUnichar * *aPrintCommand)
{
    //NS_ENSURE_ARG_POINTER(aPrintCommand);
    *aPrintCommand = ToNewUnicode(mPrintCommand);
    return NS_OK;
}
コード例 #20
0
// wrapper for ldap_get_values()
//
NS_IMETHODIMP
nsLDAPMessage::GetValues(const char *aAttr, uint32_t *aCount, 
                         char16_t ***aValues)
{
    char **values;
    
#if defined(DEBUG)
    // We only want this being logged for debug builds so as not to affect performance too much.
    MOZ_LOG(gLDAPLogModule, mozilla::LogLevel::Debug,
           ("nsLDAPMessage::GetValues(): called with aAttr = '%s'", aAttr));
#endif

    values = ldap_get_values(mConnectionHandle, mMsgHandle, aAttr);

    // bail out if there was a problem
    //
    if (!values) {
        int32_t lderrno = ldap_get_lderrno(mConnectionHandle, 0, 0);

        if ( lderrno == LDAP_DECODING_ERROR ) {
            // this may not be an error; it could just be that the 
            // caller has asked for an attribute that doesn't exist.
            //
            MOZ_LOG(gLDAPLogModule, mozilla::LogLevel::Warning, 
                   ("nsLDAPMessage::GetValues(): ldap_get_values returned "
                    "LDAP_DECODING_ERROR"));
            return NS_ERROR_LDAP_DECODING_ERROR;

        } else if ( lderrno == LDAP_PARAM_ERROR ) {
            NS_ERROR("nsLDAPMessage::GetValues(): internal error: 1");
            return NS_ERROR_UNEXPECTED;

        } else {
            NS_ERROR("nsLDAPMessage::GetValues(): internal error: 2");
            return NS_ERROR_UNEXPECTED;
        }
    }

    // count the values
    //
    uint32_t numVals = ldap_count_values(values);

    // create an array of the appropriate size
    //
    *aValues = static_cast<char16_t **>(moz_xmalloc(numVals * sizeof(char16_t *)));
    if (!*aValues) {
        ldap_value_free(values);
        return NS_ERROR_OUT_OF_MEMORY;
    }

    // clone the array (except for the trailing NULL entry) using the 
    // shared allocator for XPCOM correctness
    //
    uint32_t i;
    for ( i = 0 ; i < numVals ; i++ ) {
        nsDependentCString sValue(values[i]);
        if (IsUTF8(sValue))
            (*aValues)[i] = ToNewUnicode(NS_ConvertUTF8toUTF16(sValue));
        else
            (*aValues)[i] = ToNewUnicode(NS_ConvertASCIItoUTF16(sValue));
        if ( ! (*aValues)[i] ) {
            NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(i, aValues);
            ldap_value_free(values);
            return NS_ERROR_OUT_OF_MEMORY;
        }
    }

    // now free our value array since we already cloned the values array 
    // to the 'aValues' results array.
    ldap_value_free(values);

    *aCount = numVals;
    return NS_OK;
}
コード例 #21
0
// return the possible root forms of aWord.
NS_IMETHODIMP mozEnglishWordUtils::GetRootForm(const char16_t *aWord, uint32_t type, char16_t ***words, uint32_t *count)
{
  nsAutoString word(aWord);
  char16_t **tmpPtr;
  int32_t length = word.Length();

  *count = 0;

  mozEnglishWordUtils::myspCapitalization ct = captype(word);
  switch (ct)
    {
    case HuhCap:
    case NoCap:
      tmpPtr = (char16_t **)moz_xmalloc(sizeof(char16_t *));
      if (!tmpPtr)
        return NS_ERROR_OUT_OF_MEMORY;
      tmpPtr[0] = ToNewUnicode(word);
      if (!tmpPtr[0]) {
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(0, tmpPtr);
        return NS_ERROR_OUT_OF_MEMORY;
      }
      *words = tmpPtr;
      *count = 1;
      break;


    case AllCap:
      tmpPtr = (char16_t **)moz_xmalloc(sizeof(char16_t *) * 3);
      if (!tmpPtr)
        return NS_ERROR_OUT_OF_MEMORY;
      tmpPtr[0] = ToNewUnicode(word);
      if (!tmpPtr[0]) {
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(0, tmpPtr);
        return NS_ERROR_OUT_OF_MEMORY;
      }
      ToLowerCase(tmpPtr[0], tmpPtr[0], length);

      tmpPtr[1] = ToNewUnicode(word);
      if (!tmpPtr[1]) {
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(1, tmpPtr);
        return NS_ERROR_OUT_OF_MEMORY;
      }
      ToLowerCase(tmpPtr[1], tmpPtr[1], length);
      ToUpperCase(tmpPtr[1], tmpPtr[1], 1);

      tmpPtr[2] = ToNewUnicode(word);
      if (!tmpPtr[2]) {
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(2, tmpPtr);
        return NS_ERROR_OUT_OF_MEMORY;
      }

      *words = tmpPtr;
      *count = 3;
      break;

    case InitCap:
      tmpPtr = (char16_t **)moz_xmalloc(sizeof(char16_t *) * 2);
      if (!tmpPtr)
        return NS_ERROR_OUT_OF_MEMORY;

      tmpPtr[0] = ToNewUnicode(word);
      if (!tmpPtr[0]) {
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(0, tmpPtr);
        return NS_ERROR_OUT_OF_MEMORY;
      }
      ToLowerCase(tmpPtr[0], tmpPtr[0], length);

      tmpPtr[1] = ToNewUnicode(word);
      if (!tmpPtr[1]) {
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(1, tmpPtr);
        return NS_ERROR_OUT_OF_MEMORY;
      }

      *words = tmpPtr;
      *count = 2;
      break;
    default:
      return NS_ERROR_FAILURE; // should never get here;
    }
  return NS_OK;
}
コード例 #22
0
NS_IMETHODIMP nsScriptableDateFormat::FormatDateTime(
                            const PRUnichar *aLocale, 
                            nsDateFormatSelector dateFormatSelector, 
                            nsTimeFormatSelector timeFormatSelector, 
                            int32_t year, 
                            int32_t month, 
                            int32_t day, 
                            int32_t hour, 
                            int32_t minute, 
                            int32_t second, 
                            PRUnichar **dateTimeString)
{
  // We can't have a valid date with the year, month or day
  // being lower than 1.
  if (year < 1 || month < 1 || day < 1)
    return NS_ERROR_INVALID_ARG;

  nsresult rv;
  nsAutoString localeName(aLocale);
  *dateTimeString = nullptr;

  nsCOMPtr<nsILocale> locale;
  // re-initialise locale pointer only if the locale was given explicitly
  if (!localeName.IsEmpty()) {
    // get locale service
    nsCOMPtr<nsILocaleService> localeService(do_GetService(kLocaleServiceCID, &rv));
    NS_ENSURE_SUCCESS(rv, rv);
    // get locale
    rv = localeService->NewLocale(localeName, getter_AddRefs(locale));
    NS_ENSURE_SUCCESS(rv, rv);
  }

  nsCOMPtr<nsIDateTimeFormat> dateTimeFormat(do_CreateInstance(kDateTimeFormatCID, &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  tm tmTime;
  time_t timetTime;

  memset(&tmTime, 0, sizeof(tmTime));
  tmTime.tm_year = year - 1900;
  tmTime.tm_mon = month - 1;
  tmTime.tm_mday = day;
  tmTime.tm_hour = hour;
  tmTime.tm_min = minute;
  tmTime.tm_sec = second;
  tmTime.tm_yday = tmTime.tm_wday = 0;
  tmTime.tm_isdst = -1;
  timetTime = mktime(&tmTime);

  if ((time_t)-1 != timetTime) {
    rv = dateTimeFormat->FormatTime(locale, dateFormatSelector, timeFormatSelector, 
                                     timetTime, mStringOut);
  }
  else {
    // if mktime fails (e.g. year <= 1970), then try NSPR.
    PRTime prtime;
    char string[32];
    sprintf(string, "%.2d/%.2d/%d %.2d:%.2d:%.2d", month, day, year, hour, minute, second);
    if (PR_SUCCESS != PR_ParseTimeString(string, false, &prtime))
      return NS_ERROR_INVALID_ARG;

    rv = dateTimeFormat->FormatPRTime(locale, dateFormatSelector, timeFormatSelector, 
                                      prtime, mStringOut);
  }
  if (NS_SUCCEEDED(rv))
    *dateTimeString = ToNewUnicode(mStringOut);

  return rv;
}
コード例 #23
0
NS_IMETHODIMP
nsSimplePageSequenceFrame::Reflow(nsPresContext*          aPresContext,
                                  nsHTMLReflowMetrics&     aDesiredSize,
                                  const nsHTMLReflowState& aReflowState,
                                  nsReflowStatus&          aStatus)
{
  NS_PRECONDITION(aPresContext->IsRootPaginatedDocument(),
                  "A Page Sequence is only for real pages");
  DO_GLOBAL_REFLOW_COUNT("nsSimplePageSequenceFrame");
  DISPLAY_REFLOW(aPresContext, this, aReflowState, aDesiredSize, aStatus);
  NS_FRAME_TRACE_REFLOW_IN("nsSimplePageSequenceFrame::Reflow");

  aStatus = NS_FRAME_COMPLETE;  // we're always complete

  // Don't do incremental reflow until we've taught tables how to do
  // it right in paginated mode.
  if (!(GetStateBits() & NS_FRAME_FIRST_REFLOW)) {
    // Return our desired size
    aDesiredSize.height  = mSize.height * PresContext()->GetPrintPreviewScale();
    aDesiredSize.width   = mSize.width * PresContext()->GetPrintPreviewScale();
    aDesiredSize.SetOverflowAreasToDesiredBounds();
    FinishAndStoreOverflow(&aDesiredSize);
    return NS_OK;
  }

  PRBool isPrintPreview =
    aPresContext->Type() == nsPresContext::eContext_PrintPreview;

  // See if we can get a Print Settings from the Context
  if (!mPageData->mPrintSettings &&
      aPresContext->Medium() == nsGkAtoms::print) {
      mPageData->mPrintSettings = aPresContext->GetPrintSettings();
  }

  // now get out margins & edges
  if (mPageData->mPrintSettings) {
    nsIntMargin unwriteableTwips;
    mPageData->mPrintSettings->GetUnwriteableMarginInTwips(unwriteableTwips);
    NS_ASSERTION(unwriteableTwips.left  >= 0 && unwriteableTwips.top >= 0 &&
                 unwriteableTwips.right >= 0 && unwriteableTwips.bottom >= 0,
                 "Unwriteable twips should be non-negative");

    nsIntMargin marginTwips;
    mPageData->mPrintSettings->GetMarginInTwips(marginTwips);
    mMargin = aPresContext->CSSTwipsToAppUnits(marginTwips + unwriteableTwips);

    PRInt16 printType;
    mPageData->mPrintSettings->GetPrintRange(&printType);
    mPrintRangeType = printType;

    nsIntMargin edgeTwips;
    mPageData->mPrintSettings->GetEdgeInTwips(edgeTwips);

    // sanity check the values. three inches are sometimes needed
    PRInt32 inchInTwips = NS_INCHES_TO_INT_TWIPS(3.0);
    edgeTwips.top = NS_MIN(NS_MAX(edgeTwips.top, 0), inchInTwips);
    edgeTwips.bottom = NS_MIN(NS_MAX(edgeTwips.bottom, 0), inchInTwips);
    edgeTwips.left = NS_MIN(NS_MAX(edgeTwips.left, 0), inchInTwips);
    edgeTwips.right = NS_MIN(NS_MAX(edgeTwips.right, 0), inchInTwips);

    mPageData->mEdgePaperMargin =
      aPresContext->CSSTwipsToAppUnits(edgeTwips + unwriteableTwips);
  }

  // *** Special Override ***
  // If this is a sub-sdoc (meaning it doesn't take the whole page)
  // and if this Document is in the upper left hand corner
  // we need to suppress the top margin or it will reflow too small

  nsSize pageSize = aPresContext->GetPageSize();

  mPageData->mReflowSize = pageSize;
  // If we're printing a selection, we need to reflow with
  // unconstrained height, to make sure we'll get to the selection
  // even if it's beyond the first page of content.
  if (nsIPrintSettings::kRangeSelection == mPrintRangeType) {
    mPageData->mReflowSize.height = NS_UNCONSTRAINEDSIZE;
  }
  mPageData->mReflowMargin = mMargin;

  // Compute the size of each page and the x coordinate that each page will
  // be placed at
  nscoord extraThreshold = NS_MAX(pageSize.width, pageSize.height)/10;
  PRInt32 gapInTwips = nsContentUtils::GetIntPref("print.print_extra_margin");
  gapInTwips = NS_MAX(0, gapInTwips);

  nscoord extraGap = aPresContext->CSSTwipsToAppUnits(gapInTwips);
  extraGap = NS_MIN(extraGap, extraThreshold); // clamp to 1/10 of the largest dim of the page

  nscoord  deadSpaceGap = 0;
  if (isPrintPreview) {
    GetDeadSpaceValue(&gapInTwips);
    deadSpaceGap = aPresContext->CSSTwipsToAppUnits(gapInTwips);
  }

  nsMargin extraMargin(0,0,0,0);
  nsSize   shadowSize(0,0);
  if (aPresContext->IsScreen()) {
    extraMargin.SizeTo(extraGap, extraGap, extraGap, extraGap);
    nscoord fourPixels = nsPresContext::CSSPixelsToAppUnits(4);
    shadowSize.SizeTo(fourPixels, fourPixels);
  }

  mPageData->mShadowSize      = shadowSize;
  mPageData->mExtraMargin     = extraMargin;

  const nscoord x = deadSpaceGap;
  nscoord y = deadSpaceGap;// Running y-offset for each page

  nsSize availSize(pageSize.width + shadowSize.width + extraMargin.LeftRight(),
                   pageSize.height + shadowSize.height +
                   extraMargin.TopBottom());

  // Tile the pages vertically
  nsHTMLReflowMetrics kidSize;
  for (nsIFrame* kidFrame = mFrames.FirstChild(); nsnull != kidFrame; ) {
    // Set the shared data into the page frame before reflow
    nsPageFrame * pf = static_cast<nsPageFrame*>(kidFrame);
    pf->SetSharedPageData(mPageData);

    // Reflow the page
    nsHTMLReflowState kidReflowState(aPresContext, aReflowState, kidFrame,
                                     availSize);
    nsReflowStatus  status;

    kidReflowState.SetComputedWidth(kidReflowState.availableWidth);
    //kidReflowState.SetComputedHeight(kidReflowState.availableHeight);
    PR_PL(("AV W: %d   H: %d\n", kidReflowState.availableWidth, kidReflowState.availableHeight));

    // Place and size the page. If the page is narrower than our
    // max width then center it horizontally
    ReflowChild(kidFrame, aPresContext, kidSize, kidReflowState, x, y, 0, status);

    FinishReflowChild(kidFrame, aPresContext, nsnull, kidSize, x, y, 0);
    y += kidSize.height;

    // Leave a slight gap between the pages
    y += deadSpaceGap;

    // Is the page complete?
    nsIFrame* kidNextInFlow = kidFrame->GetNextInFlow();

    if (NS_FRAME_IS_FULLY_COMPLETE(status)) {
      NS_ASSERTION(!kidNextInFlow, "bad child flow list");
    } else if (!kidNextInFlow) {
      // The page isn't complete and it doesn't have a next-in-flow, so
      // create a continuing page.
      nsIFrame* continuingPage;
      nsresult rv = aPresContext->PresShell()->FrameConstructor()->
        CreateContinuingFrame(aPresContext, kidFrame, this, &continuingPage);
      if (NS_FAILED(rv)) {
        break;
      }

      // Add it to our child list
      mFrames.InsertFrame(nsnull, kidFrame, continuingPage);
    }

    // Get the next page
    kidFrame = kidFrame->GetNextSibling();
  }

  // Get Total Page Count
  nsIFrame* page;
  PRInt32 pageTot = 0;
  for (page = mFrames.FirstChild(); page; page = page->GetNextSibling()) {
    pageTot++;
  }

  // Set Page Number Info
  PRInt32 pageNum = 1;
  for (page = mFrames.FirstChild(); page; page = page->GetNextSibling()) {
    nsPageFrame * pf = static_cast<nsPageFrame*>(page);
    if (pf != nsnull) {
      pf->SetPageNumInfo(pageNum, pageTot);
    }
    pageNum++;
  }

  // Create current Date/Time String
  if (!mDateFormatter)
    mDateFormatter = do_CreateInstance(NS_DATETIMEFORMAT_CONTRACTID);

  NS_ENSURE_TRUE(mDateFormatter, NS_ERROR_FAILURE);

  nsAutoString formattedDateString;
  time_t ltime;
  time( &ltime );
  if (NS_SUCCEEDED(mDateFormatter->FormatTime(nsnull /* nsILocale* locale */,
                                              kDateFormatShort,
                                              kTimeFormatNoSeconds,
                                              ltime,
                                              formattedDateString))) {
    PRUnichar * uStr = ToNewUnicode(formattedDateString);
    SetDateTimeStr(uStr); // memory will be freed
  }

  // Return our desired size
  // Adjustr the reflow size by PrintPreviewScale so the scrollbars end up the
  // correct size
  nscoord w = (x + availSize.width + deadSpaceGap);
  aDesiredSize.height  = y * PresContext()->GetPrintPreviewScale(); // includes page heights and dead space
  aDesiredSize.width   = w * PresContext()->GetPrintPreviewScale();

  aDesiredSize.SetOverflowAreasToDesiredBounds();
  FinishAndStoreOverflow(&aDesiredSize);

  // cache the size so we can set the desired size 
  // for the other reflows that happen
  mSize.width  = w;
  mSize.height = y;

  NS_FRAME_TRACE_REFLOW_OUT("nsSimplePageSequeceFrame::Reflow", aStatus);
  NS_FRAME_SET_TRUNCATION(aStatus, aReflowState, aDesiredSize);
  return NS_OK;
}
コード例 #24
0
NS_IMETHODIMP nsFilePicker::ShowW(PRInt16 *aReturnVal)
{
  NS_ENSURE_ARG_POINTER(aReturnVal);

  // suppress blur events
  if (mParentWidget) {
    nsIWidget *tmp = mParentWidget;
    nsWindow *parent = static_cast<nsWindow *>(tmp);
    parent->SuppressBlurEvents(PR_TRUE);
  }

  PRBool result = PR_FALSE;
  PRUnichar fileBuffer[FILE_BUFFER_SIZE+1];
  wcsncpy(fileBuffer,  mDefault.get(), FILE_BUFFER_SIZE);
  fileBuffer[FILE_BUFFER_SIZE] = '\0'; // null terminate in case copy truncated

  NS_NAMED_LITERAL_STRING(htmExt, "html");
  nsAutoString initialDir;
  if (mDisplayDirectory)
    mDisplayDirectory->GetPath(initialDir);

  // If no display directory, re-use the last one.
  if(initialDir.IsEmpty()) {
    // Allocate copy of last used dir.
    initialDir = mLastUsedUnicodeDirectory;
  }

  mUnicodeFile.Truncate();

#ifndef WINCE_WINDOWS_MOBILE

  if (mMode == modeGetFolder) {
    PRUnichar dirBuffer[MAX_PATH+1];
    wcsncpy(dirBuffer, initialDir.get(), MAX_PATH);

    BROWSEINFOW browserInfo;
    browserInfo.hwndOwner      = (HWND)
      (mParentWidget.get() ? mParentWidget->GetNativeData(NS_NATIVE_WINDOW) : 0); 
    browserInfo.pidlRoot       = nsnull;
    browserInfo.pszDisplayName = (LPWSTR)dirBuffer;
    browserInfo.lpszTitle      = mTitle.get();
    browserInfo.ulFlags        = BIF_USENEWUI | BIF_RETURNONLYFSDIRS;
    if (initialDir.Length())
    {
      // the dialog is modal so that |initialDir.get()| will be valid in 
      // BrowserCallbackProc. Thus, we don't need to clone it.
      browserInfo.lParam       = (LPARAM) initialDir.get();
      browserInfo.lpfn         = &BrowseCallbackProc;
    }
    else
    {
    browserInfo.lParam         = nsnull;
      browserInfo.lpfn         = nsnull;
    }
    browserInfo.iImage         = nsnull;

    LPITEMIDLIST list = ::SHBrowseForFolderW(&browserInfo);
    if (list != NULL) {
      result = ::SHGetPathFromIDListW(list, (LPWSTR)fileBuffer);
      if (result) {
          mUnicodeFile.Assign(fileBuffer);
      }
  
      // free PIDL
      CoTaskMemFree(list);
    }
  }
  else 
#endif // WINCE_WINDOWS_MOBILE
  {

    OPENFILENAMEW ofn;
    memset(&ofn, 0, sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);
    nsString filterBuffer = mFilterList;
                                  
    if (!initialDir.IsEmpty()) {
      ofn.lpstrInitialDir = initialDir.get();
    }
    
    ofn.lpstrTitle   = (LPCWSTR)mTitle.get();
    ofn.lpstrFilter  = (LPCWSTR)filterBuffer.get();
    ofn.nFilterIndex = mSelectedType;
#ifdef WINCE_WINDOWS_MOBILE
    // If we're running fullscreen the dialog inherits that, which is bad
    ofn.hwndOwner    = (HWND) 0;
#else
    ofn.hwndOwner    = (HWND) (mParentWidget.get() ? mParentWidget->GetNativeData(NS_NATIVE_WINDOW) : 0); 
#endif
    ofn.lpstrFile    = fileBuffer;
    ofn.nMaxFile     = FILE_BUFFER_SIZE;

    ofn.Flags = OFN_NOCHANGEDIR | OFN_SHAREAWARE | OFN_LONGNAMES | OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST;

    if (!mDefaultExtension.IsEmpty()) {
      ofn.lpstrDefExt = mDefaultExtension.get();
    }
    else {
      // Get file extension from suggested filename
      //  to detect if we are saving an html file
      //XXX: nsIFile SHOULD HAVE A GetExtension() METHOD!
      PRInt32 extIndex = mDefault.RFind(".");
      if ( extIndex >= 0) {
        nsAutoString ext;
        mDefault.Right(ext, mDefault.Length() - extIndex);
        // Should we test for ".cgi", ".asp", ".jsp" and other
        // "generated" html pages?

        if ( ext.LowerCaseEqualsLiteral(".htm")  ||
             ext.LowerCaseEqualsLiteral(".html") ||
             ext.LowerCaseEqualsLiteral(".shtml") ) {
          // This is supposed to append ".htm" if user doesn't supply an extension
          //XXX Actually, behavior is sort of weird:
          //    often appends ".html" even if you have an extension
          //    It obeys your extension if you put quotes around name
          ofn.lpstrDefExt = htmExt.get();
        }
      }
    }

#ifndef WINCE
    try {
#endif
      if (mMode == modeOpen) {
        // FILE MUST EXIST!
        ofn.Flags |= OFN_FILEMUSTEXIST;
        result = ::GetOpenFileNameW(&ofn);
      }
      else if (mMode == modeOpenMultiple) {
        ofn.Flags |= OFN_FILEMUSTEXIST | OFN_ALLOWMULTISELECT | OFN_EXPLORER;
        result = ::GetOpenFileNameW(&ofn);
      }
      else if (mMode == modeSave) {
        ofn.Flags |= OFN_NOREADONLYRETURN;

        // Don't follow shortcuts when saving a shortcut, this can be used
        // to trick users (bug 271732)
        NS_ConvertUTF16toUTF8 ext(mDefault);
        ext.Trim(" .", PR_FALSE, PR_TRUE); // watch out for trailing space and dots
        ToLowerCase(ext);
        if (StringEndsWith(ext, NS_LITERAL_CSTRING(".lnk")) ||
            StringEndsWith(ext, NS_LITERAL_CSTRING(".pif")) ||
            StringEndsWith(ext, NS_LITERAL_CSTRING(".url")))
          ofn.Flags |= OFN_NODEREFERENCELINKS;

        result = ::GetSaveFileNameW(&ofn);
        if (!result) {
          // Error, find out what kind.
          if (::GetLastError() == ERROR_INVALID_PARAMETER 
#ifndef WINCE
              || ::CommDlgExtendedError() == FNERR_INVALIDFILENAME
#endif
              ) {
            // probably the default file name is too long or contains illegal characters!
            // Try again, without a starting file name.
            ofn.lpstrFile[0] = 0;
            result = ::GetSaveFileNameW(&ofn);
          }
        }
      } 
#ifdef WINCE_WINDOWS_MOBILE
      else if (mMode == modeGetFolder) {
        ofn.Flags = OFN_PROJECT | OFN_FILEMUSTEXIST;
        result = ::GetOpenFileNameW(&ofn);
      }
#endif
      else {
        NS_ERROR("unsupported mode"); 
      }
#ifndef WINCE
    }
    catch(...) {
      MessageBoxW(ofn.hwndOwner,
                  0,
                  L"The filepicker was unexpectedly closed by Windows.",
                  MB_ICONERROR);
      result = PR_FALSE;
    }
#endif
  
    if (result) {
      // Remember what filter type the user selected
      mSelectedType = (PRInt16)ofn.nFilterIndex;

      // Set user-selected location of file or directory
      if (mMode == modeOpenMultiple) {
        
        // from msdn.microsoft.com, "Open and Save As Dialog Boxes" section:
        // If you specify OFN_EXPLORER,
        // The directory and file name strings are NULL separated, 
        // with an extra NULL character after the last file name. 
        // This format enables the Explorer-style dialog boxes
        // to return long file names that include spaces. 
        PRUnichar *current = fileBuffer;
        
        nsAutoString dirName(current);
        // sometimes dirName contains a trailing slash
        // and sometimes it doesn't.
        if (current[dirName.Length() - 1] != '\\')
          dirName.Append((PRUnichar)'\\');
        
        nsresult rv;
        while (current && *current && *(current + nsCRT::strlen(current) + 1)) {
          current = current + nsCRT::strlen(current) + 1;
          
          nsCOMPtr<nsILocalFile> file = do_CreateInstance("@mozilla.org/file/local;1", &rv);
          NS_ENSURE_SUCCESS(rv,rv);
          
          rv = file->InitWithPath(dirName + nsDependentString(current));
          NS_ENSURE_SUCCESS(rv,rv);
          
          rv = mFiles.AppendObject(file);
          NS_ENSURE_SUCCESS(rv,rv);
        }
        
        // handle the case where the user selected just one
        // file.  according to msdn.microsoft.com:
        // If you specify OFN_ALLOWMULTISELECT and the user selects 
        // only one file, the lpstrFile string does not have 
        // a separator between the path and file name.
        if (current && *current && (current == fileBuffer)) {
          nsCOMPtr<nsILocalFile> file = do_CreateInstance("@mozilla.org/file/local;1", &rv);
          NS_ENSURE_SUCCESS(rv,rv);
          
          rv = file->InitWithPath(nsDependentString(current));
          NS_ENSURE_SUCCESS(rv,rv);
          
          rv = mFiles.AppendObject(file);
          NS_ENSURE_SUCCESS(rv,rv);
        }
      }
      else {
        // I think it also needs a conversion here (to unicode since appending to nsString) 
        // but doing that generates garbage file name, weird.
        mUnicodeFile.Assign(fileBuffer);
      }
    }

  }

  if (result) {
    PRInt16 returnOKorReplace = returnOK;

    // Remember last used directory.
    nsCOMPtr<nsILocalFile> file(do_CreateInstance("@mozilla.org/file/local;1"));
    NS_ENSURE_TRUE(file, NS_ERROR_FAILURE);

    // XXX  InitWithPath() will convert UCS2 to FS path !!!  corrupts unicode 
    file->InitWithPath(mUnicodeFile);
    nsCOMPtr<nsIFile> dir;
    if (NS_SUCCEEDED(file->GetParent(getter_AddRefs(dir)))) {
      mDisplayDirectory = do_QueryInterface(dir);
      if (mDisplayDirectory) {
        if (mLastUsedUnicodeDirectory) {
          NS_Free(mLastUsedUnicodeDirectory);
          mLastUsedUnicodeDirectory = nsnull;
        }

        nsAutoString newDir;
        mDisplayDirectory->GetPath(newDir);
        if(!newDir.IsEmpty())
          mLastUsedUnicodeDirectory = ToNewUnicode(newDir);
      }
    }

    if (mMode == modeSave) {
      // Windows does not return resultReplace,
      //   we must check if file already exists
      PRBool exists = PR_FALSE;
      file->Exists(&exists);

      if (exists)
        returnOKorReplace = returnReplace;
    }
    *aReturnVal = returnOKorReplace;
  }
  else {
    *aReturnVal = returnCancel;
  }
  if (mParentWidget) {
    nsIWidget *tmp = mParentWidget;
    nsWindow *parent = static_cast<nsWindow *>(tmp);
    parent->SuppressBlurEvents(PR_FALSE);
  }

  return NS_OK;
}
コード例 #25
0
/* attribute wstring searchString; */
NS_IMETHODIMP nsWebBrowserFind::GetSearchString(char16_t * *aSearchString)
{
    NS_ENSURE_ARG_POINTER(aSearchString);
    *aSearchString = ToNewUnicode(mSearchString);
    return NS_OK;
}
コード例 #26
0
NS_IMETHODIMP nsSMimeJSHelper::GetNoCertAddresses(
    nsIMsgCompFields *compFields,
    PRUint32 *count,
    PRUnichar ***emailAddresses)
{
  NS_ENSURE_ARG_POINTER(count);
  *count = 0;

  NS_ENSURE_ARG_POINTER(emailAddresses);

  NS_ENSURE_ARG_POINTER(compFields);

  PRUint32 mailbox_count;
  char *mailbox_list;

  nsresult rv = getMailboxList(compFields, &mailbox_count, &mailbox_list);
  if (NS_FAILED(rv))
    return rv;

  if (!mailbox_list)
    return NS_ERROR_FAILURE;

  if (!mailbox_count)
  {
    *count = 0;
    *emailAddresses = nsnull;
    if (mailbox_list) {
      nsMemory::Free(mailbox_list);
    }
    return NS_OK;
  }

  nsCOMPtr<nsIX509CertDB> certdb = do_GetService(NS_X509CERTDB_CONTRACTID);

  PRUint32 missing_count = 0;
  PRBool *haveCert = new PRBool[mailbox_count];
  if (!haveCert)
  {
    if (mailbox_list) {
      nsMemory::Free(mailbox_list);
    }
    return NS_ERROR_OUT_OF_MEMORY;
  }

  rv = NS_OK;

  if (mailbox_count)
  {
    const char *walk = mailbox_list;

    // To understand this loop, especially the "+= strlen +1", look at the documentation
    // of ParseHeaderAddresses. Basically, it returns a list of zero terminated strings.
    for (PRUint32 i = 0;
        i < mailbox_count;
        ++i, walk += strlen(walk) + 1)
    {
      haveCert[i] = PR_FALSE;

      nsDependentCString email(walk);
      nsCString email_lowercase;
      ToLowerCase(email, email_lowercase);

      nsCOMPtr<nsIX509Cert> cert;
      if (NS_SUCCEEDED(certdb->FindCertByEmailAddress(nsnull, email_lowercase.get(), getter_AddRefs(cert)))
          && cert)
      {
        PRUint32 verification_result;

        if (NS_SUCCEEDED(
              cert->VerifyForUsage(nsIX509Cert::CERT_USAGE_EmailRecipient, &verification_result))
            &&
            nsIX509Cert::VERIFIED_OK == verification_result)
        {
          haveCert[i] = PR_TRUE;
        }
      }

      if (!haveCert[i])
        ++missing_count;
    }
  }

  *count = missing_count;

  if (missing_count)
  {
    PRUnichar **outEA = static_cast<PRUnichar **>(nsMemory::Alloc(missing_count * sizeof(PRUnichar *)));
    if (!outEA )
    {
      rv = NS_ERROR_OUT_OF_MEMORY;
    }
    else
    {
      PRUnichar **iEA = outEA;
      const char *walk = mailbox_list;

      PRBool memory_failure = PR_FALSE;

      // To understand this loop, especially the "+= strlen +1", look at the documentation
      // of ParseHeaderAddresses. Basically, it returns a list of zero terminated strings.
      for (PRUint32 i = 0;
          i < mailbox_count;
          ++i, walk += strlen(walk) + 1)
      {
        if (!haveCert[i])
        {
          if (memory_failure) {
            *iEA = nsnull;
          }
          else {
            *iEA = ToNewUnicode(nsDependentCString(walk));
            if (!*iEA) {
              memory_failure = PR_TRUE;
            }
          }
          ++iEA;
        }
      }

      if (memory_failure) {
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(missing_count, outEA);
        rv = NS_ERROR_OUT_OF_MEMORY;
      }
      else {
        *emailAddresses = outEA;
      }
    }
  }
  else
  {
    *emailAddresses = nsnull;
  }

  delete [] haveCert;
  if (mailbox_list) {
    nsMemory::Free(mailbox_list);
  }
  return rv;
}
コード例 #27
0
NS_IMETHODIMP
nsStringBundleService::FormatStatusMessage(nsresult aStatus,
                                           const PRUnichar* aStatusArg,
                                           PRUnichar* *result)
{
  nsresult rv;
  PRUint32 i, argCount = 0;
  nsCOMPtr<nsIStringBundle> bundle;
  nsXPIDLCString stringBundleURL;

  // XXX hack for mailnews who has already formatted their messages:
  if (aStatus == NS_OK && aStatusArg) {
    *result = nsCRT::strdup(aStatusArg);
    NS_ENSURE_TRUE(*result, NS_ERROR_OUT_OF_MEMORY);
    return NS_OK;
  }

  if (aStatus == NS_OK) {
    return NS_ERROR_FAILURE;       // no message to format
  }

  // format the arguments:
  const nsDependentString args(aStatusArg);
  argCount = args.CountChar(PRUnichar('\n')) + 1;
  NS_ENSURE_ARG(argCount <= 10); // enforce 10-parameter limit
  PRUnichar* argArray[10];

  // convert the aStatusArg into a PRUnichar array
  if (argCount == 1) {
    // avoid construction for the simple case:
    argArray[0] = (PRUnichar*)aStatusArg;
  }
  else if (argCount > 1) {
    PRInt32 offset = 0;
    for (i = 0; i < argCount; i++) {
      PRInt32 pos = args.FindChar('\n', offset);
      if (pos == -1) 
        pos = args.Length();
      argArray[i] = ToNewUnicode(Substring(args, offset, pos - offset));
      if (argArray[i] == nsnull) {
        rv = NS_ERROR_OUT_OF_MEMORY;
        argCount = i - 1; // don't try to free uninitialized memory
        goto done;
      }
      offset = pos + 1;
    }
  }

  // find the string bundle for the error's module:
  rv = mErrorService->GetErrorStringBundle(NS_ERROR_GET_MODULE(aStatus), 
                                           getter_Copies(stringBundleURL));
  if (NS_SUCCEEDED(rv)) {
    rv = getStringBundle(stringBundleURL, getter_AddRefs(bundle));
    if (NS_SUCCEEDED(rv)) {
      rv = FormatWithBundle(bundle, aStatus, argCount, argArray, result);
    }
  }
  if (NS_FAILED(rv)) {
    rv = getStringBundle(GLOBAL_PROPERTIES, getter_AddRefs(bundle));
    if (NS_SUCCEEDED(rv)) {
      rv = FormatWithBundle(bundle, aStatus, argCount, argArray, result);
    }
  }

done:
  if (argCount > 1) {
    for (i = 0; i < argCount; i++) {
      if (argArray[i])
        nsMemory::Free(argArray[i]);
    }
  }
  return rv;
}
コード例 #28
0
NS_IMETHODIMP nsSMimeJSHelper::GetRecipientCertsInfo(
    nsIMsgCompFields *compFields,
    PRUint32 *count,
    PRUnichar ***emailAddresses,
    PRInt32 **certVerification,
    PRUnichar ***certIssuedInfos,
    PRUnichar ***certExpiresInfos,
    nsIX509Cert ***certs,
    PRBool *canEncrypt)
{
  NS_ENSURE_ARG_POINTER(count);
  *count = 0;

  NS_ENSURE_ARG_POINTER(emailAddresses);
  NS_ENSURE_ARG_POINTER(certVerification);
  NS_ENSURE_ARG_POINTER(certIssuedInfos);
  NS_ENSURE_ARG_POINTER(certExpiresInfos);
  NS_ENSURE_ARG_POINTER(certs);
  NS_ENSURE_ARG_POINTER(canEncrypt);

  NS_ENSURE_ARG_POINTER(compFields);

  PRUint32 mailbox_count;
  char *mailbox_list;

  nsresult rv = getMailboxList(compFields, &mailbox_count, &mailbox_list);
  if (NS_FAILED(rv))
    return rv;

  if (!mailbox_list)
    return NS_ERROR_FAILURE;

  nsCOMPtr<nsIX509CertDB> certdb = do_GetService(NS_X509CERTDB_CONTRACTID);

  *count = mailbox_count;
  *canEncrypt = PR_FALSE;
  rv = NS_OK;

  if (mailbox_count)
  {
    PRUnichar **outEA = static_cast<PRUnichar **>(nsMemory::Alloc(mailbox_count * sizeof(PRUnichar *)));
    PRInt32 *outCV = static_cast<PRInt32 *>(nsMemory::Alloc(mailbox_count * sizeof(PRInt32)));
    PRUnichar **outCII = static_cast<PRUnichar **>(nsMemory::Alloc(mailbox_count * sizeof(PRUnichar *)));
    PRUnichar **outCEI = static_cast<PRUnichar **>(nsMemory::Alloc(mailbox_count * sizeof(PRUnichar *)));
    nsIX509Cert **outCerts = static_cast<nsIX509Cert **>(nsMemory::Alloc(mailbox_count * sizeof(nsIX509Cert *)));

    if (!outEA || !outCV || !outCII || !outCEI || !outCerts)
    {
      nsMemory::Free(outEA);
      nsMemory::Free(outCV);
      nsMemory::Free(outCII);
      nsMemory::Free(outCEI);
      nsMemory::Free(outCerts);
      rv = NS_ERROR_OUT_OF_MEMORY;
    }
    else
    {
      PRUnichar **iEA = outEA;
      PRInt32 *iCV = outCV;
      PRUnichar **iCII = outCII;
      PRUnichar **iCEI = outCEI;
      nsIX509Cert **iCert = outCerts;

      PRBool found_blocker = PR_FALSE;
      PRBool memory_failure = PR_FALSE;

      const char *walk = mailbox_list;

      // To understand this loop, especially the "+= strlen +1", look at the documentation
      // of ParseHeaderAddresses. Basically, it returns a list of zero terminated strings.
      for (PRUint32 i = 0;
          i < mailbox_count;
          ++i, ++iEA, ++iCV, ++iCII, ++iCEI, ++iCert, walk += strlen(walk) + 1)
      {
        *iCert = nsnull;
        *iCV = 0;
        *iCII = nsnull;
        *iCEI = nsnull;

        if (memory_failure) {
          *iEA = nsnull;
          continue;
        }

        nsDependentCString email(walk);
        *iEA = ToNewUnicode(email);
        if (!*iEA) {
          memory_failure = PR_TRUE;
          continue;
        }

        nsCString email_lowercase;
        ToLowerCase(email, email_lowercase);

        nsCOMPtr<nsIX509Cert> cert;
        if (NS_SUCCEEDED(certdb->FindCertByEmailAddress(nsnull, email_lowercase.get(), getter_AddRefs(cert)))
            && cert)
        {
          *iCert = cert;
          NS_ADDREF(*iCert);

          PRUint32 verification_result;

          if (NS_FAILED(
              cert->VerifyForUsage(nsIX509Cert::CERT_USAGE_EmailRecipient, &verification_result)))
          {
            *iCV = nsIX509Cert::NOT_VERIFIED_UNKNOWN;
            found_blocker = PR_TRUE;
          }
          else
          {
            *iCV = verification_result;

            if (verification_result != nsIX509Cert::VERIFIED_OK)
            {
              found_blocker = PR_TRUE;
            }
          }

          nsCOMPtr<nsIX509CertValidity> validity;
          rv = cert->GetValidity(getter_AddRefs(validity));

          if (NS_SUCCEEDED(rv)) {
            nsString id, ed;

            if (NS_SUCCEEDED(validity->GetNotBeforeLocalDay(id)))
            {
              *iCII = ToNewUnicode(id);
              if (!*iCII) {
                memory_failure = PR_TRUE;
                continue;
              }
            }

            if (NS_SUCCEEDED(validity->GetNotAfterLocalDay(ed)))
            {
              *iCEI = ToNewUnicode(ed);
              if (!*iCEI) {
                memory_failure = PR_TRUE;
                continue;
              }
            }
          }
        }
        else
        {
          found_blocker = PR_TRUE;
        }
      }

      if (memory_failure) {
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(mailbox_count, outEA);
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(mailbox_count, outCII);
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(mailbox_count, outCEI);
        NS_FREE_XPCOM_ISUPPORTS_POINTER_ARRAY(mailbox_count, outCerts);
        nsMemory::Free(outCV);
        rv = NS_ERROR_OUT_OF_MEMORY;
      }
      else {
        if (mailbox_count > 0 && !found_blocker)
        {
          *canEncrypt = PR_TRUE;
        }

        *emailAddresses = outEA;
        *certVerification = outCV;
        *certIssuedInfos = outCII;
        *certExpiresInfos = outCEI;
        *certs = outCerts;
      }
    }
  }

  if (mailbox_list) {
    nsMemory::Free(mailbox_list);
  }
  return rv;
}
コード例 #29
0
void
nsXBLPrototypeHandler::ConstructPrototype(nsIContent* aKeyElement, 
                                          const PRUnichar* aEvent,
                                          const PRUnichar* aPhase,
                                          const PRUnichar* aAction,
                                          const PRUnichar* aCommand,
                                          const PRUnichar* aKeyCode,
                                          const PRUnichar* aCharCode,
                                          const PRUnichar* aModifiers,
                                          const PRUnichar* aButton,
                                          const PRUnichar* aClickCount,
                                          const PRUnichar* aGroup,
                                          const PRUnichar* aPreventDefault,
                                          const PRUnichar* aAllowUntrusted)
{
  mType = 0;

  if (aKeyElement) {
    mType |= NS_HANDLER_TYPE_XUL;
    nsCOMPtr<nsIWeakReference> weak = do_GetWeakReference(aKeyElement);
    if (!weak) {
      return;
    }
    weak.swap(mHandlerElement);
  }
  else {
    mType |= aCommand ? NS_HANDLER_TYPE_XBL_COMMAND : NS_HANDLER_TYPE_XBL_JS;
    mHandlerText = nsnull;
  }

  mDetail = -1;
  mMisc = 0;
  mKeyMask = 0;
  mPhase = NS_PHASE_BUBBLING;

  if (aAction)
    mHandlerText = ToNewUnicode(nsDependentString(aAction));
  else if (aCommand)
    mHandlerText = ToNewUnicode(nsDependentString(aCommand));

  nsAutoString event(aEvent);
  if (event.IsEmpty()) {
    if (mType & NS_HANDLER_TYPE_XUL)
      GetEventType(event);
    if (event.IsEmpty())
      return;
  }

  mEventName = do_GetAtom(event);

  if (aPhase) {
    const nsDependentString phase(aPhase);
    if (phase.EqualsLiteral("capturing"))
      mPhase = NS_PHASE_CAPTURING;
    else if (phase.EqualsLiteral("target"))
      mPhase = NS_PHASE_TARGET;
  }

  // Button and clickcount apply only to XBL handlers and don't apply to XUL key
  // handlers.  
  if (aButton && *aButton)
    mDetail = *aButton - '0';

  if (aClickCount && *aClickCount)
    mMisc = *aClickCount - '0';

  // Modifiers are supported by both types of handlers (XUL and XBL).  
  nsAutoString modifiers(aModifiers);
  if (mType & NS_HANDLER_TYPE_XUL)
    aKeyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::modifiers, modifiers);
  
  if (!modifiers.IsEmpty()) {
    mKeyMask = cAllModifiers;
    char* str = ToNewCString(modifiers);
    char* newStr;
    char* token = nsCRT::strtok( str, ", \t", &newStr );
    while( token != NULL ) {
      if (PL_strcmp(token, "shift") == 0)
        mKeyMask |= cShift | cShiftMask;
      else if (PL_strcmp(token, "alt") == 0)
        mKeyMask |= cAlt | cAltMask;
      else if (PL_strcmp(token, "meta") == 0)
        mKeyMask |= cMeta | cMetaMask;
      else if (PL_strcmp(token, "control") == 0)
        mKeyMask |= cControl | cControlMask;
      else if (PL_strcmp(token, "accel") == 0)
        mKeyMask |= KeyToMask(kAccelKey);
      else if (PL_strcmp(token, "access") == 0)
        mKeyMask |= KeyToMask(kMenuAccessKey);
      else if (PL_strcmp(token, "any") == 0)
        mKeyMask &= ~(mKeyMask << 4);
    
      token = nsCRT::strtok( newStr, ", \t", &newStr );
    }

    nsMemory::Free(str);
  }

  nsAutoString key(aCharCode);
  if (key.IsEmpty()) {
    if (mType & NS_HANDLER_TYPE_XUL) {
      aKeyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::key, key);
      if (key.IsEmpty()) 
        aKeyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::charcode, key);
    }
  }

  if (!key.IsEmpty()) {
    if (mKeyMask == 0)
      mKeyMask = cAllModifiers;
    ToLowerCase(key);

    // We have a charcode.
    mMisc = 1;
    mDetail = key[0];
    const PRUint8 GTK2Modifiers = cShift | cControl | cShiftMask | cControlMask;
    if ((mKeyMask & GTK2Modifiers) == GTK2Modifiers &&
        modifiers.First() != PRUnichar(',') &&
        (mDetail == 'u' || mDetail == 'U'))
      ReportKeyConflict(key.get(), modifiers.get(), aKeyElement, "GTK2Conflict");
    const PRUint8 WinModifiers = cControl | cAlt | cControlMask | cAltMask;
    if ((mKeyMask & WinModifiers) == WinModifiers &&
        modifiers.First() != PRUnichar(',') &&
        (('A' <= mDetail && mDetail <= 'Z') ||
         ('a' <= mDetail && mDetail <= 'z')))
      ReportKeyConflict(key.get(), modifiers.get(), aKeyElement, "WinConflict");
  }
  else {
    key.Assign(aKeyCode);
    if (mType & NS_HANDLER_TYPE_XUL)
      aKeyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::keycode, key);
    
    if (!key.IsEmpty()) {
      if (mKeyMask == 0)
        mKeyMask = cAllModifiers;
      mDetail = GetMatchingKeyCode(key);
    }
  }

  if (aGroup && nsDependentString(aGroup).EqualsLiteral("system"))
    mType |= NS_HANDLER_TYPE_SYSTEM;

  if (aPreventDefault &&
      nsDependentString(aPreventDefault).EqualsLiteral("true"))
    mType |= NS_HANDLER_TYPE_PREVENTDEFAULT;

  if (aAllowUntrusted) {
    mType |= NS_HANDLER_HAS_ALLOW_UNTRUSTED_ATTR;
    if (nsDependentString(aAllowUntrusted).EqualsLiteral("true")) {
      mType |= NS_HANDLER_ALLOW_UNTRUSTED;
    } else {
      mType &= ~NS_HANDLER_ALLOW_UNTRUSTED;
    }
  }
}
コード例 #30
0
NS_IMETHODIMP
nsComm4xProfile::GetMailDir(const PRUnichar *aProfile, PRUnichar **_retval)
{
    NS_ENSURE_ARG_POINTER(_retval);
    *_retval = nsnull;
#if defined(XP_WIN) || defined(XP_OS2) || defined(XP_MACOSX)
    nsresult rv;
    nsCOMPtr <nsILocalFile> resolvedLocation = do_CreateInstance("@mozilla.org/file/local;1");
    // on macos, registry entries are UTF8 encoded
    NS_ConvertUTF16toUTF8 profileName(aProfile);

    nsCOMPtr<nsIFile> regFile;
    rv = NS_GetSpecialDirectory(OLDREG_DIR, getter_AddRefs(regFile));
    if (NS_FAILED(rv)) return rv;

    regFile->AppendNative(NS_LITERAL_CSTRING(OLDREG_NAME));

    nsCAutoString path;
    rv = regFile->GetNativePath(path);
    if (NS_FAILED(rv)) return rv;

    if (NR_StartupRegistry())
        return NS_ERROR_FAILURE;

    HREG reg = nsnull;
    RKEY profile = nsnull;

    if (NR_RegOpen(path.get(), &reg))
      goto cleanup;

    if (NR_RegGetKey(reg, ROOTKEY_USERS, profileName.get(), &profile))
        goto cleanup;

    char profilePath[MAXPATHLEN];
    if (NR_RegGetEntryString(reg, profile, "ProfileLocation", profilePath, MAXPATHLEN))
        goto cleanup;

    resolvedLocation->InitWithPath(NS_ConvertUTF8toUTF16(profilePath));
    if (resolvedLocation) {
        nsCOMPtr <nsIFile> file;
        rv = resolvedLocation->Clone(getter_AddRefs(file));
        if (NS_FAILED(rv)) return rv;
        nsCOMPtr <nsILocalFile> profileLocation;
        profileLocation = do_QueryInterface(file);
        rv = profileLocation->AppendNative(NS_LITERAL_CSTRING(PREF_FILE_NAME_IN_4x));
        if (NS_FAILED(rv)) return rv;
        bool exists = false;
        rv = profileLocation->Exists(&exists);
        if (NS_FAILED(rv)) return rv;
        if (exists) {
            nsString prefValue;
            rv = GetPrefValue(profileLocation, PREF_NAME, PREF_END, getter_Copies(prefValue));
            if (NS_FAILED(rv)) return rv;
            if (!prefValue.IsEmpty()) {
#ifdef XP_MACOSX
                rv = profileLocation->SetPersistentDescriptor(NS_ConvertUTF16toUTF8(prefValue));
                if (NS_FAILED(rv)) return rv;
                nsAutoString path;
                rv = profileLocation->GetPath(path);
                if (NS_FAILED(rv)) return rv;
                *_retval = ToNewUnicode(path);
#else
                *_retval = ToNewUnicode(prefValue);
#endif
            }
#if defined(XP_WIN) || defined(XP_OS2) || defined(XP_MACOSX)
            else {
                nsCOMPtr <nsIFile> mailLocation;
                rv =  resolvedLocation->Clone(getter_AddRefs(mailLocation));
                if (NS_FAILED(rv)) return rv;
                rv = mailLocation->AppendNative(NS_LITERAL_CSTRING("Mail"));
                if (NS_FAILED(rv)) return rv;
                nsAutoString path;
                rv = mailLocation->GetPath(path);
                if (NS_FAILED(rv)) return rv;
                *_retval = ToNewUnicode(path);
            }
#endif
        }
    }

cleanup:
    if (reg)
        NR_RegClose(reg);
    NR_ShutdownRegistry();
    return rv;
#else
    return NS_ERROR_FAILURE;
#endif
}