NS_METHOD
sbLocalDatabaseLibraryLoader::PromptInaccessibleLibraries() 
{
  nsresult rv;

  nsCOMPtr<nsIPromptService> promptService =
    do_GetService("@mozilla.org/embedcomp/prompt-service;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  PRUint32 buttons = nsIPromptService::BUTTON_POS_0 * nsIPromptService::BUTTON_TITLE_IS_STRING + 
                     nsIPromptService::BUTTON_POS_0_DEFAULT;

  PRInt32 promptResult;

  // get dialog strings
  sbStringBundle bundle;

  nsTArray<nsString> params;
  nsCOMPtr<nsIProperties> dirService =
    do_GetService("@mozilla.org/file/directory_service;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  
  nsCOMPtr<nsIFile> profileDir;
  rv = dirService->Get("ProfD",
                       NS_GET_IID(nsIFile),
                       getter_AddRefs(profileDir));
  NS_ENSURE_SUCCESS(rv, rv);
  
  nsString profilePath;
  rv = profileDir->GetPath(profilePath);
  NS_ENSURE_SUCCESS(rv, rv);

  params.AppendElement(profilePath);
  
  nsCOMPtr<nsIPrefBranch> prefBranch =
    do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  
  nsString url;
  char* urlBuffer = nsnull;
  rv = prefBranch->GetCharPref(PREF_SUPPORT_INACCESSIBLE_LIBRARY, &urlBuffer);
  if (NS_SUCCEEDED(rv)) {
    url.Assign(NS_ConvertUTF8toUTF16(nsCString(urlBuffer)));
    NS_Free(urlBuffer);
  } else {
    #if PR_LOGGING
      nsresult __rv = rv;
      NS_ENSURE_SUCCESS_BODY(rv, rv);
    #endif /* PR_LOGGING */
    url = bundle.Get("database.inaccessible.dialog.url", "<error>");
  }
  params.AppendElement(url);

  nsAutoString dialogTitle = bundle.Get("database.inaccessible.dialog.title");
  nsAutoString dialogText = bundle.Format("database.inaccessible.dialog.text",
                                          params);
  nsAutoString buttonText = bundle.Get("database.inaccessible.dialog.buttons.quit");

  // prompt.
  rv = promptService->ConfirmEx(nsnull,
                                dialogTitle.BeginReading(),
                                dialogText.BeginReading(),
                                buttons,            
                                buttonText.BeginReading(),   // button 0
                                nsnull,                      // button 1
                                nsnull,                      // button 2
                                nsnull,                      // no checkbox
                                nsnull,                      // no check value
                                &promptResult);     
  NS_ENSURE_SUCCESS(rv, rv);

  // now attempt to quit/restart.
  nsCOMPtr<nsIAppStartup> appStartup = 
    (do_GetService(NS_APPSTARTUP_CONTRACTID, &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  appStartup->Quit(nsIAppStartup::eForceQuit); 

  return NS_OK;
}
Beispiel #2
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 (PR_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;
}
nsresult nsPluginFile::FreePluginInfo(nsPluginInfo& info)
{
  NS_Free(info.fName);
  NS_Free(info.fDescription);
  int variantCount = info.fVariantCount;
  for (int i = 0; i < variantCount; i++) {
    NS_Free(info.fMimeTypeArray[i]);
    NS_Free(info.fExtensionArray[i]);
    NS_Free(info.fMimeDescriptionArray[i]);
  }
  NS_Free(info.fMimeTypeArray);
  NS_Free(info.fMimeDescriptionArray);
  NS_Free(info.fExtensionArray);
  NS_Free(info.fFileName);
  NS_Free(info.fFullPath);
  NS_Free(info.fVersion);

  return NS_OK;
}
Beispiel #4
0
void Area::ParseCoords(const nsAString& aSpec)
{
  char* cp = ToNewCString(aSpec);
  if (cp) {
    char *tptr;
    char *n_str;
    PRInt32 i, cnt;
    PRInt32 *value_list;

    /*
     * Nothing in an empty list
     */
    mNumCoords = 0;
    mCoords = nsnull;
    if (*cp == '\0')
    {
      return;
    }

    /*
     * Skip beginning whitespace, all whitespace is empty list.
     */
    n_str = cp;
    while (is_space(*n_str))
    {
      n_str++;
    }
    if (*n_str == '\0')
    {
      return;
    }

    /*
     * Make a pass where any two numbers separated by just whitespace
     * are given a comma separator.  Count entries while passing.
     */
    cnt = 0;
    while (*n_str != '\0')
    {
      PRBool has_comma;

      /*
       * Skip to a separator
       */
      tptr = n_str;
      while (!is_space(*tptr) && *tptr != ',' && *tptr != '\0')
      {
        tptr++;
      }
      n_str = tptr;

      /*
       * If no more entries, break out here
       */
      if (*n_str == '\0')
      {
        break;
      }

      /*
       * Skip to the end of the separator, noting if we have a
       * comma.
       */
      has_comma = PR_FALSE;
      while (is_space(*tptr) || *tptr == ',')
      {
        if (*tptr == ',')
        {
          if (!has_comma)
          {
            has_comma = PR_TRUE;
          }
          else
          {
            break;
          }
        }
        tptr++;
      }
      /*
       * If this was trailing whitespace we skipped, we are done.
       */
      if ((*tptr == '\0') && !has_comma)
      {
        break;
      }
      /*
       * Else if the separator is all whitespace, and this is not the
       * end of the string, add a comma to the separator.
       */
      else if (!has_comma)
      {
        *n_str = ',';
      }

      /*
       * count the entry skipped.
       */
      cnt++;

      n_str = tptr;
    }
    /*
     * count the last entry in the list.
     */
    cnt++;

    /*
     * Allocate space for the coordinate array.
     */
    value_list = new nscoord[cnt];
    if (!value_list)
    {
      return;
    }

    /*
     * Second pass to copy integer values into list.
     */
    tptr = cp;
    for (i=0; i<cnt; i++)
    {
      char *ptr;

      ptr = strchr(tptr, ',');
      if (ptr)
      {
        *ptr = '\0';
      }
      /*
       * Strip whitespace in front of number because I don't
       * trust atoi to do it on all platforms.
       */
      while (is_space(*tptr))
      {
        tptr++;
      }
      if (*tptr == '\0')
      {
        value_list[i] = 0;
      }
      else
      {
        value_list[i] = (nscoord) ::atoi(tptr);
      }
      if (ptr)
      {
        *ptr = ',';
        tptr = ptr + 1;
      }
    }

    mNumCoords = cnt;
    mCoords = value_list;

    NS_Free(cp);
  }
}
// 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;
}
static void ImportAddressThread(void *stuff)
{
  IMPORT_LOG0("In Begin ImportAddressThread\n");

  AddressThreadData *pData = (AddressThreadData *)stuff;
  uint32_t          count = 0;
  uint32_t          i;
  bool              import;
  uint32_t          size;

  nsString          success;
  nsString          error;

  (void) pData->books->GetLength(&count);

  for (i = 0; (i < count) && !(pData->abort); i++) {
    nsCOMPtr<nsIImportABDescriptor> book =
      do_QueryElementAt(pData->books, i);

    if (book) {
      import = false;
      size = 0;
      nsresult rv = book->GetImport(&import);
      if (NS_SUCCEEDED(rv) && import)
        rv = book->GetSize(&size);

      if (NS_SUCCEEDED(rv) && size && import) {
        nsString name;
        book->GetPreferredName(name);

        nsCOMPtr<nsIAddrDatabase> db = pData->dBs->ObjectAt(i);

        bool fatalError = false;
        pData->currentSize = size;
        if (db) {
          char16_t *pSuccess = nullptr;
          char16_t *pError = nullptr;

          /*
          if (pData->fieldMap) {
            int32_t    sz = 0;
            int32_t    mapIndex;
            bool      active;
            pData->fieldMap->GetMapSize(&sz);
            IMPORT_LOG1("**** Field Map Size: %d\n", (int) sz);
            for (int32_t i = 0; i < sz; i++) {
              pData->fieldMap->GetFieldMap(i, &mapIndex);
              pData->fieldMap->GetFieldActive(i, &active);
              IMPORT_LOG3("Field map #%d: index=%d, active=%d\n", (int) i, (int) mapIndex, (int) active);
            }
          }
          */

          rv = pData->addressImport->ImportAddressBook(book,
                                                       db,
                                                       pData->fieldMap,
                                                       pData->ldifService,
                                                       &pError,
                                                       &pSuccess,
                                                       &fatalError);
          if (NS_SUCCEEDED(rv) && pSuccess) {
            success.Append(pSuccess);
            NS_Free(pSuccess);
          }
          if (pError) {
            error.Append(pError);
            NS_Free(pError);
          }
        }
        else {
          nsImportGenericAddressBooks::ReportError(name.get(), &error, pData->stringBundle);
        }

        pData->currentSize = 0;
        pData->currentTotal += size;

        if (db)
          db->Close(true);

        if (fatalError) {
          pData->fatalError = true;
          break;
        }
      }
    }
  }


  nsImportGenericAddressBooks::SetLogs(success, error, pData->successLog, pData->errorLog);

  if (pData->abort || pData->fatalError) {
    // FIXME: do what is necessary to get rid of what has been imported so far.
    // Nothing if we went into an existing address book!  Otherwise, delete
    // the ones we created?
  }

}
int
main(void)
{
    nsresult rv;

    XPCOMGlueStartup(nullptr);

    // Initialize XPCOM
    nsCOMPtr<nsIServiceManager> servMan;
    rv = NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr);
    if (NS_FAILED(rv))
    {
        printf("ERROR: XPCOM intialization error [%x].\n", rv);
        return -1;
    }

    nsCOMPtr<nsIComponentManager> manager = do_QueryInterface(servMan);
    
    // Create an instance of our component
    nsCOMPtr<nsISample> mysample;
    rv = manager->CreateInstanceByContractID(NS_SAMPLE_CONTRACTID,
                                             nullptr,
                                             NS_GET_IID(nsISample),
                                             getter_AddRefs(mysample));
    if (NS_FAILED(rv))
    {
        printf("ERROR: Cannot create instance of component " NS_SAMPLE_CONTRACTID " [%x].\n"
               "Debugging hint:\n"
               "\tsetenv NSPR_LOG_MODULES nsComponentManager:5\n"
               "\tsetenv NSPR_LOG_FILE xpcom.log\n"
               "\t./nsTestSample\n"
               "\t<check the contents for xpcom.log for possible cause of error>.\n",
               rv);
        return -2;
    }

    // Call methods on our sample to test it out.
    rv = mysample->WriteValue("Inital print:");
    if (NS_FAILED(rv))
    {
        printf("ERROR: Calling nsISample::WriteValue() [%x]\n", rv);
        return -3;
    }

    const char *testValue = "XPCOM defies gravity";
    rv = mysample->SetValue(testValue);
    if (NS_FAILED(rv))
    {
        printf("ERROR: Calling nsISample::SetValue() [%x]\n", rv);
        return -3;
    }
    printf("Set value to: %s\n", testValue);
    char *str;
    rv = mysample->GetValue(&str);

    if (NS_FAILED(rv))
    {
        printf("ERROR: Calling nsISample::GetValue() [%x]\n", rv);
        return -3;
    }
    if (strcmp(str, testValue))
    {
        printf("Test FAILED.\n");
        return -4;
    }

    NS_Free(str);

    rv = mysample->WriteValue("Final print :");
    printf("Test passed.\n");
    
    // All nsCOMPtr's must be deleted prior to calling shutdown XPCOM
    // as we should not hold references passed XPCOM Shutdown.
    servMan = 0;
    manager = 0;
    mysample = 0;
    
    // Shutdown XPCOM
    NS_ShutdownXPCOM(nullptr);

    XPCOMGlueShutdown();
    return 0;
}
nsMsgSearchValueImpl::~nsMsgSearchValueImpl()
{
  if (IS_STRING_ATTRIBUTE(mValue.attribute))
    NS_Free(mValue.string);
}
// Test a message send????
nsresult nsEudoraCompose::SendTheMessage(nsIFile *pMailImportLocation, nsIFile **pMsg)
{
  nsresult rv = CreateComponents();
  if (NS_SUCCEEDED( rv))
    rv = CreateIdentity();
  if (NS_FAILED( rv))
    return( rv);

  // IMPORT_LOG0( "Outlook Compose created necessary components\n");

  nsString bodyType;
  nsString charSet;
  nsString headerVal;
  GetHeaderValue( m_pHeaders, m_headerLen, "From:", headerVal);
  if (!headerVal.IsEmpty())
    m_pMsgFields->SetFrom( headerVal);
  GetHeaderValue( m_pHeaders, m_headerLen, "To:", headerVal);
  if (!headerVal.IsEmpty())
    m_pMsgFields->SetTo( headerVal);
  GetHeaderValue( m_pHeaders, m_headerLen, "Subject:", headerVal);
  if (!headerVal.IsEmpty())
    m_pMsgFields->SetSubject( headerVal);
  GetHeaderValue( m_pHeaders, m_headerLen, "Content-type:", headerVal);
  bodyType = headerVal;
  ExtractType( bodyType);
  ExtractCharset( headerVal);
  // Use platform charset as default if the msg doesn't specify one
  // (ie, no 'charset' param in the Content-Type: header). As the last
  // resort we'll use the mail default charset.
  // (ie, no 'charset' param in the Content-Type: header) or if the
  // charset parameter fails a length sanity check.
  // As the last resort we'll use the mail default charset.
  if ( headerVal.IsEmpty() || (headerVal.Length() > kContentTypeLengthSanityCheck) )
  {
    CopyASCIItoUTF16(nsMsgI18NFileSystemCharset(), headerVal);
    if (headerVal.IsEmpty())
    { // last resort
      if (m_defCharset.IsEmpty())
      {
        nsString defaultCharset;
        NS_GetLocalizedUnicharPreferenceWithDefault(nsnull, "mailnews.view_default_charset",
                                                    NS_LITERAL_STRING("ISO-8859-1"), defaultCharset);
        m_defCharset = defaultCharset;
      }
      headerVal = m_defCharset;
    }
  }
  m_pMsgFields->SetCharacterSet( NS_LossyConvertUTF16toASCII(headerVal).get() );
  charSet = headerVal;
  GetHeaderValue( m_pHeaders, m_headerLen, "CC:", headerVal);
  if (!headerVal.IsEmpty())
    m_pMsgFields->SetCc( headerVal);
  GetHeaderValue( m_pHeaders, m_headerLen, "Message-ID:", headerVal);
  if (!headerVal.IsEmpty())
    m_pMsgFields->SetMessageId( NS_LossyConvertUTF16toASCII(headerVal).get() );
  GetHeaderValue( m_pHeaders, m_headerLen, "Reply-To:", headerVal);
  if (!headerVal.IsEmpty())
    m_pMsgFields->SetReplyTo( headerVal);

  // what about all of the other headers?!?!?!?!?!?!
  char *pMimeType;
  if (!bodyType.IsEmpty())
    pMimeType = ToNewCString(bodyType);
  else
    pMimeType = ToNewCString(m_bodyType);

  // IMPORT_LOG0( "Outlook compose calling CreateAndSendMessage\n");
  nsMsgAttachedFile *pAttach = GetLocalAttachments();


  /*
    l10n - I have the body of the message in the system charset,
    I need to "encode" it to be the charset for the message
    *UNLESS* of course, I don't know what the charset of the message
    should be?  How do I determine what the charset should
    be if it doesn't exist?

  */

  nsString uniBody;
  NS_CopyNativeToUnicode( nsDependentCString(m_pBody), uniBody);

  nsCString body;

  rv = nsMsgI18NConvertFromUnicode( NS_LossyConvertUTF16toASCII(charSet).get(),
                                    uniBody, body);
  if (NS_FAILED( rv)) {
    // in this case, if we did not use the default compose
    // charset, then try that.
    if (!charSet.Equals( m_defCharset)) {
      body.Truncate();
      rv = nsMsgI18NConvertFromUnicode( NS_LossyConvertUTF16toASCII(charSet).get(),
                                        uniBody, body);
    }
  }
  uniBody.Truncate();


  // See if it's a draft msg (ie, no From: or no To: AND no Cc: AND no Bcc:).
  // Eudora saves sent and draft msgs in Out folder (ie, mixed) and it does
  // store Bcc: header in the msg itself.
  nsMsgDeliverMode mode = nsIMsgSend::nsMsgDeliverNow;
  nsAutoString from, to, cc, bcc;
  rv = m_pMsgFields->GetFrom(from);
  rv = m_pMsgFields->GetTo(to);
  rv = m_pMsgFields->GetCc(cc);
  rv = m_pMsgFields->GetBcc(bcc);
  if ( from.IsEmpty() || to.IsEmpty() && cc.IsEmpty() && bcc.IsEmpty() )
    mode = nsIMsgSend::nsMsgSaveAsDraft;

  // We only get the editor interface when there's embedded content.
  // Otherwise pEditor remains NULL. That way we only import with the pseudo
  // editor when it helps.
  nsRefPtr<nsEudoraEditor>  pEudoraEditor = new nsEudoraEditor(m_pBody, pMailImportLocation);
  nsCOMPtr<nsIEditor>       pEditor;

  if (pEudoraEditor->HasEmbeddedContent())
    // There's embedded content that we need to import, so query for the editor interface
    pEudoraEditor->QueryInterface( NS_GET_IID(nsIEditor), getter_AddRefs(pEditor) );

  if (NS_FAILED( rv)) {

    rv = m_pSendProxy->CreateAndSendMessage(
                          pEditor.get(),                // pseudo editor shell when there's embedded content
                          s_pIdentity,                  // dummy identity
                          nsnull,                       // account key
                          m_pMsgFields,                 // message fields
                          PR_FALSE,                     // digest = NO
                          PR_TRUE,                      // dont_deliver = YES, make a file
                          mode,                         // mode
                          nsnull,                       // no message to replace
                          pMimeType,                    // body type
                          m_pBody,                      // body pointer
                          m_bodyLen,                    // body length
                          nsnull,                       // remote attachment data
                          pAttach,                      // local attachments
                          nsnull,                       // related part
                          nsnull,                       // parent window
                          nsnull,                       // progress listener
                          m_pListener,                  // listener
                          nsnull,                       // password
                          EmptyCString(),               // originalMsgURI
                          nsnull);                      // message compose type

  }
  else {
    rv = m_pSendProxy->CreateAndSendMessage(
                          pEditor.get(),                // pseudo editor shell when there's embedded content
                          s_pIdentity,                  // dummy identity
                          nsnull,                       // account key
                          m_pMsgFields,                 // message fields
                          PR_FALSE,                     // digest = NO
                          PR_TRUE,                      // dont_deliver = YES, make a file
                          mode,                         // mode
                          nsnull,                       // no message to replace
                          pMimeType,                    // body type
                          body.get(),                   // body pointer
                          body.Length(),                // body length
                          nsnull,                       // remote attachment data
                          pAttach,                      // local attachments
                          nsnull,                       // related part
                          nsnull,                       // parent window
                          nsnull,                       // progress listener
                          m_pListener,                  // listener
                          nsnull,                       // password
                          EmptyCString(),               // originalMsgURI
                          nsnull);                      // message compose type

  }

  // IMPORT_LOG0( "Returned from CreateAndSendMessage\n");

  if (pAttach)
    delete [] pAttach;

  EudoraSendListener *pListen = (EudoraSendListener *)m_pListener;
  if (NS_FAILED( rv)) {
    IMPORT_LOG1( "*** Error, CreateAndSendMessage FAILED: 0x%lx\n", rv);
    // IMPORT_LOG1( "Headers: %80s\n", m_pHeaders);
  }
  else {
    // wait for the listener to get done!
    PRInt32 abortCnt = 0;
    PRInt32 cnt = 0;
    PRInt32 sleepCnt = 1;
    while (!pListen->m_done && (abortCnt < kHungAbortCount)) {
      PR_Sleep( sleepCnt);
      cnt++;
      if (cnt > kHungCount) {
        abortCnt++;
        sleepCnt *= 2;
        cnt = 0;
      }
    }

    if (abortCnt >= kHungAbortCount) {
      IMPORT_LOG0( "**** Create and send message hung\n");
      IMPORT_LOG1( "Headers: %s\n", m_pHeaders);
      IMPORT_LOG1( "Body: %s\n", m_pBody);
      rv = NS_ERROR_FAILURE;
    }

  }

  if (pMimeType)
    NS_Free( pMimeType);

  if (pListen->m_location) {
    pListen->m_location->Clone(pMsg);
    rv = NS_OK;
  }
  else {
    rv = NS_ERROR_FAILURE;
    IMPORT_LOG0( "*** Error, Outlook compose unsuccessful\n");
  }

  pListen->Reset();

  return( rv);
}
Beispiel #10
0
nsTArray_base::~nsTArray_base() {
  if (mHdr != &sEmptyHdr && !UsesAutoArrayBuffer()) {
    NS_Free(mHdr);
  }
  MOZ_COUNT_DTOR(nsTArray_base);
}
Beispiel #11
0
static int
MimeExternalBody_parse_eof (MimeObject *obj, bool abort_p)
{
  int status = 0;
  MimeExternalBody *bod = (MimeExternalBody *) obj;

  if (obj->closed_p) return 0;

  /* Run parent method first, to flush out any buffered data. */
  status = ((MimeObjectClass*)&MIME_SUPERCLASS)->parse_eof(obj, abort_p);
  if (status < 0) return status;

#ifdef XP_MACOSX
  if (obj->parent && mime_typep(obj->parent,
                                (MimeObjectClass*) &mimeMultipartAppleDoubleClass))
    goto done;
#endif /* XP_MACOSX */

  if (!abort_p &&
      obj->output_p &&
      obj->options &&
      obj->options->write_html_p)
  {
    bool all_headers_p = obj->options->headers == MimeHeadersAll;
    MimeDisplayOptions *newopt = obj->options;  /* copy it */

    char *ct = MimeHeaders_get(obj->headers, HEADER_CONTENT_TYPE,
                               PR_FALSE, PR_FALSE);
    char *at, *lexp, *size, *perm;
    char *url, *dir, *mode, *name, *site, *svr, *subj;
    char *h = 0, *lname = 0, *lurl = 0, *body = 0;
    MimeHeaders *hdrs = 0;

    if (!ct) return MIME_OUT_OF_MEMORY;

    at   = MimeHeaders_get_parameter(ct, "access-type", NULL, NULL);
    lexp  = MimeHeaders_get_parameter(ct, "expiration", NULL, NULL);
    size = MimeHeaders_get_parameter(ct, "size", NULL, NULL);
    perm = MimeHeaders_get_parameter(ct, "permission", NULL, NULL);
    dir  = MimeHeaders_get_parameter(ct, "directory", NULL, NULL);
    mode = MimeHeaders_get_parameter(ct, "mode", NULL, NULL);
    name = MimeHeaders_get_parameter(ct, "name", NULL, NULL);
    site = MimeHeaders_get_parameter(ct, "site", NULL, NULL);
    svr  = MimeHeaders_get_parameter(ct, "server", NULL, NULL);
    subj = MimeHeaders_get_parameter(ct, "subject", NULL, NULL);
    url  = MimeHeaders_get_parameter(ct, "url", NULL, NULL);
    PR_FREEIF(ct);

    /* the *internal* content-type */
    ct = MimeHeaders_get(bod->hdrs, HEADER_CONTENT_TYPE,
                         PR_TRUE, PR_FALSE);
						 
    PRUint32 hlen = ((at ? strlen(at) : 0) +
                    (lexp ? strlen(lexp) : 0) +
                    (size ? strlen(size) : 0) +
                    (perm ? strlen(perm) : 0) +
                    (dir ? strlen(dir) : 0) +
                    (mode ? strlen(mode) : 0) +
                    (name ? strlen(name) : 0) +
                    (site ? strlen(site) : 0) +
                    (svr ? strlen(svr) : 0) +
                    (subj ? strlen(subj) : 0) +
                    (ct ? strlen(ct) : 0) +
                    (url ? strlen(url) : 0) + 100);
					
	h = (char *) PR_MALLOC(hlen);
    if (!h)
    {
      status = MIME_OUT_OF_MEMORY;
      goto FAIL;
    }

    /* If there's a URL parameter, remove all whitespace from it.
      (The URL parameter to one of these headers is stored with
       lines broken every 40 characters or less; it's assumed that
       all significant whitespace was URL-hex-encoded, and all the
       rest of it was inserted just to keep the lines short.)
      */
    if (url)
    {
      char *in, *out;
      for (in = url, out = url; *in; in++)
        if (!IS_SPACE(*in))
          *out++ = *in;
      *out = 0;
    }

    hdrs = MimeHeaders_new();
    if (!hdrs)
    {
      status = MIME_OUT_OF_MEMORY;
      goto FAIL;
    }

# define FROB(STR,VAR) \
    if (VAR) \
    { \
      PL_strncpyz(h, STR ": ", hlen); \
        PL_strcatn(h, hlen, VAR); \
          PL_strcatn(h, hlen, MSG_LINEBREAK); \
            status = MimeHeaders_parse_line(h, strlen(h), hdrs); \
              if (status < 0) goto FAIL; \
    }
    FROB("Access-Type",  at);
    FROB("URL",      url);
    FROB("Site",      site);
    FROB("Server",    svr);
    FROB("Directory",    dir);
    FROB("Name",      name);
    FROB("Type",      ct);
    FROB("Size",      size);
    FROB("Mode",      mode);
    FROB("Permission",  perm);
    FROB("Expiration",  lexp);
    FROB("Subject",    subj);
# undef FROB
    PL_strncpyz(h, MSG_LINEBREAK, hlen);
    status = MimeHeaders_parse_line(h, strlen(h), hdrs);
    if (status < 0) goto FAIL;

    lurl = MimeExternalBody_make_url(ct, at, lexp, size, perm, dir, mode,
                                     name, url, site, svr, subj, bod->body);
    if (lurl)
    {
      lname = MimeGetStringByID(MIME_MSG_LINK_TO_DOCUMENT);
    }
    else
    {
      lname = MimeGetStringByID(MIME_MSG_DOCUMENT_INFO);
      all_headers_p = PR_TRUE;
    }

    all_headers_p = PR_TRUE;  /* #### just do this all the time? */

    if (bod->body && all_headers_p)
    {
      char *s = bod->body;
      while (IS_SPACE(*s)) s++;
      if (*s)
      {
        char *s2;
        const char *pre = "<P><PRE>";
        const char *suf = "</PRE>";
        PRInt32 i;
        for(i = strlen(s)-1; i >= 0 && IS_SPACE(s[i]); i--)
          s[i] = 0;
        s2 = MsgEscapeHTML(s);
        if (!s2) goto FAIL;
        body = (char *) PR_MALLOC(strlen(pre) + strlen(s2) +
                                  strlen(suf) + 1);
        if (!body)
        {
          NS_Free(s2);
          goto FAIL;
        }
        PL_strcpy(body, pre);
        PL_strcat(body, s2);
        PL_strcat(body, suf);
      }
    }

    newopt->fancy_headers_p = PR_TRUE;
    newopt->headers = (all_headers_p ? MimeHeadersAll : MimeHeadersSome);

FAIL:
      if (hdrs)
        MimeHeaders_free(hdrs);
    PR_FREEIF(h);
    PR_FREEIF(lname);
    PR_FREEIF(lurl);
    PR_FREEIF(body);
    PR_FREEIF(ct);
    PR_FREEIF(at);
    PR_FREEIF(lexp);
    PR_FREEIF(size);
    PR_FREEIF(perm);
    PR_FREEIF(dir);
    PR_FREEIF(mode);
    PR_FREEIF(name);
    PR_FREEIF(url);
    PR_FREEIF(site);
    PR_FREEIF(svr);
    PR_FREEIF(subj);
  }

#ifdef XP_MACOSX
done:
#endif

    return status;
}
Beispiel #12
0
static nsresult
moz_gdk_pixbuf_to_channel(GdkPixbuf* aPixbuf, nsIURI* aURI,
                          nsIChannel** aChannel)
{
  int width = gdk_pixbuf_get_width(aPixbuf);
  int height = gdk_pixbuf_get_height(aPixbuf);
  NS_ENSURE_TRUE(height < 256 && width < 256 && height > 0 && width > 0 &&
                 gdk_pixbuf_get_colorspace(aPixbuf) == GDK_COLORSPACE_RGB &&
                 gdk_pixbuf_get_bits_per_sample(aPixbuf) == 8 &&
                 gdk_pixbuf_get_has_alpha(aPixbuf) &&
                 gdk_pixbuf_get_n_channels(aPixbuf) == 4,
                 NS_ERROR_UNEXPECTED);

  const int n_channels = 4;
  gsize buf_size = 2 + n_channels * height * width;
  uint8_t* const buf = (uint8_t*)NS_Alloc(buf_size);
  NS_ENSURE_TRUE(buf, NS_ERROR_OUT_OF_MEMORY);
  uint8_t* out = buf;

  *(out++) = width;
  *(out++) = height;

  const guchar* const pixels = gdk_pixbuf_get_pixels(aPixbuf);
  int rowextra = gdk_pixbuf_get_rowstride(aPixbuf) - width * n_channels;

  // encode the RGB data and the A data
  const guchar* in = pixels;
  for (int y = 0; y < height; ++y, in += rowextra) {
    for (int x = 0; x < width; ++x) {
      uint8_t r = *(in++);
      uint8_t g = *(in++);
      uint8_t b = *(in++);
      uint8_t a = *(in++);
#define DO_PREMULTIPLY(c_) uint8_t(uint16_t(c_) * uint16_t(a) / uint16_t(255))
#if MOZ_LITTLE_ENDIAN
      *(out++) = DO_PREMULTIPLY(b);
      *(out++) = DO_PREMULTIPLY(g);
      *(out++) = DO_PREMULTIPLY(r);
      *(out++) = a;
#else
      *(out++) = a;
      *(out++) = DO_PREMULTIPLY(r);
      *(out++) = DO_PREMULTIPLY(g);
      *(out++) = DO_PREMULTIPLY(b);
#endif
#undef DO_PREMULTIPLY
    }
  }

  NS_ASSERTION(out == buf + buf_size, "size miscalculation");

  nsresult rv;
  nsCOMPtr<nsIStringInputStream> stream =
    do_CreateInstance("@mozilla.org/io/string-input-stream;1", &rv);

  // Prevent the leaking of buf
  if (NS_WARN_IF(NS_FAILED(rv))) {
    NS_Free(buf);
    return rv;
  }

  // stream takes ownership of buf and will free it on destruction.
  // This function cannot fail.
  rv = stream->AdoptData((char*)buf, buf_size);

  // If this no longer holds then re-examine buf's lifetime.
  MOZ_ASSERT(NS_SUCCEEDED(rv));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIPrincipal> nullPrincipal = nsNullPrincipal::Create();
  NS_ENSURE_TRUE(nullPrincipal, NS_ERROR_FAILURE);

  return NS_NewInputStreamChannel(aChannel,
                                  aURI,
                                  stream,
                                  nullPrincipal,
                                  nsILoadInfo::SEC_NORMAL,
                                  nsIContentPolicy::TYPE_OTHER,
                                  NS_LITERAL_CSTRING(IMAGE_ICON_MS));
}
Beispiel #13
0
void
WriteConsoleLog()
{
  nsresult rv;

  nsCOMPtr<nsILocalFile> lfile;

  char* logFileEnv = PR_GetEnv("XRE_CONSOLE_LOG");
  if (logFileEnv && *logFileEnv) {
    rv = XRE_GetFileFromPath(logFileEnv, getter_AddRefs(lfile));
    if (NS_FAILED(rv))
      return;
  }
  else {
    if (!gLogConsoleErrors)
      return;

    rv = gDirServiceProvider->GetUserAppDataDirectory(getter_AddRefs(lfile));
    if (NS_FAILED(rv))
      return;

    lfile->AppendNative(NS_LITERAL_CSTRING("console.log"));
  }

  PRFileDesc *file;
  rv = lfile->OpenNSPRFileDesc(PR_WRONLY | PR_APPEND | PR_CREATE_FILE,
                               0660, &file);
  if (NS_FAILED(rv))
    return;

  nsCOMPtr<nsIConsoleService> csrv
    (do_GetService(NS_CONSOLESERVICE_CONTRACTID));
  if (!csrv) {
    PR_Close(file);
    return;
  }

  nsIConsoleMessage** messages;
  PRUint32 mcount;

  rv = csrv->GetMessageArray(&messages, &mcount);
  if (NS_FAILED(rv)) {
    PR_Close(file);
    return;
  }

  if (mcount) {
    PRExplodedTime etime;
    PR_ExplodeTime(PR_Now(), PR_LocalTimeParameters, &etime);
    char datetime[512];
    PR_FormatTimeUSEnglish(datetime, sizeof(datetime),
                           "%Y-%m-%d %H:%M:%S", &etime);

    PR_fprintf(file, NS_LINEBREAK
                     "*** Console log: %s ***" NS_LINEBREAK,
               datetime);
  }

  // From this point on, we have to release all the messages, and free
  // the memory allocated for the messages array. XPCOM arrays suck.

  nsXPIDLString msg;
  nsCAutoString nativemsg;

  for (PRUint32 i = 0; i < mcount; ++i) {
    rv = messages[i]->GetMessage(getter_Copies(msg));
    if (NS_SUCCEEDED(rv)) {
      NS_CopyUnicodeToNative(msg, nativemsg);
      PR_fprintf(file, "%s" NS_LINEBREAK, nativemsg.get());
    }
    NS_IF_RELEASE(messages[i]);
  }

  PR_Close(file);
  NS_Free(messages);
}
Beispiel #14
0
NS_IMETHODIMP
nsParserUtils::ParseFragment(const nsAString& aFragment,
                             PRUint32 aFlags,
                             bool 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
  nsRefPtr<nsScriptLoader> loader;
  bool scripts_enabled = false;
  if (document) {
    loader = document->ScriptLoader();
    scripts_enabled = loader->GetEnabled();
  }
  if (scripts_enabled) {
    loader->SetEnabled(false);
  }

  // Wrap things in a div or body for parsing, but it won't show up in
  // the fragment.
  nsAutoTArray<nsString, 2> 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(NS_ConvertUTF8toUTF16(base));
    }  else {
      tagStack.AppendElement(NS_LITERAL_STRING(XHTML_DIV_TAG));
    }
  }

  if (NS_SUCCEEDED(rv)) {
    nsCOMPtr<nsIContent> fragment;
    if (aIsXML) {
      rv = nsContentUtils::ParseFragmentXML(aFragment,
                                            document,
                                            tagStack,
                                            true,
                                            aReturn);
      fragment = do_QueryInterface(*aReturn);
    } else {
      NS_NewDocumentFragment(aReturn,
                             document->NodeInfoManager());
      fragment = do_QueryInterface(*aReturn);
      rv = nsContentUtils::ParseFragmentHTML(aFragment,
                                             fragment,
                                             nsGkAtoms::body,
                                             kNameSpaceID_XHTML,
                                             false,
                                             true);
      // Now, set the base URI on all subtree roots.
      if (aBaseURI) {
        aBaseURI->GetSpec(spec);
        nsAutoString spec16;
        CopyUTF8toUTF16(spec, spec16);
        nsIContent* node = fragment->GetFirstChild();
        while (node) {
          if (node->IsElement()) {
            node->SetAttr(kNameSpaceID_XML,
                          nsGkAtoms::base,
                          nsGkAtoms::xml,
                          spec16,
                          false);
          }
          node = node->GetNextSibling();
        }
      }
    }
    if (fragment) {
      nsTreeSanitizer sanitizer(aFlags);
      sanitizer.Sanitize(fragment);
    }
  }

  if (scripts_enabled)
      loader->SetEnabled(true);
  
  return rv;
}
Beispiel #15
0
static bool
DeleteCString(nsHashKey *aKey, void *aData, void* closure)
{
    NS_Free(aData);
    return true;
}
Beispiel #16
0
NS_IMETHODIMP
ImportEudoraMailImpl::ImportMailbox(nsIImportMailboxDescriptor *pSource,
                                    nsIMsgFolder *pDstFolder,
                                    PRUnichar **pErrorLog,
                                    PRUnichar **pSuccessLog,
                                    bool *fatalError)
{
  NS_ENSURE_ARG_POINTER(pSource);
  NS_ENSURE_ARG_POINTER(pDstFolder);
  NS_ENSURE_ARG_POINTER(fatalError);

  nsString  success;
  nsString  error;
  bool      abort = false;
  nsString  name;
  PRUnichar *  pName;
  if (NS_SUCCEEDED(pSource->GetDisplayName(&pName)))
  {
    name = pName;
    NS_Free(pName);
  }

  PRUint32 mailSize = 0;
  pSource->GetSize(&mailSize);
  if (mailSize == 0)
  {
    IMPORT_LOG0("Mailbox size is 0, skipping mailbox.\n");
    ReportSuccess(name, 0, &success);
    SetLogs(success, error, pErrorLog, pSuccessLog);
    return NS_OK;
  }


  nsCOMPtr <nsIFile>  inFile;
  if (NS_FAILED(pSource->GetFile(getter_AddRefs(inFile))))
  {
    ReportError(EUDORAIMPORT_MAILBOX_BADSOURCEFILE, name, &error);
    SetLogs(success, error, pErrorLog, pSuccessLog);
    return NS_ERROR_FAILURE;
  }

#ifdef IMPORT_DEBUG
  nsCString pPath;
  inFile->GetNativePath(pPath);
  IMPORT_LOG1("Import mailbox: %s\n", pPath.get());
#endif


  PRInt32  msgCount = 0;
  nsresult rv = NS_OK;

  m_bytes = 0;
  rv = m_eudora.ImportMailbox( &m_bytes, &abort, name.get(), inFile, pDstFolder, &msgCount);
  if (NS_SUCCEEDED(rv))
    ReportSuccess(name, msgCount, &success);
  else
    ReportError(EUDORAIMPORT_MAILBOX_CONVERTERROR, name, &error);

  SetLogs(success, error, pErrorLog, pSuccessLog);

  IMPORT_LOG0("*** Returning from eudora mailbox import\n");

  return rv;
}
NS_IMETHODIMP nsImportGenericAddressBooks::GetData(const char *dataId, nsISupports **_retval)
{
  NS_PRECONDITION(_retval != nullptr, "null ptr");
  if (!_retval)
    return NS_ERROR_NULL_POINTER;

  nsresult rv;
  *_retval = nullptr;
  if (!PL_strcasecmp(dataId, "addressInterface")) {
    *_retval = m_pInterface;
    NS_IF_ADDREF(m_pInterface);
  }

  if (!PL_strcasecmp(dataId, "addressLocation")) {
    if (!m_pLocation)
      GetDefaultLocation();
    NS_IF_ADDREF(*_retval = m_pLocation);
  }

  if (!PL_strcasecmp(dataId, "addressBooks")) {
    if (!m_pLocation)
      GetDefaultLocation();
    if (!m_Books)
      GetDefaultBooks();
    *_retval = m_Books;
  }

  if (!PL_strcasecmp(dataId, "addressDestination")) {
    if (m_pDestinationUri) {
            nsCOMPtr<nsISupportsCString> abString = do_CreateInstance(NS_SUPPORTS_CSTRING_CONTRACTID, &rv);
            NS_ENSURE_SUCCESS(rv, rv);
            abString->SetData(nsDependentCString(m_pDestinationUri));
            NS_IF_ADDREF(*_retval = abString);
    }
  }

  if (!PL_strcasecmp(dataId, "fieldMap")) {
    if (m_pFieldMap) {
      *_retval = m_pFieldMap;
      m_pFieldMap->AddRef();
    }
    else {
      if (m_pInterface && m_pLocation) {
        bool needsIt = false;
        m_pInterface->GetNeedsFieldMap(m_pLocation, &needsIt);
        if (needsIt) {
          GetDefaultFieldMap();
          if (m_pFieldMap) {
            *_retval = m_pFieldMap;
            m_pFieldMap->AddRef();
          }
        }
      }
    }
  }

  if (!PL_strncasecmp(dataId, "sampleData-", 11)) {
    // extra the record number
    const char *pNum = dataId + 11;
    int32_t  rNum = 0;
    while (*pNum) {
      rNum *= 10;
      rNum += (*pNum - '0');
      pNum++;
    }
    IMPORT_LOG1("Requesting sample data #: %ld\n", (long)rNum);
    if (m_pInterface) {
      nsCOMPtr<nsISupportsString>  data = do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID, &rv);
      if (NS_FAILED(rv))
        return rv;
      char16_t *  pData = nullptr;
      bool      found = false;
      rv = m_pInterface->GetSampleData(rNum, &found, &pData);
      if (NS_FAILED(rv))
        return rv;
      if (found) {
        data->SetData(nsDependentString(pData));
        *_retval = data;
        NS_ADDREF(*_retval);
      }
      NS_Free(pData);
    }
  }

  return NS_OK;
}
Beispiel #18
0
NS_IMETHODIMP
EmbedWindow::OnShowTooltip(PRInt32 aXCoords, PRInt32 aYCoords,
			   const PRUnichar *aTipText)
{
  nsAutoString tipText ( aTipText );

  const char* tipString = ToNewUTF8String(tipText);

  if (sTipWindow)
    gtk_widget_destroy(sTipWindow);
  
  // get the root origin for this content window
  nsCOMPtr<nsIWidget> mainWidget;
  mBaseWindow->GetMainWidget(getter_AddRefs(mainWidget));
  GdkWindow *window;
  window = static_cast<GdkWindow *>(mainWidget->GetNativeData(NS_NATIVE_WINDOW));
  gint root_x, root_y;
  gdk_window_get_origin(window, &root_x, &root_y);

  // XXX work around until I can get pink to figure out why
  // tooltips vanish if they show up right at the origin of the
  // cursor.
  root_y += 10;
  
  sTipWindow = gtk_window_new(GTK_WINDOW_POPUP);
  gtk_widget_set_app_paintable(sTipWindow, TRUE);
  gtk_window_set_resizable(GTK_WINDOW(sTipWindow), TRUE);
  // needed to get colors + fonts etc correctly
  gtk_widget_set_name(sTipWindow, "gtk-tooltips");
  gtk_window_set_type_hint(GTK_WINDOW(sTipWindow), GDK_WINDOW_TYPE_HINT_TOOLTIP);
  
  // set up the popup window as a transient of the widget.
  GtkWidget *toplevel_window;
  toplevel_window = gtk_widget_get_toplevel(GTK_WIDGET(mOwner->mOwningWidget));
  if (!GTK_WINDOW(toplevel_window)) {
    NS_ERROR("no gtk window in hierarchy!\n");
    return NS_ERROR_FAILURE;
  }
  gtk_window_set_transient_for(GTK_WINDOW(sTipWindow),
			       GTK_WINDOW(toplevel_window));
  
  // realize the widget
  gtk_widget_realize(sTipWindow);

  g_signal_connect(G_OBJECT(sTipWindow), "expose_event",
                   G_CALLBACK(tooltips_paint_window), NULL);

  // set up the label for the tooltip
  GtkWidget *label = gtk_label_new(tipString);
  // wrap automatically
  gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
  gtk_container_add(GTK_CONTAINER(sTipWindow), label);
  gtk_container_set_border_width(GTK_CONTAINER(sTipWindow), 4);
  // set the coords for the widget
  gtk_widget_set_uposition(sTipWindow, aXCoords + root_x,
			   aYCoords + root_y);

  // and show it.
  gtk_widget_show_all(sTipWindow);

  NS_Free( (void*)tipString );

  return NS_OK;
}
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;
}
/* nsIVariant getPreference (in AString aPrefName); */
NS_IMETHODIMP sbMockDevice::GetPreference(const nsAString & aPrefName, nsIVariant **_retval)
{
  /* what, you expect a mock device to be actually useful? */
  NS_ENSURE_ARG_POINTER(_retval);
  nsresult rv;

  nsCOMPtr<nsIPrefService> prefRoot =
    do_GetService("@mozilla.org/preferences-service;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIPrefBranch> prefBranch;
  rv = prefRoot->GetBranch(DEVICE_PREF_BRANCH, getter_AddRefs(prefBranch));
  NS_ENSURE_SUCCESS(rv, rv);

  NS_LossyConvertUTF16toASCII prefNameC(aPrefName);

  PRInt32 prefType;
  rv = prefBranch->GetPrefType(prefNameC.get(),
                               &prefType);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIWritableVariant> result =
    do_CreateInstance("@songbirdnest.com/Songbird/Variant;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  switch(prefType) {
    case nsIPrefBranch::PREF_INVALID: {
      rv = result->SetAsVoid();
      NS_ENSURE_SUCCESS(rv, rv);
      break;
    }
    case nsIPrefBranch::PREF_STRING: {
      char *value = nsnull;
      rv = prefBranch->GetCharPref(prefNameC.get(), &value);
      NS_ENSURE_SUCCESS(rv, rv);
      rv = result->SetAsString(value);
      NS_Free(value);
      NS_ENSURE_SUCCESS(rv, rv);
      break;
    }
    case nsIPrefBranch::PREF_INT: {
      PRInt32 value;
      rv = prefBranch->GetIntPref(prefNameC.get(), &value);
      NS_ENSURE_SUCCESS(rv, rv);
      rv = result->SetAsInt32(value);
      NS_ENSURE_SUCCESS(rv, rv);
      break;
    }
    case nsIPrefBranch::PREF_BOOL: {
      bool value;
      rv = prefBranch->GetBoolPref(prefNameC.get(), &value);
      NS_ENSURE_SUCCESS(rv, rv);
      rv = result->SetAsBool(value);
      NS_ENSURE_SUCCESS(rv, rv);
      break;
    }
    default: {
      /* wtf? */
      return NS_ERROR_UNEXPECTED;
    }
  }

  return CallQueryInterface(result, _retval);
}
Beispiel #21
0
nsMemoryImpl::Free(void* aPtr)
{
  NS_Free(aPtr);
}
Beispiel #22
0
nsMemoryImpl::Free(void* ptr)
{
    NS_Free(ptr);
}
Beispiel #23
0
nsFileView::~nsFileView()
{
  uint32_t count = mCurrentFilters.Length();
  for (uint32_t i = 0; i < count; ++i)
    NS_Free(mCurrentFilters[i]);
}
nsresult
sbCDDeviceMarshall::RemoveDevice(sbIDevice* aDevice) {
  nsresult rv;

  // Get the device name.
  nsString                  deviceName;
  nsCOMPtr<nsIPropertyBag2> parameters;
  nsCOMPtr<nsIVariant>      var;
  nsCOMPtr<nsISupports>     supports;
  rv = aDevice->GetParameters(getter_AddRefs(parameters));
  NS_ENSURE_SUCCESS(rv, rv);
  rv = parameters->GetProperty(NS_LITERAL_STRING("sbICDDevice"),
                               getter_AddRefs(var));
  NS_ENSURE_SUCCESS(rv, rv);
  rv = var->GetAsISupports(getter_AddRefs(supports));
  NS_ENSURE_SUCCESS(rv, rv);
  nsCOMPtr<sbICDDevice> cdDevice = do_QueryInterface(supports, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = cdDevice->GetName(deviceName);
  NS_ENSURE_SUCCESS(rv, rv);

  // Just return if device is not in the hash of known CD devices.
  PRBool hasDevice;
  rv = GetHasDevice(deviceName, &hasDevice);
  NS_ENSURE_SUCCESS(rv, rv);
  if (!hasDevice)
    return NS_OK;

  // Remove device from hash of known CD devices.
  {
    nsAutoMonitor mon(mKnownDevicesLock);
    mKnownDevices.Remove(deviceName);
  }

  nsCOMPtr<sbIDeviceRegistrar> deviceRegistrar =
    do_GetService("@songbirdnest.com/Songbird/DeviceManager;2", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<sbIDeviceControllerRegistrar> deviceControllerRegistrar =
    do_GetService("@songbirdnest.com/Songbird/DeviceManager;2", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  // Get the device controller for this device.
  nsCOMPtr<sbIDeviceController> deviceController;
  nsID *controllerId = nsnull;
  rv = aDevice->GetControllerId(&controllerId);
  if (NS_SUCCEEDED(rv)) {
    rv = deviceControllerRegistrar->GetController(
        controllerId,
        getter_AddRefs(deviceController));
  }

  if (NS_FAILED(rv)) {
    NS_WARNING("Failed to get device controller.");
    deviceController = nsnull;
  }

  if (controllerId) {
    NS_Free(controllerId);
  }

  // Release the device from the controller
  if (deviceController) {
    rv = deviceController->ReleaseDevice(aDevice);
    NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "Failed to release the device");
  }

  // Unregister the device
  rv = deviceRegistrar->UnregisterDevice(aDevice);
  NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "Failed to unregister device");

  return NS_OK;
}
Beispiel #25
0
NS_IMETHODIMP nsImportFieldMap::SetFieldValue(nsIAddrDatabase *database, nsIMdbRow *row, PRInt32 fieldNum, const PRUnichar *value)
{
  NS_PRECONDITION(database != nsnull, "null ptr");
  NS_PRECONDITION(row != nsnull, "null ptr");
  NS_PRECONDITION(value != nsnull, "null ptr");
  if (!database || !row || !value)
    return NS_ERROR_NULL_POINTER;

  // Allow the special value for a null field
  if (fieldNum == -1)
    return( NS_OK);

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

  // UGGG!!!!! lot's of typing here!
  nsresult rv;

  nsString str(value);
  char *pVal = ToNewUTF8String(str);

  switch( fieldNum) {
  case 0:
    rv = database->AddFirstName( row, pVal);
    break;
  case 1:
    rv = database->AddLastName( row, pVal);
    break;
  case 2:
    rv = database->AddDisplayName( row, pVal);
    break;
  case 3:
    rv = database->AddNickName( row, pVal);
    break;
  case 4:
    rv = database->AddPrimaryEmail( row, pVal);
    break;
  case 5:
    rv = database->Add2ndEmail( row, pVal);
    break;
  case 6:
    rv = database->AddWorkPhone( row, pVal);
    break;
  case 7:
    rv = database->AddHomePhone( row, pVal);
    break;
  case 8:
    rv = database->AddFaxNumber( row, pVal);
    break;
  case 9:
    rv = database->AddPagerNumber( row, pVal);
    break;
  case 10:
    rv = database->AddCellularNumber( row, pVal);
    break;
  case 11:
    rv = database->AddHomeAddress( row, pVal);
    break;
  case 12:
    rv = database->AddHomeAddress2( row, pVal);
    break;
  case 13:
    rv = database->AddHomeCity( row, pVal);
    break;
  case 14:
    rv = database->AddHomeState( row, pVal);
    break;
  case 15:
    rv = database->AddHomeZipCode( row, pVal);
    break;
  case 16:
    rv = database->AddHomeCountry( row, pVal);
    break;
  case 17:
    rv = database->AddWorkAddress( row, pVal);
    break;
  case 18:
    rv = database->AddWorkAddress2( row, pVal);
    break;
  case 19:
    rv = database->AddWorkCity( row, pVal);
    break;
  case 20:
    rv = database->AddWorkState( row, pVal);
    break;
  case 21:
    rv = database->AddWorkZipCode( row, pVal);
    break;
  case 22:
    rv = database->AddWorkCountry( row, pVal);
    break;
  case 23:
    rv = database->AddJobTitle(row, pVal);
    break;
  case 24:
    rv = database->AddDepartment(row, pVal);
    break;
  case 25:
    rv = database->AddCompany(row, pVal);
    break;
  case 26:
    rv = database->AddWebPage1(row, pVal);
    break;
  case 27:
    rv = database->AddWebPage2(row, pVal);
    break;
  case 28:
    rv = database->AddBirthYear(row, pVal);
    break;
  case 29:
    rv = database->AddBirthMonth(row, pVal);
    break;
  case 30:
    rv = database->AddBirthDay(row, pVal);
    break;
  case 31:
    rv = database->AddCustom1(row, pVal);
    break;
  case 32:
    rv = database->AddCustom2(row, pVal);
    break;
  case 33:
    rv = database->AddCustom3(row, pVal);
    break;
  case 34:
    rv = database->AddCustom4(row, pVal);
    break;
  case 35:
    rv = database->AddNotes(row, pVal);
    break;
  case 36:
    rv = database->AddAimScreenName(row, pVal);
    break;
  default:
    /* Get the field description, and add it as an anonymous attr? */
    /* OR WHAT???? */
    {
      rv = NS_ERROR_FAILURE;
    }
  }

  NS_Free( pVal);

  return( rv);
}
Beispiel #26
0
static void ImportAddressThread( void *stuff)
{
  IMPORT_LOG0( "In Begin ImportAddressThread\n");

  AddressThreadData *pData = (AddressThreadData *)stuff;
  PRUint32  count = 0;
  nsresult   rv = pData->books->Count( &count);

  PRUint32          i;
  PRBool            import;
  PRUint32          size;
  nsCOMPtr<nsIAddrDatabase>  destDB( getter_AddRefs( GetAddressBookFromUri( pData->pDestinationUri)));
  nsCOMPtr<nsIAddrDatabase> pDestDB;

  nsString          success;
  nsString          error;

    nsCOMPtr<nsIStringBundle> pBundle;
    rv = nsImportStringBundle::GetStringBundleProxy(pData->stringBundle, getter_AddRefs(pBundle));
    if (NS_FAILED(rv))
    {
      IMPORT_LOG0("*** ImportMailThread: Unable to obtain proxy string service for the import.");
      pData->abort = PR_TRUE;
    }

  for (i = 0; (i < count) && !(pData->abort); i++) {
    nsCOMPtr<nsIImportABDescriptor> book =
      do_QueryElementAt(pData->books, i);
    if (book) {
      import = PR_FALSE;
      size = 0;
      rv = book->GetImport( &import);
      if (import)
        rv = book->GetSize( &size);

      if (size && import) {
        nsString name;
        book->GetPreferredName(name);
        if (destDB) {
          pDestDB = destDB;
        }
        else {
          pDestDB = GetAddressBook(name.get(), PR_TRUE);
        }

        nsCOMPtr<nsIProxyObjectManager> proxyObjectManager =
          do_GetService(NS_XPCOMPROXY_CONTRACTID, &rv);
        if (NS_FAILED(rv))
          return;

        nsCOMPtr<nsIAddrDatabase> proxyAddrDatabase;
        rv = proxyObjectManager->GetProxyForObject(NS_PROXY_TO_MAIN_THREAD,
                                                   NS_GET_IID(nsIAddrDatabase),
                                                   pDestDB,
                                                   NS_PROXY_SYNC | NS_PROXY_ALWAYS,
                                                   getter_AddRefs(proxyAddrDatabase));
        if (NS_FAILED(rv))
          return;


        PRBool fatalError = PR_FALSE;
        pData->currentSize = size;
        if (proxyAddrDatabase) {
          PRUnichar *pSuccess = nsnull;
          PRUnichar *pError = nsnull;

          /*
          if (pData->fieldMap) {
            PRInt32    sz = 0;
            PRInt32    mapIndex;
            PRBool    active;
            pData->fieldMap->GetMapSize( &sz);
            IMPORT_LOG1( "**** Field Map Size: %d\n", (int) sz);
            for (PRInt32 i = 0; i < sz; i++) {
              pData->fieldMap->GetFieldMap( i, &mapIndex);
              pData->fieldMap->GetFieldActive( i, &active);
              IMPORT_LOG3( "Field map #%d: index=%d, active=%d\n", (int) i, (int) mapIndex, (int) active);
            }
          }
          */

          rv = pData->addressImport->ImportAddressBook(book,
                                                       proxyAddrDatabase,
                                                       pData->fieldMap,
                                                       pData->ldifService,
                                                       pData->bAddrLocInput,
                                                       &pError,
                                                       &pSuccess,
                                                       &fatalError);
          if (pSuccess) {
            success.Append( pSuccess);
            NS_Free( pSuccess);
          }
          if (pError) {
            error.Append( pError);
            NS_Free( pError);
          }
        }
        else {
          nsImportGenericAddressBooks::ReportError(name.get(), &error, pBundle);
        }

        pData->currentSize = 0;
        pData->currentTotal += size;

        if (!proxyAddrDatabase) {
          proxyAddrDatabase->Close( PR_TRUE);
        }

        if (fatalError) {
          pData->fatalError = PR_TRUE;
          break;
        }
      }
    }

    if (destDB) {
      destDB->Close( PR_TRUE);
    }
  }


  nsImportGenericAddressBooks::SetLogs( success, error, pData->successLog, pData->errorLog);

  if (pData->abort || pData->fatalError) {
    // FIXME: do what is necessary to get rid of what has been imported so far.
    // Nothing if we went into an existing address book!  Otherwise, delete
    // the ones we created?
  }

  pData->ThreadDelete();
}
nsresult nsMsgSearchAdapter::EncodeImapTerm (nsIMsgSearchTerm *term, bool reallyDredd, const PRUnichar *srcCharset, const PRUnichar *destCharset, char **ppOutTerm)
{
  NS_ENSURE_ARG_POINTER(term);
  NS_ENSURE_ARG_POINTER(ppOutTerm);

  nsresult err = NS_OK;
  bool useNot = false;
  bool useQuotes = false;
  bool ignoreValue = false;
  nsCAutoString arbitraryHeader;
  const char *whichMnemonic = nsnull;
  const char *orHeaderMnemonic = nsnull;

  *ppOutTerm = nsnull;

  nsCOMPtr <nsIMsgSearchValue> searchValue;
  nsresult rv = term->GetValue(getter_AddRefs(searchValue));

  NS_ENSURE_SUCCESS(rv,rv);

  nsMsgSearchOpValue op;
  term->GetOp(&op);

  if (op == nsMsgSearchOp::DoesntContain || op == nsMsgSearchOp::Isnt)
    useNot = true;

  nsMsgSearchAttribValue attrib;
  term->GetAttrib(&attrib);

  switch (attrib)
  {
  case nsMsgSearchAttrib::ToOrCC:
    orHeaderMnemonic = m_kImapCC;
    // fall through to case nsMsgSearchAttrib::To:
  case nsMsgSearchAttrib::To:
    whichMnemonic = m_kImapTo;
    break;
  case nsMsgSearchAttrib::CC:
    whichMnemonic = m_kImapCC;
    break;
  case nsMsgSearchAttrib::Sender:
    whichMnemonic = m_kImapFrom;
    break;
  case nsMsgSearchAttrib::Subject:
    whichMnemonic = m_kImapSubject;
    break;
  case nsMsgSearchAttrib::Body:
    whichMnemonic = m_kImapBody;
    break;
  case nsMsgSearchAttrib::AgeInDays:  // added for searching online for age in days...
    // for AgeInDays, we are actually going to perform a search by date, so convert the operations for age
    // to the IMAP mnemonics that we would use for date!
    {
      // If we have a future date, the > and < are reversed.
      // e.g. ageInDays > 2 means more than 2 days old ("date before X") whereas
      //      ageInDays > -2 should be more than 2 days in the future ("date after X")
      PRInt32 ageInDays;
      searchValue->GetAge(&ageInDays);
      bool dateInFuture = (ageInDays < 0);
      switch (op)
      {
      case nsMsgSearchOp::IsGreaterThan:
        whichMnemonic = (!dateInFuture) ? m_kImapBefore : m_kImapSince;
        break;
      case nsMsgSearchOp::IsLessThan:
        whichMnemonic = (!dateInFuture) ? m_kImapSince : m_kImapBefore;
        break;
      case nsMsgSearchOp::Is:
        whichMnemonic = m_kImapSentOn;
        break;
      default:
        NS_ASSERTION(false, "invalid search operator");
        return NS_ERROR_INVALID_ARG;
      }
    }
    break;
  case nsMsgSearchAttrib::Size:
    switch (op)
    {
    case nsMsgSearchOp::IsGreaterThan:
      whichMnemonic = m_kImapSizeLarger;
      break;
    case nsMsgSearchOp::IsLessThan:
      whichMnemonic = m_kImapSizeSmaller;
      break;
    default:
      NS_ASSERTION(false, "invalid search operator");
      return NS_ERROR_INVALID_ARG;
    }
    break;
    case nsMsgSearchAttrib::Date:
      switch (op)
      {
      case nsMsgSearchOp::IsBefore:
        whichMnemonic = m_kImapBefore;
        break;
      case nsMsgSearchOp::IsAfter:
        whichMnemonic = m_kImapSince;
        break;
      case nsMsgSearchOp::Isnt:  /* we've already added the "Not" so just process it like it was a date is search */
      case nsMsgSearchOp::Is:
        whichMnemonic = m_kImapSentOn;
        break;
      default:
        NS_ASSERTION(false, "invalid search operator");
        return NS_ERROR_INVALID_ARG;
      }
      break;
    case nsMsgSearchAttrib::AnyText:
      whichMnemonic = m_kImapAnyText;
      break;
    case nsMsgSearchAttrib::Keywords:
      whichMnemonic = m_kImapKeyword;
      break;
    case nsMsgSearchAttrib::MsgStatus:
      useNot = false; // bizarrely, NOT SEEN is wrong, but UNSEEN is right.
      ignoreValue = true; // the mnemonic is all we need
      PRUint32 status;
      searchValue->GetStatus(&status);

      switch (status)
      {
      case nsMsgMessageFlags::Read:
        whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapSeen : m_kImapNotSeen;
        break;
      case nsMsgMessageFlags::Replied:
        whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapAnswered : m_kImapNotAnswered;
        break;
      case nsMsgMessageFlags::New:
        whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapNew : m_kImapNotNew;
        break;
      case nsMsgMessageFlags::Marked:
        whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapFlagged : m_kImapNotFlagged;
        break;
      default:
        NS_ASSERTION(false, "invalid search operator");
        return NS_ERROR_INVALID_ARG;
      }
      break;
    default:
      if ( attrib > nsMsgSearchAttrib::OtherHeader && attrib < nsMsgSearchAttrib::kNumMsgSearchAttributes)
      {
        nsCString arbitraryHeaderTerm;
        term->GetArbitraryHeader(arbitraryHeaderTerm);
        if (!arbitraryHeaderTerm.IsEmpty())
        {
          arbitraryHeader.AssignLiteral(" \"");
          arbitraryHeader.Append(arbitraryHeaderTerm);
          arbitraryHeader.AppendLiteral("\" ");
          whichMnemonic = arbitraryHeader.get();
        }
        else
          return NS_ERROR_FAILURE;
      }
      else
      {
        NS_ASSERTION(false, "invalid search operator");
        return NS_ERROR_INVALID_ARG;
      }
    }

    char *value = nsnull;
    char dateBuf[100];
    dateBuf[0] = '\0';

    bool valueWasAllocated = false;
    if (attrib == nsMsgSearchAttrib::Date)
    {
      // note that there used to be code here that encoded an RFC822 date for imap searches.
      // The IMAP RFC 2060 is misleading to the point that it looks like it requires an RFC822
      // date but really it expects dd-mmm-yyyy, like dredd, and refers to the RFC822 date only in that the
      // dd-mmm-yyyy date will match the RFC822 date within the message.

      PRTime adjustedDate;
      searchValue->GetDate(&adjustedDate);
      if (whichMnemonic == m_kImapSince)
      {
        // it looks like the IMAP server searches on Since includes the date in question...
        // our UI presents Is, IsGreater and IsLessThan. For the IsGreater case (m_kImapSince)
        // we need to adjust the date so we get greater than and not greater than or equal to which
        // is what the IMAP server wants to search on
        // won't work on Mac.
        // ack, is this right? is PRTime seconds or microseconds?
        PRInt64 microSecondsPerSecond, secondsInDay, microSecondsInDay;

        LL_I2L(microSecondsPerSecond, PR_USEC_PER_SEC);
        LL_UI2L(secondsInDay, 60 * 60 * 24);
        LL_MUL(microSecondsInDay, secondsInDay, microSecondsPerSecond);
        LL_ADD(adjustedDate, adjustedDate, microSecondsInDay); // bump up to the day after this one...
      }

      PRExplodedTime exploded;
      PR_ExplodeTime(adjustedDate, PR_LocalTimeParameters, &exploded);
      PR_FormatTimeUSEnglish(dateBuf, sizeof(dateBuf), "%d-%b-%Y", &exploded);
      //    strftime (dateBuf, sizeof(dateBuf), "%d-%b-%Y", localtime (/* &term->m_value.u.date */ &adjustedDate));
      value = dateBuf;
    }
    else
    {
      if (attrib == nsMsgSearchAttrib::AgeInDays)
      {
        // okay, take the current date, subtract off the age in days, then do an appropriate Date search on
        // the resulting day.
        PRInt32 ageInDays;

        searchValue->GetAge(&ageInDays);

        PRTime now = PR_Now();
        PRTime matchDay;

        PRInt64 microSecondsPerSecond, secondsInDays, microSecondsInDay;

        LL_I2L(microSecondsPerSecond, PR_USEC_PER_SEC);
        LL_I2L(secondsInDays, 60 * 60 * 24 * ageInDays);
        LL_MUL(microSecondsInDay, secondsInDays, microSecondsPerSecond);

        LL_SUB(matchDay, now, microSecondsInDay); // = now - term->m_value.u.age * 60 * 60 * 24;
        PRExplodedTime exploded;
        PR_ExplodeTime(matchDay, PR_LocalTimeParameters, &exploded);
        PR_FormatTimeUSEnglish(dateBuf, sizeof(dateBuf), "%d-%b-%Y", &exploded);
        //      strftime (dateBuf, sizeof(dateBuf), "%d-%b-%Y", localtime (&matchDay));
        value = dateBuf;
      }
      else if (attrib == nsMsgSearchAttrib::Size)
      {
        PRUint32 sizeValue;
        nsCAutoString searchTermValue;
        searchValue->GetSize(&sizeValue);

        // Multiply by 1024 to get into kb resolution
        sizeValue *= 1024;

        // Ensure that greater than is really greater than
        // in kb resolution.
        if (op == nsMsgSearchOp::IsGreaterThan)
          sizeValue += 1024;

        searchTermValue.AppendInt(sizeValue);

        value = ToNewCString(searchTermValue);
        valueWasAllocated = true;
      }
      else

      if (IS_STRING_ATTRIBUTE(attrib))
      {
        PRUnichar *convertedValue; // = reallyDredd ? MSG_EscapeSearchUrl (term->m_value.u.string) : msg_EscapeImapSearchProtocol(term->m_value.u.string);
        nsString searchTermValue;
        searchValue->GetStr(searchTermValue);
        // Ugly switch for Korean mail/news charsets.
        // We want to do this here because here is where
        // we know what charset we want to use.
#ifdef DOING_CHARSET
        if (reallyDredd)
          dest_csid = INTL_DefaultNewsCharSetID(dest_csid);
        else
          dest_csid = INTL_DefaultMailCharSetID(dest_csid);
#endif

        // do all sorts of crazy escaping
        convertedValue = reallyDredd ? EscapeSearchUrl (searchTermValue.get()) :
        EscapeImapSearchProtocol(searchTermValue.get());
        useQuotes = ((!reallyDredd ||
                    (nsDependentString(convertedValue).FindChar(PRUnichar(' ')) != -1)) &&
           (attrib != nsMsgSearchAttrib::Keywords));
        // now convert to char* and escape quoted_specials
        nsCAutoString valueStr;
        nsresult rv = ConvertFromUnicode(NS_LossyConvertUTF16toASCII(destCharset).get(),
          nsDependentString(convertedValue), valueStr);
        if (NS_SUCCEEDED(rv))
        {
          const char *vptr = valueStr.get();
          // max escaped length is one extra character for every character in the cmd.
          nsAutoArrayPtr<char> newValue(new char[2*strlen(vptr) + 1]);
          if (newValue)
          {
            char *p = newValue;
            while (1)
            {
              char ch = *vptr++;
              if (!ch)
                break;
              if ((useQuotes ? ch == '"' : 0) || ch == '\\')
                *p++ = '\\';
              *p++ = ch;
            }
            *p = '\0';
            value = strdup(newValue); // realloc down to smaller size
          }
        }
        else
          value = strdup("");
        NS_Free(convertedValue);
        valueWasAllocated = true;

      }
    }

    // this should be rewritten to use nsCString
    int subLen =
      (value ? strlen(value) : 0) +
      (useNot ? strlen(m_kImapNot) : 0) +
      strlen(m_kImapHeader);
    int len = strlen(whichMnemonic) + subLen + (useQuotes ? 2 : 0) +
      (orHeaderMnemonic
       ? (subLen + strlen(m_kImapOr) + strlen(orHeaderMnemonic) + 2 /*""*/)
       : 0) +
      10; // add slough for imap string literals
    char *encoding = new char[len];
    if (encoding)
    {
      encoding[0] = '\0';
      // Remember: if ToOrCC and useNot then the expression becomes NOT To AND Not CC as opposed to (NOT TO) || (NOT CC)
      if (orHeaderMnemonic && !useNot)
        PL_strcat(encoding, m_kImapOr);
      if (useNot)
        PL_strcat (encoding, m_kImapNot);
      if (!arbitraryHeader.IsEmpty())
        PL_strcat (encoding, m_kImapHeader);
      PL_strcat (encoding, whichMnemonic);
      if (!ignoreValue)
        err = EncodeImapValue(encoding, value, useQuotes, reallyDredd);

      if (orHeaderMnemonic)
      {
        if (useNot)
          PL_strcat(encoding, m_kImapNot);

        PL_strcat (encoding, m_kImapHeader);

        PL_strcat (encoding, orHeaderMnemonic);
        if (!ignoreValue)
          err = EncodeImapValue(encoding, value, useQuotes, reallyDredd);
      }

      // kmcentee, don't let the encoding end with whitespace,
      // this throws off later url STRCMP
      if (*encoding && *(encoding + strlen(encoding) - 1) == ' ')
        *(encoding + strlen(encoding) - 1) = '\0';
    }

    if (value && valueWasAllocated)
      NS_Free (value);

    *ppOutTerm = encoding;

    return err;
}
void nsMessengerUnixIntegration::FillToolTipInfo()
{
  nsresult rv;
  nsCString folderUri;
  GetFirstFolderWithNewMail(folderUri);

  uint32_t count = 0;
  if (NS_FAILED(mFoldersWithNewMail->Count(&count)))
    return;

  nsCOMPtr<nsIWeakReference> weakReference;
  nsCOMPtr<nsIMsgFolder> folder = nullptr;
  nsCOMPtr<nsIMsgFolder> folderWithNewMail = nullptr;

  uint32_t i;
  for (i = 0; i < count && !folderWithNewMail; i++)
  {
    weakReference = do_QueryElementAt(mFoldersWithNewMail, i);
    folder = do_QueryReferent(weakReference);
    folder->GetChildWithURI(folderUri, true, true,
                            getter_AddRefs(folderWithNewMail));
  }

  if (folder && folderWithNewMail)
  {
#ifdef MOZ_THUNDERBIRD
    nsCOMPtr<nsIStringBundle> bundle;
    GetStringBundle(getter_AddRefs(bundle));

    if (!bundle)
      return;

    // Create the notification title
    nsString alertTitle;
    if (!BuildNotificationTitle(folder, bundle, alertTitle))
      return;

    // Let's get the new mail for this folder
    nsCOMPtr<nsIMsgDatabase> db;
    if (NS_FAILED(folderWithNewMail->GetMsgDatabase(getter_AddRefs(db))))
      return;

    uint32_t numNewKeys = 0;
    uint32_t *newMessageKeys;
    db->GetNewList(&numNewKeys, &newMessageKeys);

    // If we had new messages, we *should* have new keys, but we'll
    // check just in case.
    if (numNewKeys <= 0) {
      NS_Free(newMessageKeys);
      return;
    }

    // Find the rootFolder that folder belongs to, and find out
    // what MRUTime it maps to.  Assign this to lastMRUTime.
    uint32_t lastMRUTime = 0;
    if (NS_FAILED(GetMRUTimestampForFolder(folder, &lastMRUTime)))
      lastMRUTime = 0;

    // Next, add the new message headers to an nsCOMArray.  We
    // only add message headers that are newer than lastMRUTime.
    nsCOMArray<nsIMsgDBHdr> newMsgHdrs;
    for (unsigned int i = 0; i < numNewKeys; ++i) {
      nsCOMPtr<nsIMsgDBHdr> hdr;
      if (NS_FAILED(db->GetMsgHdrForKey(newMessageKeys[i], getter_AddRefs(hdr))))
        continue;

      uint32_t dateInSeconds = 0;
      hdr->GetDateInSeconds(&dateInSeconds);

      if (dateInSeconds > lastMRUTime)
        newMsgHdrs.AppendObject(hdr);

    }

    // At this point, we don't need newMessageKeys any more,
    // so let's free it.
    NS_Free(newMessageKeys);

    // If we didn't happen to add any message headers, bail out
    if (!newMsgHdrs.Count())
      return;

    // Sort the message headers by dateInSeconds, in ascending
    // order
    newMsgHdrs.Sort(nsMsgDbHdrTimestampComparator, nullptr);

    nsString alertBody;

    // Build the body text of the notification.
    if (!BuildNotificationBody(newMsgHdrs[0], bundle, alertBody))
      return;

    // Show the notification
    ShowAlertMessage(alertTitle, alertBody, EmptyCString());

    // Find the last, and therefore newest message header
    // in our nsCOMArray
    nsCOMPtr<nsIMsgDBHdr> lastMsgHdr = newMsgHdrs[newMsgHdrs.Count() - 1];

    uint32_t dateInSeconds = 0;
    if (NS_FAILED(lastMsgHdr->GetDateInSeconds(&dateInSeconds)))
      return;

    // Write the newest message timestamp to the appropriate
    // mapping in our hashtable of MRUTime's.
    PutMRUTimestampForFolder(folder, dateInSeconds);
#else
    nsString accountName;
    folder->GetPrettiestName(accountName);

    nsCOMPtr<nsIStringBundle> bundle;
    GetStringBundle(getter_AddRefs(bundle));
    if (bundle)
    {
      int32_t numNewMessages = 0;
      folder->GetNumNewMessages(true, &numNewMessages);
      nsAutoString numNewMsgsText;
      numNewMsgsText.AppendInt(numNewMessages);

      const PRUnichar *formatStrings[] =
      {
        numNewMsgsText.get(),
      };

      nsString finalText;
      if (numNewMessages == 1)
        bundle->FormatStringFromName(NS_LITERAL_STRING("biffNotification_message").get(), formatStrings, 1, getter_Copies(finalText));
      else
        bundle->FormatStringFromName(NS_LITERAL_STRING("biffNotification_messages").get(), formatStrings, 1, getter_Copies(finalText));

      ShowAlertMessage(accountName, finalText, EmptyCString());
    } // if we got a bundle
#endif
  } // if we got a folder
}
Beispiel #29
0
nsFileView::~nsFileView()
{
  PRUint32 count = mCurrentFilters.Length();
  for (PRUint32 i = 0; i < count; ++i)
    NS_Free(mCurrentFilters[i]);
}
NS_IMETHODIMP
nsJavaXPTCStub::QueryInterface(const nsID &aIID, void **aInstancePtr)
{
  nsresult rv;

  LOG(("JavaStub::QueryInterface()\n"));
  *aInstancePtr = nsnull;
  nsJavaXPTCStub *master = mMaster ? mMaster : this;

  // This helps us differentiate between the help classes.
  if (aIID.Equals(NS_GET_IID(nsJavaXPTCStub)))
  {
    *aInstancePtr = master;
    NS_ADDREF(this);
    return NS_OK;
  }

  // always return the master stub for nsISupports
  if (aIID.Equals(NS_GET_IID(nsISupports)))
  {
    *aInstancePtr = master->mXPTCStub;
    NS_ADDREF(master);
    return NS_OK;
  }

  // All Java objects support weak references
  if (aIID.Equals(NS_GET_IID(nsISupportsWeakReference)))
  {
    *aInstancePtr = static_cast<nsISupportsWeakReference*>(master);
    NS_ADDREF(master);
    return NS_OK;
  }

  // does any existing stub support the requested IID?
  nsJavaXPTCStub *stub = master->FindStubSupportingIID(aIID);
  if (stub)
  {
    *aInstancePtr = stub->mXPTCStub;
    NS_ADDREF(stub);
    return NS_OK;
  }

  JNIEnv* env = GetJNIEnv();

  // Query Java object
  LOG(("\tCalling Java object queryInterface\n"));
  jobject javaObject = env->CallObjectMethod(mJavaWeakRef, getReferentMID);

  jmethodID qiMID = 0;
  jclass clazz = env->GetObjectClass(javaObject);
  if (clazz) {
    char* sig = "(Ljava/lang/String;)Lorg/mozilla/interfaces/nsISupports;";
    qiMID = env->GetMethodID(clazz, "queryInterface", sig);
    NS_ASSERTION(qiMID, "Failed to get queryInterface method ID");
  }

  if (qiMID == 0) {
    env->ExceptionClear();
    return NS_NOINTERFACE;
  }

  // construct IID string
  jstring iid_jstr = nsnull;
  char* iid_str = aIID.ToString();
  if (iid_str) {
    iid_jstr = env->NewStringUTF(iid_str);
  }
  if (!iid_str || !iid_jstr) {
    env->ExceptionClear();
    return NS_ERROR_OUT_OF_MEMORY;
  }
  NS_Free(iid_str);

  // call queryInterface method
  jobject obj = env->CallObjectMethod(javaObject, qiMID, iid_jstr);
  if (env->ExceptionCheck()) {
    env->ExceptionClear();
    return NS_ERROR_FAILURE;
  }
  if (!obj)
    return NS_NOINTERFACE;

  // Get interface info for new java object
  nsCOMPtr<nsIInterfaceInfoManager>
    iim(do_GetService(NS_INTERFACEINFOMANAGER_SERVICE_CONTRACTID, &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIInterfaceInfo> iinfo;
  rv = iim->GetInfoForIID(&aIID, getter_AddRefs(iinfo));
  if (NS_FAILED(rv))
    return rv;

  stub = new nsJavaXPTCStub(obj, iinfo, &rv);
  if (!stub)
    return NS_ERROR_OUT_OF_MEMORY;

  if (NS_FAILED(rv)) {
    delete stub;
    return rv;
  }

  // add stub to the master's list of children, so we can preserve
  // symmetry in future QI calls.  the master will delete each child
  // when it is destroyed.  the refcount of each child is bound to
  // the refcount of the master.  this is done to deal with code
  // like this:
  //
  //   nsCOMPtr<nsIBar> bar = ...;
  //   nsIFoo *foo;
  //   {
  //     nsCOMPtr<nsIFoo> temp = do_QueryInterface(bar);
  //     foo = temp;
  //   }
  //   foo->DoStuff();
  //
  // while this code is not valid XPCOM (since it is using |foo|
  // after having called Release on it), such code is unfortunately
  // very common in the mozilla codebase.  the assumption this code
  // is making is that so long as |bar| is alive, it should be valid
  // to access |foo| even if the code doesn't own a strong reference
  // to |foo|!  clearly wrong, but we need to support it anyways.

  stub->mMaster = master;
  master->mChildren.AppendElement(stub);

  *aInstancePtr = stub->mXPTCStub;
  NS_ADDREF(stub);
  return NS_OK;
}