当前位置: 首页>>代码示例>>C++>>正文


C++ NS_ConvertUTF8toUTF16函数代码示例

本文整理汇总了C++中NS_ConvertUTF8toUTF16函数的典型用法代码示例。如果您正苦于以下问题:C++ NS_ConvertUTF8toUTF16函数的具体用法?C++ NS_ConvertUTF8toUTF16怎么用?C++ NS_ConvertUTF8toUTF16使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NS_ConvertUTF8toUTF16函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: MOZ_ASSERT

void
nsHttpConnectionMgr::OnMsgPrintDiagnostics(int32_t, ARefBase *)
{
  MOZ_ASSERT(OnSocketThread(), "not on socket thread");

  nsCOMPtr<nsIConsoleService> consoleService =
    do_GetService(NS_CONSOLESERVICE_CONTRACTID);
  if (!consoleService)
    return;

  mLogData.AppendPrintf("HTTP Connection Diagnostics\n---------------------\n");
  mLogData.AppendPrintf("IsSpdyEnabled() = %d\n", gHttpHandler->IsSpdyEnabled());
  mLogData.AppendPrintf("MaxSocketCount() = %d\n", gHttpHandler->MaxSocketCount());
  mLogData.AppendPrintf("mNumActiveConns = %d\n", mNumActiveConns);
  mLogData.AppendPrintf("mNumIdleConns = %d\n", mNumIdleConns);

  for (auto iter = mCT.Iter(); !iter.Done(); iter.Next()) {
    RefPtr<nsConnectionEntry> ent = iter.Data();

    mLogData.AppendPrintf(" ent host = %s hashkey = %s\n",
                          ent->mConnInfo->Origin(), ent->mConnInfo->HashKey().get());
    mLogData.AppendPrintf("   AtActiveConnectionLimit = %d\n",
                          AtActiveConnectionLimit(ent, NS_HTTP_ALLOW_KEEPALIVE));
    mLogData.AppendPrintf("   RestrictConnections = %d\n",
                          RestrictConnections(ent));
    mLogData.AppendPrintf("   Pending Q Length = %zu\n",
                          ent->PendingQLength());
    mLogData.AppendPrintf("   Active Conns Length = %zu\n",
                          ent->mActiveConns.Length());
    mLogData.AppendPrintf("   Idle Conns Length = %zu\n",
                          ent->mIdleConns.Length());
    mLogData.AppendPrintf("   Half Opens Length = %zu\n",
                          ent->mHalfOpens.Length());
    mLogData.AppendPrintf("   Coalescing Keys Length = %zu\n",
                          ent->mCoalescingKeys.Length());
    mLogData.AppendPrintf("   Spdy using = %d\n", ent->mUsingSpdy);

    uint32_t i;
    for (i = 0; i < ent->mActiveConns.Length(); ++i) {
      mLogData.AppendPrintf("   :: Active Connection #%u\n", i);
      ent->mActiveConns[i]->PrintDiagnostics(mLogData);
    }
    for (i = 0; i < ent->mIdleConns.Length(); ++i) {
      mLogData.AppendPrintf("   :: Idle Connection #%u\n", i);
      ent->mIdleConns[i]->PrintDiagnostics(mLogData);
    }
    for (i = 0; i < ent->mHalfOpens.Length(); ++i) {
      mLogData.AppendPrintf("   :: Half Open #%u\n", i);
      ent->mHalfOpens[i]->PrintDiagnostics(mLogData);
    }
    i = 0;
    for (auto it = ent->mPendingTransactionTable.Iter();
         !it.Done();
         it.Next()) {
      mLogData.AppendPrintf("   :: Pending Transactions with Window ID = %"
        PRIu64 "\n", it.Key());
      for (uint32_t j = 0; j < it.UserData()->Length(); ++j) {
        mLogData.AppendPrintf("     ::: Pending Transaction #%u\n", i);
        it.UserData()->ElementAt(j)->PrintDiagnostics(mLogData);
        ++i;
      }
    }
    for (i = 0; i < ent->mCoalescingKeys.Length(); ++i) {
      mLogData.AppendPrintf("   :: Coalescing Key #%u %s\n",
                            i, ent->mCoalescingKeys[i].get());
    }
  }

  consoleService->LogStringMessage(NS_ConvertUTF8toUTF16(mLogData).Data());
  mLogData.Truncate();
}
开发者ID:luke-chang,项目名称:gecko-1,代码行数:71,代码来源:ConnectionDiagnostics.cpp

示例2: PR_LOG

NS_IMETHODIMP KDEWallet::FindLogins(PRUint32 *count,
                                    const nsAString & aHostname,
                                    const nsAString & aActionURL,
                                    const nsAString & aHttpRealm,
                                    nsILoginInfo ***logins) {
    PR_LOG( gKDEWalletLog, PR_LOG_DEBUG, ( "KDEWallet::FindLogins() Called") );
    *count = 0;

    nsresult res = checkWallet();
    NS_ENSURE_SUCCESS(res, res);

    QString key = generateQueryWalletKey( aHostname, aActionURL, aHttpRealm, NS_ConvertUTF8toUTF16( "*" ) );

    QMap< QString, QMap< QString, QString > > entryMap;
    if( wallet->readMapList( key, entryMap ) != 0 )
        return NS_OK;
    PR_LOG( gKDEWalletLog, PR_LOG_DEBUG, ( "KDEWallet::FindLogins() Found %d maps", entryMap.count() ) );
    if( entryMap.count() == 0 )
        return NS_OK;
    nsILoginInfo **array = (nsILoginInfo**) nsMemory::Alloc(entryMap.count() * sizeof(nsILoginInfo*));
    NS_ENSURE_TRUE(array, NS_ERROR_OUT_OF_MEMORY);
    memset(array, 0, entryMap.count() * sizeof(nsILoginInfo*));

    QMapIterator< QString, QMap< QString, QString > > iterator(entryMap);
    int i = 0;
    while (iterator.hasNext()) {
        iterator.next();
        QMap< QString, QString > entry = iterator.value();
        nsCOMPtr<nsILoginInfo> loginInfo = do_CreateInstance(NS_LOGININFO_CONTRACTID);
        NS_ADDREF((nsILoginInfo*) loginInfo);
        if (!loginInfo)
            return NS_ERROR_FAILURE;
        nsAutoString temp;
        if( entry.contains( kHostnameAttr ) )
            loginInfo->SetHostname( QtString2NSString( entry.value( kHostnameAttr ) ) );
        if( entry.contains( kUsernameAttr ) )
            loginInfo->SetUsername(QtString2NSString( entry.value( kUsernameAttr ) ) );
        if( entry.contains( kUsernameFieldAttr ) )
            loginInfo->SetUsernameField(QtString2NSString( entry.value( kUsernameFieldAttr ) ) );
        if( entry.contains( kPasswordAttr ) )
            loginInfo->SetPassword(QtString2NSString( entry.value( kPasswordAttr ) ) );
        if( entry.contains( kPasswordFieldAttr ) )
            loginInfo->SetPasswordField(QtString2NSString( entry.value( kPasswordFieldAttr ) ) );
        if( entry.contains( kFormSubmitURLAttr ) )
            loginInfo->SetFormSubmitURL(QtString2NSString( entry.value( kFormSubmitURLAttr ) ) );
        if( entry.contains( kHttpRealmAttr ) )
            loginInfo->SetHttpRealm(QtString2NSString( entry.value( kHttpRealmAttr ) ) );
        if( entry.contains( kGuidAttr ) ) {
            nsCOMPtr<nsILoginMetaInfo> loginmeta( do_QueryInterface(loginInfo, &res) );
            NS_ENSURE_SUCCESS(res, res);
            nsAutoString aGUID ;
            res = loginmeta->SetGuid(QtString2NSString( entry.value( kGuidAttr ) ));
            NS_ENSURE_SUCCESS(res, res);
        }
        PR_LOG( gKDEWalletLog, PR_LOG_DEBUG, ( "KDEWallet::FindLogins() Found key: %s guid: %s", iterator.key().toUtf8().data(), entry.value( kGuidAttr ).toUtf8().data() ) );
        array[i] = loginInfo;
        i++;
    }
    *logins = array;
    *count = i;
    return NS_OK;
}
开发者ID:maciex,项目名称:mozilla-kwallet,代码行数:62,代码来源:KDEWallet.cpp

示例3: main


//.........这里部分代码省略.........
         * counting and freeing.
         */
        nsCOMPtr<nsIComponentManager> manager;
        rc = NS_GetComponentManager (getter_AddRefs (manager));
        if (NS_FAILED(rc))
        {
            printf("Error: could not get component manager! rc=%08X\n", rc);
            exit(-1);
        }

        nsCOMPtr<IVirtualBox> virtualBox;
        rc = manager->CreateInstanceByContractID(NS_VIRTUALBOX_CONTRACTID,
                                                 nsnull,
                                                 NS_GET_IID(IVirtualBox),
                                                 getter_AddRefs(virtualBox));
        if (NS_FAILED(rc))
        {
            printf("Error, could not instantiate object! rc=0x%x\n", rc);
            exit(-1);
        }

        nsCOMPtr<ISession> session;
        rc = manager->CreateInstance(CLSID_Session,
                                     nsnull,
                                     NS_GET_IID(ISession),
                                     getter_AddRefs(session));
        if (NS_FAILED(rc))
        {
            printf("Error: could not instantiate Session object! rc = %08X\n", rc);
            exit(-1);
        }

        // open session for this VM
        rc = virtualBox->OpenSession(session, NS_ConvertUTF8toUTF16(uuid).get());
        if (NS_FAILED(rc))
        {
            printf("Error: given machine not found!\n");
            exit(-1);
        }
        nsCOMPtr<IMachine> machine;
        session->GetMachine(getter_AddRefs(machine));
        if (!machine)
        {
            printf("Error: given machine not found!\n");
            exit(-1);
        }
        nsCOMPtr<IConsole> console;
        session->GetConsole(getter_AddRefs(console));
        if (!console)
        {
            printf("Error: cannot get console!\n");
            exit(-1);
        }

        nsCOMPtr<IDisplay> display;
        console->GetDisplay(getter_AddRefs(display));
        if (!display)
        {
            printf("Error: could not get display object!\n");
            exit(-1);
        }

        nsCOMPtr<IKeyboard> keyboard;
        nsCOMPtr<IMouse> mouse;
        VBoxDirectFB *frameBuffer = NULL;
开发者ID:VirtualMonitor,项目名称:VirtualMonitor,代码行数:66,代码来源:VBoxFB.cpp

示例4: ParseBody

  // The end of a body is marked by a CRLF followed by the boundary. So the
  // CRLF is part of the boundary and not the body, but any prior CRLFs are
  // part of the body. This will position the iterator at the beginning of the
  // boundary (after the CRLF).
  bool
  ParseBody(const nsACString& aBoundaryString,
            nsACString::const_iterator& aStart,
            nsACString::const_iterator& aEnd)
  {
    const char* beginning = aStart.get();

    // Find the boundary marking the end of the body.
    nsACString::const_iterator end(aEnd);
    if (!FindInReadable(aBoundaryString, aStart, end)) {
      return false;
    }

    // We found a boundary, strip the just prior CRLF, and consider
    // everything else the body section.
    if (aStart.get() - beginning < 2) {
      // Only the first entry can have a boundary right at the beginning. Even
      // an empty body will have a CRLF before the boundary. So this is
      // a failure.
      return false;
    }

    // Check that there is a CRLF right before the boundary.
    aStart.advance(-2);

    // Skip optional hyphens.
    if (*aStart == '-' && *(aStart.get()+1) == '-') {
      if (aStart.get() - beginning < 2) {
        return false;
      }

      aStart.advance(-2);
    }

    if (*aStart != nsCRT::CR || *(aStart.get()+1) != nsCRT::LF) {
      return false;
    }

    nsAutoCString body(beginning, aStart.get() - beginning);

    // Restore iterator to after the \r\n as we promised.
    // We do not need to handle the extra hyphens case since our boundary
    // parser in PushOverBoundary()
    aStart.advance(2);

    if (!mFormData) {
      mFormData = new nsFormData();
    }

    NS_ConvertUTF8toUTF16 name(mName);

    if (mFilename.IsVoid()) {
      mFormData->Append(name, NS_ConvertUTF8toUTF16(body));
    } else {
      // Unfortunately we've to copy the data first since all our strings are
      // going to free it. We also need fallible alloc, so we can't just use
      // ToNewCString().
      char* copy = static_cast<char*>(moz_xmalloc(body.Length()));
      if (!copy) {
        NS_WARNING("Failed to copy File entry body.");
        return false;
      }
      nsCString::const_iterator bodyIter, bodyEnd;
      body.BeginReading(bodyIter);
      body.EndReading(bodyEnd);
      char *p = copy;
      while (bodyIter != bodyEnd) {
        *p++ = *bodyIter++;
      }
      p = nullptr;

      nsRefPtr<Blob> file =
        File::CreateMemoryFile(mParentObject,
                               reinterpret_cast<void *>(copy), body.Length(),
                               NS_ConvertUTF8toUTF16(mFilename),
                               NS_ConvertUTF8toUTF16(mContentType), /* aLastModifiedDate */ 0);
      Optional<nsAString> dummy;
      mFormData->Append(name, *file, dummy);
    }

    return true;
  }
开发者ID:mak77,项目名称:gecko-dev,代码行数:86,代码来源:Fetch.cpp

示例5: ConvertString

 static void ConvertString(const std::string& aFrom, nsString& aOutTo) {
   aOutTo = NS_ConvertUTF8toUTF16(aFrom.c_str(), aFrom.size());
 }
开发者ID:MekliCZ,项目名称:positron,代码行数:3,代码来源:APZTestData.cpp

示例6: NS_ENSURE_ARG_POINTER

nsresult
nsAddbookProtocolHandler::BuildDirectoryXML(nsIAbDirectory *aDirectory, 
                                       nsString &aOutput)
{
  NS_ENSURE_ARG_POINTER(aDirectory);

  nsresult rv;    
  nsCOMPtr<nsISimpleEnumerator> cardsEnumerator;
  nsCOMPtr<nsIAbCard> card;

  aOutput.AppendLiteral("<?xml version=\"1.0\"?>\n"
                        "<?xml-stylesheet type=\"text/css\" href=\"chrome://messagebody/content/addressbook/print.css\"?>\n"
                        "<directory>\n");

  // Get Address Book string and set it as title of XML document
  nsCOMPtr<nsIStringBundle> bundle;
  nsCOMPtr<nsIStringBundleService> stringBundleService =
    mozilla::services::GetStringBundleService();
  if (stringBundleService) {
    rv = stringBundleService->CreateBundle("chrome://messenger/locale/addressbook/addressBook.properties", getter_AddRefs(bundle));
    if (NS_SUCCEEDED(rv)) {
      nsString addrBook;
      rv = bundle->GetStringFromName(NS_LITERAL_STRING("addressBook").get(), getter_Copies(addrBook));
      if (NS_SUCCEEDED(rv)) {
        aOutput.AppendLiteral("<title xmlns=\"http://www.w3.org/1999/xhtml\">");
        aOutput.Append(addrBook);
        aOutput.AppendLiteral("</title>\n");
      }
    }
  }

 // create a view and init it with the generated name sort order. Then, iterate
  // over the view, getting the card for each row, and printing them.
  nsString sortColumn;
  nsCOMPtr <nsIAbView> view = do_CreateInstance("@mozilla.org/addressbook/abview;1", &rv);
  
  view->SetView(aDirectory, nullptr, NS_LITERAL_STRING("GeneratedName"),
                NS_LITERAL_STRING("ascending"), sortColumn);

  int32_t numRows;
  nsCOMPtr <nsITreeView> treeView = do_QueryInterface(view, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  treeView->GetRowCount(&numRows);
  
  for (int32_t row = 0; row < numRows; row++)
  {
    
    nsCOMPtr <nsIAbCard> card;
    view->GetCardFromRow(row, getter_AddRefs(card));
    nsCString xmlSubstr;

    rv = card->TranslateTo(NS_LITERAL_CSTRING("xml"), xmlSubstr);
    NS_ENSURE_SUCCESS(rv,rv);

    aOutput.AppendLiteral("<separator/>");
    aOutput.Append(NS_ConvertUTF8toUTF16(xmlSubstr));
    aOutput.AppendLiteral("<separator/>");
  }

  aOutput.AppendLiteral("</directory>\n");

  return NS_OK;
}
开发者ID:klainfo,项目名称:releases-comm-central,代码行数:63,代码来源:nsAddbookProtocolHandler.cpp

示例7: DO_PR_DEBUG_LOG

/* void initPrintSettingsFromPrinter (in wstring aPrinterName, in nsIPrintSettings aPrintSettings); */
NS_IMETHODIMP nsPrinterEnumeratorGTK::InitPrintSettingsFromPrinter(const PRUnichar *aPrinterName, nsIPrintSettings *aPrintSettings)
{
  DO_PR_DEBUG_LOG(("nsPrinterEnumeratorGTK::InitPrintSettingsFromPrinter()"));
  nsresult rv;

  NS_ENSURE_ARG_POINTER(aPrinterName);
  NS_ENSURE_ARG_POINTER(aPrintSettings);
  
  NS_ENSURE_TRUE(*aPrinterName, NS_ERROR_FAILURE);
  NS_ENSURE_TRUE(aPrintSettings, NS_ERROR_FAILURE);

  nsCOMPtr<nsIPrefBranch> pPrefs = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
  if (NS_FAILED(rv))
    return rv;

  nsXPIDLCString fullPrinterName, /* Full name of printer incl. driver-specific prefix */ 
                 printerName;     /* "Stripped" name of printer */
  fullPrinterName.Assign(NS_ConvertUTF16toUTF8(aPrinterName));
  printerName.Assign(NS_ConvertUTF16toUTF8(aPrinterName));
  DO_PR_DEBUG_LOG(("printerName='%s'\n", printerName.get()));
  
  PrintMethod type = pmInvalid;
  rv = nsDeviceContextSpecGTK::GetPrintMethod(printerName, type);
  if (NS_FAILED(rv))
    return rv;

#ifdef USE_POSTSCRIPT
  /* "Demangle" postscript printer name */
  if (type == pmPostScript) {
    /* Strip the printing method name from the printer,
     * e.g. turn "PostScript/foobar" to "foobar" */
    PRInt32 slash = printerName.FindChar('/');
    if (kNotFound != slash)
      printerName.Cut(0, slash + 1);
  }
#endif /* USE_POSTSCRIPT */

#ifdef SET_PRINTER_FEATURES_VIA_PREFS
  /* Defaults to FALSE */
  pPrefs->SetBoolPref(nsPrintfCString(256, PRINTERFEATURES_PREF ".%s.has_special_printerfeatures", fullPrinterName.get()).get(), PR_FALSE);
#endif /* SET_PRINTER_FEATURES_VIA_PREFS */

  
  /* Set filename */
  nsXPIDLCString filename;
  if (NS_FAILED(CopyPrinterCharPref(pPrefs, nsnull, printerName, "filename", filename))) {
    const char *path;
  
    if (!(path = PR_GetEnv("PWD")))
      path = PR_GetEnv("HOME");
  
    if (path)
      filename = nsPrintfCString(PATH_MAX, "%s/mozilla.ps", path);
    else
      filename.AssignLiteral("mozilla.ps");
  }  
  DO_PR_DEBUG_LOG(("Setting default filename to '%s'\n", filename.get()));
  aPrintSettings->SetToFileName(NS_ConvertUTF8toUTF16(filename).get());

  aPrintSettings->SetIsInitializedFromPrinter(PR_TRUE);

#ifdef USE_POSTSCRIPT
  if (type == pmPostScript) {
    DO_PR_DEBUG_LOG(("InitPrintSettingsFromPrinter() for PostScript printer\n"));

#ifdef SET_PRINTER_FEATURES_VIA_PREFS
    nsPrinterFeatures printerFeatures(fullPrinterName);

    printerFeatures.SetSupportsPaperSizeChange(PR_TRUE);
    printerFeatures.SetSupportsOrientationChange(PR_TRUE);
    printerFeatures.SetSupportsPlexChange(PR_FALSE);
    printerFeatures.SetSupportsResolutionNameChange(PR_FALSE);
    printerFeatures.SetSupportsColorspaceChange(PR_FALSE);
#endif /* SET_PRINTER_FEATURES_VIA_PREFS */ 
      
#ifdef SET_PRINTER_FEATURES_VIA_PREFS
    printerFeatures.SetCanChangeOrientation(PR_TRUE);
#endif /* SET_PRINTER_FEATURES_VIA_PREFS */

    nsXPIDLCString orientation;
    if (NS_SUCCEEDED(CopyPrinterCharPref(pPrefs, "postscript", printerName, "orientation", orientation))) {
      if (orientation.LowerCaseEqualsLiteral("portrait")) {
        DO_PR_DEBUG_LOG(("setting default orientation to 'portrait'\n"));
        aPrintSettings->SetOrientation(nsIPrintSettings::kPortraitOrientation);
      }
      else if (orientation.LowerCaseEqualsLiteral("landscape")) {
        DO_PR_DEBUG_LOG(("setting default orientation to 'landscape'\n"));
        aPrintSettings->SetOrientation(nsIPrintSettings::kLandscapeOrientation);  
      }
      else {
        DO_PR_DEBUG_LOG(("Unknown default orientation '%s'\n", orientation.get()));
      }
    }

#ifdef SET_PRINTER_FEATURES_VIA_PREFS
    printerFeatures.SetOrientationRecord(0, "portrait");
    printerFeatures.SetOrientationRecord(1, "landscape");
    printerFeatures.SetNumOrientationRecords(2);
#endif /* SET_PRINTER_FEATURES_VIA_PREFS */
//.........这里部分代码省略.........
开发者ID:fortunto2,项目名称:celtx,代码行数:101,代码来源:nsDeviceContextSpecG.cpp

示例8: NS_ASSERTION

nsresult
PluginDocument::CreateSyntheticPluginDocument()
{
  NS_ASSERTION(!GetShell() || !GetShell()->DidInitialize(),
               "Creating synthetic plugin document content too late");

  // make our generic document
  nsresult rv = MediaDocument::CreateSyntheticDocument();
  NS_ENSURE_SUCCESS(rv, rv);
  // then attach our plugin

  Element* body = GetBodyElement();
  if (!body) {
    NS_WARNING("no body on plugin document!");
    return NS_ERROR_FAILURE;
  }

  // remove margins from body
  NS_NAMED_LITERAL_STRING(zero, "0");
  body->SetAttr(kNameSpaceID_None, nsGkAtoms::marginwidth, zero, false);
  body->SetAttr(kNameSpaceID_None, nsGkAtoms::marginheight, zero, false);


  // make plugin content
  nsCOMPtr<nsINodeInfo> nodeInfo;
  nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::embed, nullptr,
                                           kNameSpaceID_XHTML,
                                           nsIDOMNode::ELEMENT_NODE);
  NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
  rv = NS_NewHTMLElement(getter_AddRefs(mPluginContent), nodeInfo.forget(),
                         NOT_FROM_PARSER);
  NS_ENSURE_SUCCESS(rv, rv);

  // make it a named element
  mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::name,
                          NS_LITERAL_STRING("plugin"), false);

  // fill viewport and auto-resize
  NS_NAMED_LITERAL_STRING(percent100, "100%");
  mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::width, percent100,
                          false);
  mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::height, percent100,
                          false);

  // set URL
  nsAutoCString src;
  mDocumentURI->GetSpec(src);
  mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::src,
                          NS_ConvertUTF8toUTF16(src), false);

  // set mime type
  mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::type,
                          NS_ConvertUTF8toUTF16(mMimeType), false);

  // This will not start the load because nsObjectLoadingContent checks whether
  // its document is an nsIPluginDocument
  body->AppendChildTo(mPluginContent, false);

  return NS_OK;


}
开发者ID:AshishNamdev,项目名称:mozilla-central,代码行数:62,代码来源:PluginDocument.cpp

示例9: MSE_DEBUG

void
SourceBuffer::DispatchSimpleEvent(const char* aName)
{
  MSE_DEBUG("%p Dispatching event %s to SourceBuffer", this, aName);
  DispatchTrustedEvent(NS_ConvertUTF8toUTF16(aName));
}
开发者ID:elefant,项目名称:gecko-dev,代码行数:6,代码来源:SourceBuffer.cpp

示例10: NS_ASSERTION


//.........这里部分代码省略.........
  if (!listeners) {
    listeners = new StreamListeners;
    GetActiveWindows()->Put(windowID, listeners);
  }
  // Ensure there's a thread for gum to proxy to off main thread
  nsIThread *mediaThread = MediaManager::GetThread();

  // Create a disabled listener to act as a placeholder
  GetUserMediaCallbackMediaStreamListener* listener =
    new GetUserMediaCallbackMediaStreamListener(mediaThread, windowID);

  // No need for locking because we always do this in the main thread.
  listeners->AppendElement(listener);

  // Developer preference for turning off permission check.
  if (Preferences::GetBool("media.navigator.permission.disabled", false)) {
    aPrivileged = true;
  }

  /**
   * Pass runnables along to GetUserMediaRunnable so it can add the
   * MediaStreamListener to the runnable list. The last argument can
   * optionally be a MediaDevice object, which should provided if one was
   * selected by the user via the UI, or was provided by privileged code
   * via the device: attribute via nsIMediaStreamOptions.
   *
   * If a fake stream was requested, we force the use of the default backend.
   */
  if (fake) {
    // Fake stream from default backend.
    gUMRunnable = new GetUserMediaRunnable(
      audio, video, onSuccess.forget(), onError.forget(), windowID, listener,
      new MediaEngineDefault()
                                           );
  } else if (audiodevice || videodevice) {
    // Stream from provided device.
    gUMRunnable = new GetUserMediaRunnable(
      audio, video, picture, onSuccess.forget(), onError.forget(), windowID, listener,
      static_cast<MediaDevice*>(audiodevice.get()),
      static_cast<MediaDevice*>(videodevice.get())
                                           );
  } else {
    // Stream from default device from WebRTC backend.
    gUMRunnable = new GetUserMediaRunnable(
      audio, video, picture, onSuccess.forget(), onError.forget(), windowID, listener
                                           );
  }

#ifdef ANDROID
  if (picture) {
    // ShowFilePickerForMimeType() must run on the Main Thread! (on Android)
    NS_DispatchToMainThread(gUMRunnable);
  }
  // XXX No support for Audio or Video in Android yet
#else
  // XXX No full support for picture in Desktop yet (needs proper UI)
  if (aPrivileged || fake) {
    mMediaThread->Dispatch(gUMRunnable, NS_DISPATCH_NORMAL);
  } else {
    // Ask for user permission, and dispatch runnable (or not) when a response
    // is received via an observer notification. Each call is paired with its
    // runnable by a GUID.
    nsresult rv;
    nsCOMPtr<nsIUUIDGenerator> uuidgen =
      do_GetService("@mozilla.org/uuid-generator;1", &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    // Generate a call ID.
    nsID id;
    rv = uuidgen->GenerateUUIDInPlace(&id);
    NS_ENSURE_SUCCESS(rv, rv);

    char buffer[NSID_LENGTH];
    id.ToProvidedString(buffer);
    NS_ConvertUTF8toUTF16 callID(buffer);

    // Store the current callback.
    mActiveCallbacks.Put(callID, gUMRunnable);

    // Construct JSON structure with both the windowID and the callID.
    nsAutoString data;
    data.Append(NS_LITERAL_STRING("{\"windowID\":"));

    // Convert window ID to string.
    char windowBuffer[32];
    PR_snprintf(windowBuffer, sizeof(windowBuffer), "%llu",
                aWindow->GetOuterWindow()->WindowID());
    data.Append(NS_ConvertUTF8toUTF16(windowBuffer));

    data.Append(NS_LITERAL_STRING(", \"callID\":\""));
    data.Append(callID);
    data.Append(NS_LITERAL_STRING("\"}"));

    nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
    obs->NotifyObservers(aParams, "getUserMedia:request", data.get());
  }
#endif

  return NS_OK;
}
开发者ID:bjacob,项目名称:mozilla-central,代码行数:101,代码来源:MediaManager.cpp

示例11: lf

nsresult
nsOperaProfileMigrator::CopySmartKeywords(nsINavBookmarksService* aBMS, 
                                          nsIStringBundle* aBundle,
                                          PRInt64 aParentFolder)
{
  nsresult rv;

  nsCOMPtr<nsIFile> smartKeywords;
  mOperaProfile->Clone(getter_AddRefs(smartKeywords));
  smartKeywords->Append(NS_LITERAL_STRING("search.ini"));

  nsCOMPtr<nsILocalFile> lf(do_QueryInterface(smartKeywords));
  nsINIParser parser;
  if (!lf || NS_FAILED(parser.Init(lf)))
    return NS_OK;

  nsString sourceNameOpera;
  rv = aBundle->GetStringFromName(NS_LITERAL_STRING("sourceNameOpera").get(),
                                  getter_Copies(sourceNameOpera));
  NS_ENSURE_SUCCESS(rv, rv);

  const PRUnichar* sourceNameStrings[] = { sourceNameOpera.get() };
  nsString importedSearchUrlsTitle;
  rv = aBundle->FormatStringFromName(NS_LITERAL_STRING("importedSearchURLsFolder").get(),
                                     sourceNameStrings, 1, 
                                     getter_Copies(importedSearchUrlsTitle));
  NS_ENSURE_SUCCESS(rv, rv);

  PRInt64 keywordsFolder;
  rv = aBMS->CreateFolder(aParentFolder,
                          NS_ConvertUTF16toUTF8(importedSearchUrlsTitle),
                          nsINavBookmarksService::DEFAULT_INDEX,
                          &keywordsFolder);
  NS_ENSURE_SUCCESS(rv, rv);

  PRInt32 sectionIndex = 1;
  nsCAutoString name, url, keyword;
  do {
    nsCAutoString section("Search Engine ");
    section.AppendInt(sectionIndex++);

    rv = parser.GetString(section.get(), "Name", name);
    if (NS_FAILED(rv)) {
      // No more smart keywords found, stop parsing the file.
      break;
    }
    if (name.IsEmpty())
      continue;

    rv = parser.GetString(section.get(), "URL", url);
    if (NS_FAILED(rv) || url.IsEmpty())
      continue;

    rv = parser.GetString(section.get(), "Key", keyword);
    if (NS_FAILED(rv) || keyword.IsEmpty())
      continue;

    PRInt32 post;
    rv = GetInteger(parser, section.get(), "Is post", &post);
    if (NS_SUCCEEDED(rv) && post)
      continue;

    PRUint32 length = name.Length();
    PRInt32 index = 0;
    do {
      index = name.FindChar('&', index);
      if ((PRUint32)index >= length - 2)
        break;

      // Assume "&&" is an escaped ampersand in the search query title. 
      if (name.CharAt(index + 1) == '&') {
        name.Cut(index, 1);
        index += 2;
        continue;
      }

      name.Cut(index, 1);
    }
    while ((PRUint32)index < length);

    nsCOMPtr<nsIURI> uri;
    if (NS_FAILED(NS_NewURI(getter_AddRefs(uri), url.get())) || !uri)
      continue;

    nsCAutoString hostCStr;
    uri->GetHost(hostCStr);
    NS_ConvertASCIItoUTF16 host(hostCStr);

    const PRUnichar* descStrings[] = { NS_ConvertUTF8toUTF16(keyword).get(),
                                       host.get() };
    nsString keywordDesc;
    rv = aBundle->FormatStringFromName(NS_LITERAL_STRING("importedSearchUrlDesc").get(),
                                       descStrings, 2,
                                       getter_Copies(keywordDesc));
    NS_ENSURE_SUCCESS(rv, rv);

    PRInt64 newId;
    rv = aBMS->InsertBookmark(keywordsFolder, uri,
                              nsINavBookmarksService::DEFAULT_INDEX,
                              name, &newId);
//.........这里部分代码省略.........
开发者ID:Egyptghost1,项目名称:DOMinator,代码行数:101,代码来源:nsOperaProfileMigrator.cpp

示例12: GetScriptHandlingObject

NS_IMETHODIMP
nsXMLDocument::Load(const nsAString& aUrl, bool *aReturn)
{
  bool hasHadScriptObject = true;
  nsIScriptGlobalObject* scriptObject =
    GetScriptHandlingObject(hasHadScriptObject);
  NS_ENSURE_STATE(scriptObject || !hasHadScriptObject);

  ReportUseOfDeprecatedMethod(this, "UseOfDOM3LoadMethodWarning");

  NS_ENSURE_ARG_POINTER(aReturn);
  *aReturn = false;

  nsCOMPtr<nsIDocument> callingDoc =
    do_QueryInterface(nsContentUtils::GetDocumentFromContext());

  nsIURI *baseURI = mDocumentURI;
  nsAutoCString charset;

  if (callingDoc) {
    baseURI = callingDoc->GetDocBaseURI();
    charset = callingDoc->GetDocumentCharacterSet();
  }

  // Create a new URI
  nsCOMPtr<nsIURI> uri;
  nsresult rv = NS_NewURI(getter_AddRefs(uri), aUrl, charset.get(), baseURI);
  if (NS_FAILED(rv)) {
    return rv;
  }

  // Check to see whether the current document is allowed to load this URI.
  // It's important to use the current document's principal for this check so
  // that we don't end up in a case where code with elevated privileges is
  // calling us and changing the principal of this document.

  // Enforce same-origin even for chrome loaders to avoid someone accidentally
  // using a document that content has a reference to and turn that into a
  // chrome document.
  nsCOMPtr<nsIPrincipal> principal = NodePrincipal();
  if (!nsContentUtils::IsSystemPrincipal(principal)) {
    rv = principal->CheckMayLoad(uri, false, false);
    NS_ENSURE_SUCCESS(rv, rv);

    int16_t shouldLoad = nsIContentPolicy::ACCEPT;
    rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_XMLHTTPREQUEST,
                                   uri,
                                   principal,
                                   callingDoc ? callingDoc.get() :
                                     static_cast<nsIDocument*>(this),
                                   NS_LITERAL_CSTRING("application/xml"),
                                   nullptr,
                                   &shouldLoad,
                                   nsContentUtils::GetContentPolicy(),
                                   nsContentUtils::GetSecurityManager());
    NS_ENSURE_SUCCESS(rv, rv);
    if (NS_CP_REJECTED(shouldLoad)) {
      return NS_ERROR_CONTENT_BLOCKED;
    }
  } else {
    // We're called from chrome, check to make sure the URI we're
    // about to load is also chrome.

    bool isChrome = false;
    if (NS_FAILED(uri->SchemeIs("chrome", &isChrome)) || !isChrome) {
      nsAutoCString spec;
      if (mDocumentURI)
        mDocumentURI->GetSpec(spec);

      nsAutoString error;
      error.AssignLiteral("Cross site loading using document.load is no "
                          "longer supported. Use XMLHttpRequest instead.");
      nsCOMPtr<nsIScriptError> errorObject =
          do_CreateInstance(NS_SCRIPTERROR_CONTRACTID, &rv);
      NS_ENSURE_SUCCESS(rv, rv);

      rv = errorObject->InitWithWindowID(error,
                                         NS_ConvertUTF8toUTF16(spec),
                                         EmptyString(),
                                         0, 0, nsIScriptError::warningFlag,
                                         "DOM",
                                         callingDoc ?
                                           callingDoc->InnerWindowID() :
                                           this->InnerWindowID());

      NS_ENSURE_SUCCESS(rv, rv);

      nsCOMPtr<nsIConsoleService> consoleService =
        do_GetService(NS_CONSOLESERVICE_CONTRACTID);
      if (consoleService) {
        consoleService->LogMessage(errorObject);
      }

      return NS_ERROR_DOM_SECURITY_ERR;
    }
  }

  // Partial Reset, need to restore principal for security reasons and
  // event listener manager so that load listeners etc. will
  // remain. This should be done before the security check is done to
//.........这里部分代码省略.........
开发者ID:Web5design,项目名称:mozilla-central,代码行数:101,代码来源:nsXMLDocument.cpp

示例13: UnpackPDU

nsresult
UnpackPDU(BluetoothDaemonPDU& aPDU, BluetoothProperty& aOut)
{
  nsresult rv = UnpackPDU(aPDU, aOut.mType);
  if (NS_FAILED(rv)) {
    return rv;
  }
  uint16_t len;
  rv = UnpackPDU(aPDU, len);
  if (NS_FAILED(rv)) {
    return rv;
  }

  switch (aOut.mType) {
    case PROPERTY_BDNAME:
      /* fall through */
    case PROPERTY_REMOTE_FRIENDLY_NAME: {
        const uint8_t* data = aPDU.Consume(len);
        if (NS_WARN_IF(!data)) {
          return NS_ERROR_ILLEGAL_VALUE;
        }
        // We construct an nsCString here because the string
        // returned from the PDU is not 0-terminated.
        aOut.mString = NS_ConvertUTF8toUTF16(
          nsCString(reinterpret_cast<const char*>(data), len));
      }
      break;
    case PROPERTY_BDADDR:
      rv = UnpackPDU<BluetoothAddress>(
        aPDU, UnpackConversion<BluetoothAddress, nsAString>(aOut.mString));
      break;
    case PROPERTY_UUIDS: {
        size_t numUuids = len / MAX_UUID_SIZE;
        aOut.mUuidArray.SetLength(numUuids);
        rv = UnpackPDU(aPDU, aOut.mUuidArray);
      }
      break;
    case PROPERTY_CLASS_OF_DEVICE:
      /* fall through */
    case PROPERTY_ADAPTER_DISCOVERY_TIMEOUT:
      rv = UnpackPDU(aPDU, aOut.mUint32);
      break;
    case PROPERTY_TYPE_OF_DEVICE:
      rv = UnpackPDU(aPDU, aOut.mTypeOfDevice);
      break;
    case PROPERTY_SERVICE_RECORD:
      rv = UnpackPDU(aPDU, aOut.mServiceRecord);
      break;
    case PROPERTY_ADAPTER_SCAN_MODE:
      rv = UnpackPDU(aPDU, aOut.mScanMode);
      break;
    case PROPERTY_ADAPTER_BONDED_DEVICES: {
        /* unpack addresses */
        size_t numAddresses = len / BLUETOOTH_ADDRESS_BYTES;
        nsAutoArrayPtr<BluetoothAddress> addresses;
        UnpackArray<BluetoothAddress> addressArray(addresses, numAddresses);
        rv = UnpackPDU(aPDU, addressArray);
        if (NS_FAILED(rv)) {
          return rv;
        }
        /* convert addresses to strings */
        aOut.mStringArray.SetLength(numAddresses);
        ConvertArray<BluetoothAddress> convertArray(addressArray.mData,
                                                    addressArray.mLength);
        rv = Convert(convertArray, aOut.mStringArray);
      }
      break;
    case PROPERTY_REMOTE_RSSI: {
        int8_t rssi;
        rv = UnpackPDU(aPDU, rssi);
        aOut.mInt32 = rssi;
      }
      break;
    case PROPERTY_REMOTE_VERSION_INFO:
      rv = UnpackPDU(aPDU, aOut.mRemoteInfo);
      break;
    case PROPERTY_REMOTE_DEVICE_TIMESTAMP:
      /* nothing to do */
      break;
    default:
      break;
  }
  return rv;
}
开发者ID:stormandsun,项目名称:firefox,代码行数:84,代码来源:BluetoothDaemonHelpers.cpp

示例14: net_GetFileFromURLSpec

nsresult
net_GetFileFromURLSpec(const nsACString &aURL, nsIFile **result)
{
    nsresult rv;

    nsCOMPtr<nsILocalFile> localFile(
            do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv));
    if (NS_FAILED(rv)) {
        NS_ERROR("Only nsILocalFile supported right now");
        return rv;
    }

    localFile->SetFollowLinks(PR_TRUE);

    const nsACString *specPtr;

    nsCAutoString buf;
    if (net_NormalizeFileURL(aURL, buf))
        specPtr = &buf;
    else
        specPtr = &aURL;
    
    nsCAutoString directory, fileBaseName, fileExtension;
    
    rv = net_ParseFileURL(*specPtr, directory, fileBaseName, fileExtension);
    if (NS_FAILED(rv)) return rv;

    nsCAutoString path;

    if (!directory.IsEmpty()) {
        NS_EscapeURL(directory, esc_Directory|esc_AlwaysCopy, path);
        if (path.Length() > 2 && path.CharAt(2) == '|')
            path.SetCharAt(':', 2);
        path.ReplaceChar('/', '\\');
    }    
    if (!fileBaseName.IsEmpty())
        NS_EscapeURL(fileBaseName, esc_FileBaseName|esc_AlwaysCopy, path);
    if (!fileExtension.IsEmpty()) {
        path += '.';
        NS_EscapeURL(fileExtension, esc_FileExtension|esc_AlwaysCopy, path);
    }
    
    NS_UnescapeURL(path);
    if (path.Length() != strlen(path.get()))
        return NS_ERROR_FILE_INVALID_PATH;

    // remove leading '\'
    if (path.CharAt(0) == '\\')
        path.Cut(0, 1);

    if (IsUTF8(path))
        rv = localFile->InitWithPath(NS_ConvertUTF8toUTF16(path));
        // XXX In rare cases, a valid UTF-8 string can be valid as a native 
        // encoding (e.g. 0xC5 0x83 is valid both as UTF-8 and Windows-125x).
        // However, the chance is very low that a meaningful word in a legacy
        // encoding is valid as UTF-8.
    else 
        // if path is not in UTF-8, assume it is encoded in the native charset
        rv = localFile->InitWithNativePath(path);

    if (NS_FAILED(rv)) return rv;

    NS_ADDREF(*result = localFile);
    return NS_OK;
}
开发者ID:binoc-software,项目名称:mozilla-cvs,代码行数:65,代码来源:nsURLHelperWin.cpp

示例15: main

// General note about return values:
// return 1 for a setup or xpcom type failure, return 2 for a real test failure
int main(int argc, char** argv)
{

  ScopedXPCOM xpcom("TestMsgStripRE.cpp");
  if (xpcom.failed())
    return 1;

  nsresult rv;
  nsCOMPtr<nsIPrefBranch> prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID,
                                     &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  // create an nsISupportsString and stuff our literal into it   
  nsCOMPtr<nsISupportsString> rePrefixes = 
    do_CreateInstance("@mozilla.org/supports-string;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  // portable C++ expression of "SV,ÆØÅ"
  static const unsigned char utf8Prefixes[] =
    {'S', 'V', ',', 0303, 0206, 0303, 0230, 0303, 0205, '\0'};

  rv = rePrefixes->SetData(NS_ConvertUTF8toUTF16(utf8Prefixes));
  NS_ENSURE_SUCCESS(rv, rv);

  // set localizedRe pref
  rv = prefBranch->SetComplexValue("mailnews.localizedRe", 
                                   NS_GET_IID(nsISupportsString), rePrefixes);
  NS_ENSURE_SUCCESS(rv, rv);

  // run our tests 
  struct testInfo testInfoStructs[] = {
    {"SV: =?ISO-8859-1?Q?=C6blegr=F8d?=", "=?ISO-8859-1?Q?=C6blegr=F8d?=",
     PR_TRUE},
    {"=?ISO-8859-1?Q?SV=3A=C6blegr=F8d?=", "=?ISO-8859-1?Q?=C6blegr=F8d?=",
     PR_TRUE},

     // Note that in the next two tests, the only ISO-8859-1 chars are in the
     // localizedRe piece, so once they've been stripped, the re-encoding process 
     // simply writes out ASCII rather than an ISO-8859-1 encoded string with
     // no actual ISO-8859-1 special characters, which seems reasonable.
    {"=?ISO-8859-1?Q?=C6=D8=C5=3A_Foo_bar?=", "Foo bar", PR_TRUE},
    {"=?ISO-8859-1?Q?=C6=D8=C5=3AFoo_bar?=", "Foo bar", PR_TRUE}
  };

  bool allTestsPassed = true;
  int result;
  for (unsigned int i = 0; i < NS_ARRAY_LENGTH(testInfoStructs); i++) {
    result = testStripRe(testInfoStructs[i].encodedInput,
                         testInfoStructs[i].expectedOutput,
                         testInfoStructs[i].expectedDidModify);
    if (result)
    {
      fail("%s, i=%d | result=%d\n", __FILE__, i, result);
      allTestsPassed = false;
    }
  }

  if (allTestsPassed) {
    passed("all tests passed\n");
  }
  
  return allTestsPassed ? 0 : 2;
}
开发者ID:mikeconley,项目名称:comm-central,代码行数:65,代码来源:TestMsgStripRE.cpp


注:本文中的NS_ConvertUTF8toUTF16函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。