本文整理汇总了C++中do_CreateInstance函数的典型用法代码示例。如果您正苦于以下问题:C++ do_CreateInstance函数的具体用法?C++ do_CreateInstance怎么用?C++ do_CreateInstance使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了do_CreateInstance函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: do_CreateInstance
already_AddRefed<nsITransferable>
DataTransfer::GetTransferable(uint32_t aIndex, nsILoadContext* aLoadContext)
{
if (aIndex >= mItems.Length()) {
return nullptr;
}
nsTArray<TransferItem>& item = mItems[aIndex];
uint32_t count = item.Length();
if (!count) {
return nullptr;
}
nsCOMPtr<nsITransferable> transferable =
do_CreateInstance("@mozilla.org/widget/transferable;1");
if (!transferable) {
return nullptr;
}
transferable->Init(aLoadContext);
nsCOMPtr<nsIStorageStream> storageStream;
nsCOMPtr<nsIBinaryOutputStream> stream;
bool added = false;
bool handlingCustomFormats = true;
uint32_t totalCustomLength = 0;
const char* knownFormats[] = {
kTextMime, kHTMLMime, kNativeHTMLMime, kRTFMime,
kURLMime, kURLDataMime, kURLDescriptionMime, kURLPrivateMime,
kPNGImageMime, kJPEGImageMime, kGIFImageMime, kNativeImageMime,
kFileMime, kFilePromiseMime, kFilePromiseURLMime,
kFilePromiseDestFilename, kFilePromiseDirectoryMime,
kMozTextInternal, kHTMLContext, kHTMLInfo };
/*
* Two passes are made here to iterate over all of the types. First, look for
* any types that are not in the list of known types. For this pass,
* handlingCustomFormats will be true. Data that corresponds to unknown types
* will be pulled out and inserted into a single type (kCustomTypesMime) by
* writing the data into a stream.
*
* The second pass will iterate over the formats looking for known types.
* These are added as is. The unknown types are all then inserted as a single
* type (kCustomTypesMime) in the same position of the first custom type. This
* model is used to maintain the format order as best as possible.
*
* The format of the kCustomTypesMime type is one or more of the following
* stored sequentially:
* <32-bit> type (only none or string is supported)
* <32-bit> length of format
* <wide string> format
* <32-bit> length of data
* <wide string> data
* A type of eCustomClipboardTypeId_None ends the list, without any following
* data.
*/
do {
for (uint32_t f = 0; f < count; f++) {
const TransferItem& formatitem = item[f];
if (!formatitem.mData) { // skip empty items
continue;
}
// If the data is of one of the well-known formats, use it directly.
bool isCustomFormat = true;
for (uint32_t f = 0; f < ArrayLength(knownFormats); f++) {
if (formatitem.mFormat.EqualsASCII(knownFormats[f])) {
isCustomFormat = false;
break;
}
}
uint32_t lengthInBytes;
nsCOMPtr<nsISupports> convertedData;
if (handlingCustomFormats) {
if (!ConvertFromVariant(formatitem.mData, getter_AddRefs(convertedData),
&lengthInBytes)) {
continue;
}
// When handling custom types, add the data to the stream if this is a
// custom type.
if (isCustomFormat) {
// If it isn't a string, just ignore it. The dataTransfer is cached in
// the drag sesion during drag-and-drop, so non-strings will be
// available when dragging locally.
nsCOMPtr<nsISupportsString> str(do_QueryInterface(convertedData));
if (str) {
nsAutoString data;
str->GetData(data);
if (!stream) {
// Create a storage stream to write to.
NS_NewStorageStream(1024, UINT32_MAX, getter_AddRefs(storageStream));
nsCOMPtr<nsIOutputStream> outputStream;
storageStream->GetOutputStream(0, getter_AddRefs(outputStream));
//.........这里部分代码省略.........
示例2: do_GetInterface
NS_IMETHODIMP
nsNSSDialogs::ChooseCertificate(nsIInterfaceRequestor *ctx, const char16_t *cn, const char16_t *organization, const char16_t *issuer, const char16_t **certNickList, const char16_t **certDetailsList, uint32_t count, int32_t *selectedIndex, bool *canceled)
{
nsresult rv;
uint32_t i;
*canceled = false;
// Get the parent window for the dialog
nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(ctx);
nsCOMPtr<nsIDialogParamBlock> block =
do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);
if (!block) return NS_ERROR_FAILURE;
block->SetNumberStrings(4+count*2);
rv = block->SetString(0, cn);
if (NS_FAILED(rv)) return rv;
rv = block->SetString(1, organization);
if (NS_FAILED(rv)) return rv;
rv = block->SetString(2, issuer);
if (NS_FAILED(rv)) return rv;
for (i = 0; i < count; i++) {
rv = block->SetString(i+3, certNickList[i]);
if (NS_FAILED(rv)) return rv;
}
for (i = 0; i < count; i++) {
rv = block->SetString(i+count+3, certDetailsList[i]);
if (NS_FAILED(rv)) return rv;
}
rv = block->SetInt(0, count);
if (NS_FAILED(rv)) return rv;
rv = nsNSSDialogHelper::openDialog(nullptr,
"chrome://pippki/content/clientauthask.xul",
block);
if (NS_FAILED(rv)) return rv;
int32_t status;
rv = block->GetInt(0, &status);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIClientAuthUserDecision> extraResult = do_QueryInterface(ctx);
if (extraResult) {
int32_t rememberSelection;
rv = block->GetInt(2, &rememberSelection);
if (NS_SUCCEEDED(rv)) {
extraResult->SetRememberClientAuthCertificate(rememberSelection!=0);
}
}
*canceled = (status == 0)?true:false;
if (!*canceled) {
// retrieve the nickname
rv = block->GetInt(1, selectedIndex);
}
return rv;
}
示例3: PrincipalInfoToPrincipal
already_AddRefed<nsIPrincipal>
PrincipalInfoToPrincipal(const PrincipalInfo& aPrincipalInfo,
nsresult* aOptionalResult)
{
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aPrincipalInfo.type() != PrincipalInfo::T__None);
nsresult stackResult;
nsresult& rv = aOptionalResult ? *aOptionalResult : stackResult;
nsCOMPtr<nsIScriptSecurityManager> secMan =
do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv);
if (NS_WARN_IF(NS_FAILED(rv))) {
return nullptr;
}
nsCOMPtr<nsIPrincipal> principal;
switch (aPrincipalInfo.type()) {
case PrincipalInfo::TSystemPrincipalInfo: {
rv = secMan->GetSystemPrincipal(getter_AddRefs(principal));
if (NS_WARN_IF(NS_FAILED(rv))) {
return nullptr;
}
return principal.forget();
}
case PrincipalInfo::TNullPrincipalInfo: {
principal = do_CreateInstance(NS_NULLPRINCIPAL_CONTRACTID, &rv);
if (NS_WARN_IF(NS_FAILED(rv))) {
return nullptr;
}
return principal.forget();
}
case PrincipalInfo::TContentPrincipalInfo: {
const ContentPrincipalInfo& info =
aPrincipalInfo.get_ContentPrincipalInfo();
nsCOMPtr<nsIURI> uri;
rv = NS_NewURI(getter_AddRefs(uri), info.spec());
if (NS_WARN_IF(NS_FAILED(rv))) {
return nullptr;
}
if (info.appId() == nsIScriptSecurityManager::UNKNOWN_APP_ID) {
rv = secMan->GetSimpleCodebasePrincipal(uri, getter_AddRefs(principal));
} else {
rv = secMan->GetAppCodebasePrincipal(uri,
info.appId(),
info.isInBrowserElement(),
getter_AddRefs(principal));
}
if (NS_WARN_IF(NS_FAILED(rv))) {
return nullptr;
}
return principal.forget();
}
case PrincipalInfo::TExpandedPrincipalInfo: {
const ExpandedPrincipalInfo& info = aPrincipalInfo.get_ExpandedPrincipalInfo();
nsTArray< nsCOMPtr<nsIPrincipal> > whitelist;
nsCOMPtr<nsIPrincipal> wlPrincipal;
for (uint32_t i = 0; i < info.whitelist().Length(); i++) {
wlPrincipal = PrincipalInfoToPrincipal(info.whitelist()[i], &rv);
if (NS_WARN_IF(NS_FAILED(rv))) {
return nullptr;
}
// append that principal to the whitelist
whitelist.AppendElement(wlPrincipal);
}
nsRefPtr<nsExpandedPrincipal> expandedPrincipal = new nsExpandedPrincipal(whitelist);
if (!expandedPrincipal) {
NS_WARNING("could not instantiate expanded principal");
return nullptr;
}
principal = expandedPrincipal;
return principal.forget();
}
default:
MOZ_CRASH("Unknown PrincipalInfo type!");
}
MOZ_CRASH("Should never get here!");
}
示例4: NS_ENSURE_ARG_POINTER
NS_IMETHODIMP nsAutoSyncState::GetNextGroupOfMessages(uint32_t aSuggestedGroupSizeLimit,
uint32_t *aActualGroupSize,
nsIMutableArray **aMessagesList)
{
NS_ENSURE_ARG_POINTER(aMessagesList);
NS_ENSURE_ARG_POINTER(aActualGroupSize);
*aActualGroupSize = 0;
nsresult rv;
nsCOMPtr <nsIMsgFolder> folder = do_QueryReferent(mOwnerFolder, &rv);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIMsgDatabase> database;
folder->GetMsgDatabase(getter_AddRefs(database));
nsCOMPtr<nsIMutableArray> group = do_CreateInstance(NS_ARRAY_CONTRACTID);
if (database)
{
if (!mDownloadQ.IsEmpty())
{
// sort the download queue if new items are added since the last time
if (mIsDownloadQChanged)
{
// we want to sort only pending messages. mOffset is
// the position of the first pending message in the download queue
rv = (mOffset > 0)
? SortSubQueueBasedOnStrategy(mDownloadQ, mOffset)
: SortQueueBasedOnStrategy(mDownloadQ);
if (NS_SUCCEEDED(rv))
mIsDownloadQChanged = false;
}
nsCOMPtr<nsIAutoSyncManager> autoSyncMgr = do_GetService(NS_AUTOSYNCMANAGER_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
uint32_t msgCount = mDownloadQ.Length();
uint32_t idx = mOffset;
nsCOMPtr<nsIAutoSyncMsgStrategy> msgStrategy;
autoSyncMgr->GetMsgStrategy(getter_AddRefs(msgStrategy));
for (; idx < msgCount; idx++)
{
bool containsKey = false;
database->ContainsKey(mDownloadQ[idx], &containsKey);
if (!containsKey)
{
mDownloadQ.RemoveElementAt(idx--);
msgCount--;
continue;
}
nsCOMPtr<nsIMsgDBHdr> qhdr;
database->GetMsgHdrForKey(mDownloadQ[idx], getter_AddRefs(qhdr));
if(!qhdr)
continue; //maybe deleted, skip it!
// ensure that we don't have this message body offline already,
// possible if the user explicitly selects this message prior
// to auto-sync kicks in
uint32_t msgFlags = 0;
qhdr->GetFlags(&msgFlags);
if (msgFlags & nsMsgMessageFlags::Offline)
continue;
// this check point allows msg strategy function
// to do last minute decisions based on the current
// state of TB such as the size of the message store etc.
if (msgStrategy)
{
bool excluded = false;
if (NS_SUCCEEDED(msgStrategy->IsExcluded(folder, qhdr, &excluded)) && excluded)
continue;
}
uint32_t msgSize;
qhdr->GetMessageSize(&msgSize);
// ignore 0 byte messages; the imap parser asserts when we try
// to download them, and there's no point anyway.
if (!msgSize)
continue;
if (!*aActualGroupSize && msgSize >= aSuggestedGroupSizeLimit)
{
*aActualGroupSize = msgSize;
group->AppendElement(qhdr, false);
idx++;
break;
}
else if ((*aActualGroupSize) + msgSize > aSuggestedGroupSizeLimit)
break;
else
{
group->AppendElement(qhdr, false);
*aActualGroupSize += msgSize;
}
}// endfor
mLastOffset = mOffset;
//.........这里部分代码省略.........
示例5: NS_ENSURE_ARG_POINTER
NS_IMETHODIMP nsDeviceContextSpecQt::GetSurfaceForPrinter(
gfxASurface** aSurface)
{
NS_ENSURE_ARG_POINTER(aSurface);
*aSurface = nullptr;
double width, height;
mPrintSettings->GetEffectivePageSize(&width, &height);
// If we're in landscape mode, we'll be rotating the output --
// need to swap width & height.
int32_t orientation;
mPrintSettings->GetOrientation(&orientation);
if (nsIPrintSettings::kLandscapeOrientation == orientation) {
double tmp = width;
width = height;
height = tmp;
}
// convert twips to points
width /= TWIPS_PER_POINT_FLOAT;
height /= TWIPS_PER_POINT_FLOAT;
DO_PR_DEBUG_LOG(("\"%s\", %f, %f\n", mPath, width, height));
QTemporaryFile file;
if(!file.open()) {
return NS_ERROR_GFX_PRINTER_COULD_NOT_OPEN_FILE;
}
file.setAutoRemove(false);
nsresult rv = NS_NewNativeLocalFile(
nsDependentCString(file.fileName().toUtf8().constData()),
false,
getter_AddRefs(mSpoolFile));
if (NS_FAILED(rv)) {
file.remove();
return NS_ERROR_GFX_PRINTER_COULD_NOT_OPEN_FILE;
}
mSpoolName = file.fileName().toUtf8().constData();
mSpoolFile->SetPermissions(0600);
nsCOMPtr<nsIFileOutputStream> stream =
do_CreateInstance("@mozilla.org/network/file-output-stream;1");
rv = stream->Init(mSpoolFile, -1, -1, 0);
if (NS_FAILED(rv))
return rv;
int16_t format;
mPrintSettings->GetOutputFormat(&format);
nsRefPtr<gfxASurface> surface;
gfxSize surfaceSize(width, height);
if (format == nsIPrintSettings::kOutputFormatNative) {
if (mIsPPreview) {
// There is nothing to detect on Print Preview, use PS.
// TODO: implement for Qt?
//format = nsIPrintSettings::kOutputFormatPS;
return NS_ERROR_NOT_IMPLEMENTED;
}
format = nsIPrintSettings::kOutputFormatPDF;
}
if (format == nsIPrintSettings::kOutputFormatPDF) {
surface = new gfxPDFSurface(stream, surfaceSize);
} else {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_ABORT_IF_FALSE(surface, "valid address expected");
surface.swap(*aSurface);
return NS_OK;
}
示例6: do_CreateInstance
NS_IMETHODIMP
DOMStorageObserver::Observe(nsISupports* aSubject,
const char* aTopic,
const char16_t* aData)
{
nsresult rv;
// Start the thread that opens the database.
if (!strcmp(aTopic, kStartupTopic)) {
nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
obs->RemoveObserver(this, kStartupTopic);
mDBThreadStartDelayTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
if (!mDBThreadStartDelayTimer) {
return NS_ERROR_UNEXPECTED;
}
mDBThreadStartDelayTimer->Init(this, nsITimer::TYPE_ONE_SHOT, kStartupDelay);
return NS_OK;
}
// Timer callback used to start the database a short timer after startup
if (!strcmp(aTopic, NS_TIMER_CALLBACK_TOPIC)) {
nsCOMPtr<nsITimer> timer = do_QueryInterface(aSubject);
if (!timer) {
return NS_ERROR_UNEXPECTED;
}
if (timer == mDBThreadStartDelayTimer) {
mDBThreadStartDelayTimer = nullptr;
DOMStorageDBBridge* db = DOMStorageCache::StartDatabase();
NS_ENSURE_TRUE(db, NS_ERROR_FAILURE);
}
return NS_OK;
}
// Clear everything, caches + database
if (!strcmp(aTopic, "cookie-changed")) {
if (!NS_LITERAL_STRING("cleared").Equals(aData)) {
return NS_OK;
}
DOMStorageDBBridge* db = DOMStorageCache::StartDatabase();
NS_ENSURE_TRUE(db, NS_ERROR_FAILURE);
db->AsyncClearAll();
Notify("cookie-cleared");
return NS_OK;
}
// Clear from caches everything that has been stored
// while in session-only mode
if (!strcmp(aTopic, "perm-changed")) {
// Check for cookie permission change
nsCOMPtr<nsIPermission> perm(do_QueryInterface(aSubject));
if (!perm) {
return NS_OK;
}
nsAutoCString type;
perm->GetType(type);
if (type != NS_LITERAL_CSTRING("cookie")) {
return NS_OK;
}
uint32_t cap = 0;
perm->GetCapability(&cap);
if (!(cap & nsICookiePermission::ACCESS_SESSION) ||
!NS_LITERAL_STRING("deleted").Equals(nsDependentString(aData))) {
return NS_OK;
}
nsCOMPtr<nsIPrincipal> principal;
perm->GetPrincipal(getter_AddRefs(principal));
if (!principal) {
return NS_OK;
}
nsAutoCString originSuffix;
BasePrincipal::Cast(principal)->OriginAttributesRef().CreateSuffix(originSuffix);
nsCOMPtr<nsIURI> origin;
principal->GetURI(getter_AddRefs(origin));
if (!origin) {
return NS_OK;
}
nsAutoCString host;
origin->GetHost(host);
if (host.IsEmpty()) {
return NS_OK;
}
nsAutoCString originScope;
rv = CreateReversedDomain(host, originScope);
//.........这里部分代码省略.........
示例7: presShell
NS_IMETHODIMP
nsTypeAheadFind::Find(const nsAString& aSearchString, bool aLinksOnly,
PRUint16* aResult)
{
*aResult = FIND_NOTFOUND;
nsCOMPtr<nsIPresShell> presShell (GetPresShell());
if (!presShell) {
nsCOMPtr<nsIDocShell> ds (do_QueryReferent(mDocShell));
NS_ENSURE_TRUE(ds, NS_ERROR_FAILURE);
ds->GetPresShell(getter_AddRefs(presShell));
mPresShell = do_GetWeakReference(presShell);
}
nsCOMPtr<nsISelection> selection;
nsCOMPtr<nsISelectionController> selectionController =
do_QueryReferent(mSelectionController);
if (!selectionController) {
GetSelection(presShell, getter_AddRefs(selectionController),
getter_AddRefs(selection)); // cache for reuse
mSelectionController = do_GetWeakReference(selectionController);
} else {
selectionController->GetSelection(
nsISelectionController::SELECTION_NORMAL, getter_AddRefs(selection));
}
if (selection)
selection->CollapseToStart();
if (aSearchString.IsEmpty()) {
mTypeAheadBuffer.Truncate();
// These will be initialized to their true values after the first character
// is typed
mStartFindRange = nsnull;
mSelectionController = nsnull;
*aResult = FIND_FOUND;
return NS_OK;
}
bool atEnd = false;
if (mTypeAheadBuffer.Length()) {
const nsAString& oldStr = Substring(mTypeAheadBuffer, 0, mTypeAheadBuffer.Length());
const nsAString& newStr = Substring(aSearchString, 0, mTypeAheadBuffer.Length());
if (oldStr.Equals(newStr))
atEnd = true;
const nsAString& newStr2 = Substring(aSearchString, 0, aSearchString.Length());
const nsAString& oldStr2 = Substring(mTypeAheadBuffer, 0, aSearchString.Length());
if (oldStr2.Equals(newStr2))
atEnd = true;
if (!atEnd)
mStartFindRange = nsnull;
}
if (!mIsSoundInitialized && !mNotFoundSoundURL.IsEmpty()) {
// This makes sure system sound library is loaded so that
// there's no lag before the first sound is played
// by waiting for the first keystroke, we still get the startup time benefits.
mIsSoundInitialized = true;
mSoundInterface = do_CreateInstance("@mozilla.org/sound;1");
if (mSoundInterface && !mNotFoundSoundURL.Equals(NS_LITERAL_CSTRING("beep"))) {
mSoundInterface->Init();
}
}
#ifdef XP_WIN
// After each keystroke, ensure sound object is destroyed, to free up memory
// allocated for error sound, otherwise Windows' nsISound impl
// holds onto the last played sound, using up memory.
mSoundInterface = nsnull;
#endif
PRInt32 bufferLength = mTypeAheadBuffer.Length();
mTypeAheadBuffer = aSearchString;
bool isFirstVisiblePreferred = false;
// --------- Initialize find if 1st char ----------
if (bufferLength == 0) {
// If you can see the selection (not collapsed or thru caret browsing),
// or if already focused on a page element, start there.
// Otherwise we're going to start at the first visible element
bool isSelectionCollapsed = true;
if (selection)
selection->GetIsCollapsed(&isSelectionCollapsed);
// If true, we will scan from top left of visible area
// If false, we will scan from start of selection
isFirstVisiblePreferred = !atEnd && !mCaretBrowsingOn && isSelectionCollapsed;
if (isFirstVisiblePreferred) {
// Get the focused content. If there is a focused node, ensure the
// selection is at that point. Otherwise, we will just want to start
// from the caret position or the beginning of the document.
nsPresContext* presContext = presShell->GetPresContext();
NS_ENSURE_TRUE(presContext, NS_OK);
//.........这里部分代码省略.........
示例8: handlerKeyName
// The "real" name of a given helper app (as specified by the path to the
// executable file held in various registry keys) is stored n the VERSIONINFO
// block in the file's resources. We need to find the path to the executable
// and then retrieve the "FileDescription" field value from the file.
nsresult
nsOSHelperAppService::GetDefaultAppInfo(const nsAString& aAppInfo,
nsAString& aDefaultDescription,
nsIFile** aDefaultApplication)
{
nsAutoString handlerCommand;
// If all else fails, use the file type key name, which will be
// something like "pngfile" for .pngs, "WMVFile" for .wmvs, etc.
aDefaultDescription = aAppInfo;
*aDefaultApplication = nullptr;
if (aAppInfo.IsEmpty())
return NS_ERROR_FAILURE;
// aAppInfo may be a file, file path, program id, or
// Applications reference -
// c:\dir\app.exe
// Applications\appfile.exe/dll (shell\open...)
// ProgID.progid (shell\open...)
nsAutoString handlerKeyName(aAppInfo);
nsCOMPtr<nsIWindowsRegKey> chkKey =
do_CreateInstance("@mozilla.org/windows-registry-key;1");
if (!chkKey)
return NS_ERROR_FAILURE;
nsresult rv = chkKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT,
handlerKeyName,
nsIWindowsRegKey::ACCESS_QUERY_VALUE);
if (NS_FAILED(rv)) {
// It's a file system path to a handler
handlerCommand.Assign(aAppInfo);
}
else {
handlerKeyName.AppendLiteral("\\shell\\open\\command");
nsCOMPtr<nsIWindowsRegKey> regKey =
do_CreateInstance("@mozilla.org/windows-registry-key;1");
if (!regKey)
return NS_ERROR_FAILURE;
nsresult rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT,
handlerKeyName,
nsIWindowsRegKey::ACCESS_QUERY_VALUE);
if (NS_FAILED(rv))
return NS_ERROR_FAILURE;
// OK, the default value here is the description of the type.
rv = regKey->ReadStringValue(EmptyString(), handlerCommand);
if (NS_FAILED(rv)) {
// Check if there is a DelegateExecute string
nsAutoString delegateExecute;
rv = regKey->ReadStringValue(NS_LITERAL_STRING("DelegateExecute"), delegateExecute);
NS_ENSURE_SUCCESS(rv, rv);
// Look for InProcServer32
nsAutoString delegateExecuteRegPath;
delegateExecuteRegPath.AssignLiteral("CLSID\\");
delegateExecuteRegPath.Append(delegateExecute);
delegateExecuteRegPath.AppendLiteral("\\InProcServer32");
rv = chkKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT,
delegateExecuteRegPath,
nsIWindowsRegKey::ACCESS_QUERY_VALUE);
if (NS_SUCCEEDED(rv)) {
rv = chkKey->ReadStringValue(EmptyString(), handlerCommand);
}
if (NS_FAILED(rv)) {
// Look for LocalServer32
delegateExecuteRegPath.AssignLiteral("CLSID\\");
delegateExecuteRegPath.Append(delegateExecute);
delegateExecuteRegPath.AppendLiteral("\\LocalServer32");
rv = chkKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT,
delegateExecuteRegPath,
nsIWindowsRegKey::ACCESS_QUERY_VALUE);
NS_ENSURE_SUCCESS(rv, rv);
rv = chkKey->ReadStringValue(EmptyString(), handlerCommand);
NS_ENSURE_SUCCESS(rv, rv);
}
}
}
if (!CleanupCmdHandlerPath(handlerCommand))
return NS_ERROR_FAILURE;
// XXX FIXME: If this fails, the UI will display the full command
// string.
// There are some rare cases this can happen - ["url.dll" -foo]
// for example won't resolve correctly to the system dir. The
// subsequent launch of the helper app will work though.
nsCOMPtr<nsIFile> lf;
NS_NewLocalFile(handlerCommand, true, getter_AddRefs(lf));
if (!lf)
return NS_ERROR_FILE_NOT_FOUND;
//.........这里部分代码省略.........
示例9: MakeByteRangeString
nsresult
nsPluginStreamListenerPeer::RequestRead(NPByteRange* rangeList)
{
nsAutoCString rangeString;
int32_t numRequests;
MakeByteRangeString(rangeList, rangeString, &numRequests);
if (numRequests == 0)
return NS_ERROR_FAILURE;
nsresult rv = NS_OK;
nsCOMPtr<nsIInterfaceRequestor> callbacks = do_QueryReferent(mWeakPtrChannelCallbacks);
nsCOMPtr<nsILoadGroup> loadGroup = do_QueryReferent(mWeakPtrChannelLoadGroup);
nsCOMPtr<nsIChannel> channel;
rv = NS_NewChannel(getter_AddRefs(channel), mURL, nullptr, loadGroup, callbacks);
if (NS_FAILED(rv))
return rv;
nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(channel));
if (!httpChannel)
return NS_ERROR_FAILURE;
httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Range"), rangeString, false);
mAbort = true; // instruct old stream listener to cancel
// the request on the next ODA.
nsCOMPtr<nsIStreamListener> converter;
if (numRequests == 1) {
converter = this;
// set current stream offset equal to the first offset in the range list
// it will work for single byte range request
// for multy range we'll reset it in ODA
SetStreamOffset(rangeList->offset);
} else {
nsWeakPtr weakpeer =
do_GetWeakReference(static_cast<nsISupportsWeakReference*>(this));
nsPluginByteRangeStreamListener *brrListener =
new nsPluginByteRangeStreamListener(weakpeer);
if (brrListener)
converter = brrListener;
else
return NS_ERROR_OUT_OF_MEMORY;
}
mPendingRequests += numRequests;
nsCOMPtr<nsISupportsPRUint32> container = do_CreateInstance(NS_SUPPORTS_PRUINT32_CONTRACTID, &rv);
if (NS_FAILED(rv))
return rv;
rv = container->SetData(MAGIC_REQUEST_CONTEXT);
if (NS_FAILED(rv))
return rv;
rv = channel->AsyncOpen(converter, container);
if (NS_SUCCEEDED(rv))
TrackRequest(channel);
return rv;
}
示例10: NS_ASSERTION
bool
nsTypeAheadFind::IsRangeVisible(nsIPresShell *aPresShell,
nsPresContext *aPresContext,
nsIDOMRange *aRange, bool aMustBeInViewPort,
bool aGetTopVisibleLeaf,
nsIDOMRange **aFirstVisibleRange,
bool *aUsesIndependentSelection)
{
NS_ASSERTION(aPresShell && aPresContext && aRange && aFirstVisibleRange,
"params are invalid");
// We need to know if the range start is visible.
// Otherwise, return the first visible range start
// in aFirstVisibleRange
aRange->CloneRange(aFirstVisibleRange);
nsCOMPtr<nsIDOMNode> node;
aRange->GetStartContainer(getter_AddRefs(node));
nsCOMPtr<nsIContent> content(do_QueryInterface(node));
if (!content)
return false;
nsIFrame *frame = content->GetPrimaryFrame();
if (!frame)
return false; // No frame! Not visible then.
if (!frame->GetStyleVisibility()->IsVisible())
return false;
// Detect if we are _inside_ a text control, or something else with its own
// selection controller.
if (aUsesIndependentSelection) {
*aUsesIndependentSelection =
(frame->GetStateBits() & NS_FRAME_INDEPENDENT_SELECTION);
}
// ---- We have a frame ----
if (!aMustBeInViewPort)
return true; // Don't need it to be on screen, just in rendering tree
// Get the next in flow frame that contains the range start
PRInt32 startRangeOffset, startFrameOffset, endFrameOffset;
aRange->GetStartOffset(&startRangeOffset);
while (true) {
frame->GetOffsets(startFrameOffset, endFrameOffset);
if (startRangeOffset < endFrameOffset)
break;
nsIFrame *nextContinuationFrame = frame->GetNextContinuation();
if (nextContinuationFrame)
frame = nextContinuationFrame;
else
break;
}
// Set up the variables we need, return true if we can't get at them all
const PRUint16 kMinPixels = 12;
nscoord minDistance = nsPresContext::CSSPixelsToAppUnits(kMinPixels);
// Get the bounds of the current frame, relative to the current view.
// We don't use the more accurate AccGetBounds, because that is
// more expensive and the STATE_OFFSCREEN flag that this is used
// for only needs to be a rough indicator
nsRectVisibility rectVisibility = nsRectVisibility_kAboveViewport;
if (!aGetTopVisibleLeaf && !frame->GetRect().IsEmpty()) {
rectVisibility =
aPresShell->GetRectVisibility(frame,
nsRect(nsPoint(0,0), frame->GetSize()),
minDistance);
if (rectVisibility != nsRectVisibility_kAboveViewport) {
return true;
}
}
// We know that the target range isn't usable because it's not in the
// view port. Move range forward to first visible point,
// this speeds us up a lot in long documents
nsCOMPtr<nsIFrameEnumerator> frameTraversal;
nsCOMPtr<nsIFrameTraversal> trav(do_CreateInstance(kFrameTraversalCID));
if (trav)
trav->NewFrameTraversal(getter_AddRefs(frameTraversal),
aPresContext, frame,
eLeaf,
false, // aVisual
false, // aLockInScrollView
false // aFollowOOFs
);
if (!frameTraversal)
return false;
while (rectVisibility == nsRectVisibility_kAboveViewport) {
frameTraversal->Next();
frame = frameTraversal->CurrentItem();
if (!frame)
return false;
//.........这里部分代码省略.........
示例11: mItems
nsAutoCompleteResults::nsAutoCompleteResults() :
mItems(do_CreateInstance(NS_SUPPORTSARRAY_CONTRACTID)),
mDefaultItemIndex(0)
{
}
示例12: MOZ_ASSERT
nsresult
BackgroundFileSaver::ExtractSignatureInfo(const nsAString& filePath)
{
MOZ_ASSERT(!NS_IsMainThread(), "Cannot extract signature on main thread");
nsNSSShutDownPreventionLock nssLock;
if (isAlreadyShutDown()) {
return NS_ERROR_NOT_AVAILABLE;
}
{
MutexAutoLock lock(mLock);
if (!mSignatureInfoEnabled) {
return NS_OK;
}
}
nsresult rv;
nsCOMPtr<nsIX509CertDB> certDB = do_GetService(NS_X509CERTDB_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
#ifdef XP_WIN
// Setup the file to check.
WINTRUST_FILE_INFO fileToCheck = {0};
fileToCheck.cbStruct = sizeof(WINTRUST_FILE_INFO);
fileToCheck.pcwszFilePath = filePath.Data();
fileToCheck.hFile = nullptr;
fileToCheck.pgKnownSubject = nullptr;
// We want to check it is signed and trusted.
WINTRUST_DATA trustData = {0};
trustData.cbStruct = sizeof(trustData);
trustData.pPolicyCallbackData = nullptr;
trustData.pSIPClientData = nullptr;
trustData.dwUIChoice = WTD_UI_NONE;
trustData.fdwRevocationChecks = WTD_REVOKE_NONE;
trustData.dwUnionChoice = WTD_CHOICE_FILE;
trustData.dwStateAction = WTD_STATEACTION_VERIFY;
trustData.hWVTStateData = nullptr;
trustData.pwszURLReference = nullptr;
// Disallow revocation checks over the network
trustData.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL;
// no UI
trustData.dwUIContext = 0;
trustData.pFile = &fileToCheck;
// The WINTRUST_ACTION_GENERIC_VERIFY_V2 policy verifies that the certificate
// chains up to a trusted root CA and has appropriate permissions to sign
// code.
GUID policyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
// Check if the file is signed by something that is trusted. If the file is
// not signed, this is a no-op.
LONG ret = WinVerifyTrust(nullptr, &policyGUID, &trustData);
CRYPT_PROVIDER_DATA* cryptoProviderData = nullptr;
// According to the Windows documentation, we should check against 0 instead
// of ERROR_SUCCESS, which is an HRESULT.
if (ret == 0) {
cryptoProviderData = WTHelperProvDataFromStateData(trustData.hWVTStateData);
}
if (cryptoProviderData) {
// Lock because signature information is read on the main thread.
MutexAutoLock lock(mLock);
LOG(("Downloaded trusted and signed file [this = %p].", this));
// A binary may have multiple signers. Each signer may have multiple certs
// in the chain.
for (DWORD i = 0; i < cryptoProviderData->csSigners; ++i) {
const CERT_CHAIN_CONTEXT* certChainContext =
cryptoProviderData->pasSigners[i].pChainContext;
if (!certChainContext) {
break;
}
for (DWORD j = 0; j < certChainContext->cChain; ++j) {
const CERT_SIMPLE_CHAIN* certSimpleChain =
certChainContext->rgpChain[j];
if (!certSimpleChain) {
break;
}
nsCOMPtr<nsIX509CertList> nssCertList =
do_CreateInstance(NS_X509CERTLIST_CONTRACTID);
if (!nssCertList) {
break;
}
bool extractionSuccess = true;
for (DWORD k = 0; k < certSimpleChain->cElement; ++k) {
CERT_CHAIN_ELEMENT* certChainElement = certSimpleChain->rgpElement[k];
if (certChainElement->pCertContext->dwCertEncodingType !=
X509_ASN_ENCODING) {
continue;
}
nsCOMPtr<nsIX509Cert> nssCert = nullptr;
rv = certDB->ConstructX509(
reinterpret_cast<char *>(
certChainElement->pCertContext->pbCertEncoded),
certChainElement->pCertContext->cbCertEncoded,
getter_AddRefs(nssCert));
if (!nssCert) {
extractionSuccess = false;
LOG(("Couldn't create NSS cert [this = %p]", this));
break;
}
nssCertList->AddCert(nssCert);
nsString subjectName;
nssCert->GetSubjectName(subjectName);
//.........这里部分代码省略.........
示例13: NS_PRECONDITION
void
DataTransfer::FillInExternalData(TransferItem& aItem, uint32_t aIndex)
{
NS_PRECONDITION(mIsExternal, "Not an external data transfer");
if (aItem.mData) {
return;
}
// only drag and paste events should be calling FillInExternalData
NS_ASSERTION(mEventMessage != eCut && mEventMessage != eCopy,
"clipboard event with empty data");
NS_ConvertUTF16toUTF8 utf8format(aItem.mFormat);
const char* format = utf8format.get();
if (strcmp(format, "text/plain") == 0)
format = kUnicodeMime;
else if (strcmp(format, "text/uri-list") == 0)
format = kURLDataMime;
nsCOMPtr<nsITransferable> trans =
do_CreateInstance("@mozilla.org/widget/transferable;1");
if (!trans)
return;
trans->Init(nullptr);
trans->AddDataFlavor(format);
if (mEventMessage == ePaste) {
MOZ_ASSERT(aIndex == 0, "index in clipboard must be 0");
nsCOMPtr<nsIClipboard> clipboard = do_GetService("@mozilla.org/widget/clipboard;1");
if (!clipboard || mClipboardType < 0) {
return;
}
clipboard->GetData(trans, mClipboardType);
} else {
nsCOMPtr<nsIDragSession> dragSession = nsContentUtils::GetDragSession();
if (!dragSession) {
return;
}
#ifdef DEBUG
// Since this is an external drag, the source document will always be null.
nsCOMPtr<nsIDOMDocument> domDoc;
dragSession->GetSourceDocument(getter_AddRefs(domDoc));
MOZ_ASSERT(!domDoc);
#endif
dragSession->GetData(trans, aIndex);
}
uint32_t length = 0;
nsCOMPtr<nsISupports> data;
trans->GetTransferData(format, getter_AddRefs(data), &length);
if (!data)
return;
nsCOMPtr<nsIWritableVariant> variant = do_CreateInstance(NS_VARIANT_CONTRACTID);
if (!variant)
return;
nsCOMPtr<nsISupportsString> supportsstr = do_QueryInterface(data);
if (supportsstr) {
nsAutoString str;
supportsstr->GetData(str);
variant->SetAsAString(str);
}
else {
variant->SetAsISupports(data);
}
aItem.mData = variant;
}
示例14: char16_t
already_AddRefed<nsMIMEInfoWin> nsOSHelperAppService::GetByExtension(const nsAFlatString& aFileExt, const char *aTypeHint)
{
if (aFileExt.IsEmpty())
return nullptr;
// windows registry assumes your file extension is going to include the '.'.
// so make sure it's there...
nsAutoString fileExtToUse;
if (aFileExt.First() != char16_t('.'))
fileExtToUse = char16_t('.');
fileExtToUse.Append(aFileExt);
// Try to get an entry from the windows registry.
nsCOMPtr<nsIWindowsRegKey> regKey =
do_CreateInstance("@mozilla.org/windows-registry-key;1");
if (!regKey)
return nullptr;
nsresult rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT,
fileExtToUse,
nsIWindowsRegKey::ACCESS_QUERY_VALUE);
if (NS_FAILED(rv))
return nullptr;
nsAutoCString typeToUse;
if (aTypeHint && *aTypeHint) {
typeToUse.Assign(aTypeHint);
}
else {
nsAutoString temp;
if (NS_FAILED(regKey->ReadStringValue(NS_LITERAL_STRING("Content Type"),
temp)) || temp.IsEmpty()) {
return nullptr;
}
// Content-Type is always in ASCII
LossyAppendUTF16toASCII(temp, typeToUse);
}
nsRefPtr<nsMIMEInfoWin> mimeInfo = new nsMIMEInfoWin(typeToUse);
// don't append the '.'
mimeInfo->AppendExtension(NS_ConvertUTF16toUTF8(Substring(fileExtToUse, 1)));
mimeInfo->SetPreferredAction(nsIMIMEInfo::useSystemDefault);
nsAutoString appInfo;
bool found;
// Retrieve the default application for this extension
if (mAppAssoc) {
// Vista: use the new application association COM interfaces
// for resolving helpers.
nsString assocType(fileExtToUse);
wchar_t * pResult = nullptr;
HRESULT hr = mAppAssoc->QueryCurrentDefault(assocType.get(),
AT_FILEEXTENSION, AL_EFFECTIVE,
&pResult);
if (SUCCEEDED(hr)) {
found = true;
appInfo.Assign(pResult);
CoTaskMemFree(pResult);
}
else {
found = false;
}
}
else
{
found = NS_SUCCEEDED(regKey->ReadStringValue(EmptyString(),
appInfo));
}
// Bug 358297 - ignore the default handler, force the user to choose app
if (appInfo.EqualsLiteral("XPSViewer.Document"))
found = false;
if (!found) {
return nullptr;
}
// Get other nsIMIMEInfo fields from registry, if possible.
nsAutoString defaultDescription;
nsCOMPtr<nsIFile> defaultApplication;
if (NS_FAILED(GetDefaultAppInfo(appInfo, defaultDescription,
getter_AddRefs(defaultApplication)))) {
return nullptr;
}
mimeInfo->SetDefaultDescription(defaultDescription);
mimeInfo->SetDefaultApplicationHandler(defaultApplication);
// Grab the general description
GetMIMEInfoFromRegistry(appInfo, mimeInfo);
return mimeInfo.forget();
}
示例15: do_CreateInstance
NS_IMETHODIMP
nsCookiePromptService::CookieDialog(nsIDOMWindow *aParent,
nsICookie *aCookie,
const nsACString &aHostname,
PRInt32 aCookiesFromHost,
bool aChangingCookie,
bool *aRememberDecision,
PRInt32 *aAccept)
{
nsresult rv;
nsCOMPtr<nsIDialogParamBlock> block = do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID,&rv);
if (NS_FAILED(rv)) return rv;
block->SetInt(nsICookieAcceptDialog::ACCEPT_COOKIE, 1);
block->SetString(nsICookieAcceptDialog::HOSTNAME, NS_ConvertUTF8toUTF16(aHostname).get());
block->SetInt(nsICookieAcceptDialog::COOKIESFROMHOST, aCookiesFromHost);
block->SetInt(nsICookieAcceptDialog::CHANGINGCOOKIE, aChangingCookie ? 1 : 0);
nsCOMPtr<nsIMutableArray> objects =
do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
rv = objects->AppendElement(aCookie, false);
if (NS_FAILED(rv)) return rv;
block->SetObjects(objects);
nsCOMPtr<nsIWindowWatcher> wwatcher = do_GetService(NS_WINDOWWATCHER_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsISupports> arguments = do_QueryInterface(block);
nsCOMPtr<nsIDOMWindow> dialog;
nsCOMPtr<nsIDOMWindow> parent(aParent);
if (!parent) // if no parent provided, consult the window watcher:
wwatcher->GetActiveWindow(getter_AddRefs(parent));
if (parent) {
nsCOMPtr<nsPIDOMWindow> privateParent(do_QueryInterface(parent));
if (privateParent)
privateParent = privateParent->GetPrivateRoot();
parent = do_QueryInterface(privateParent);
}
// The cookie dialog will be modal for the root chrome window rather than the
// tab containing the permission-requesting page. This removes confusion
// about which monitor is displaying the dialog (see bug 470356), but also
// avoids unwanted tab switches (see bug 405239).
rv = wwatcher->OpenWindow(parent, "chrome://cookie/content/cookieAcceptDialog.xul", "_blank",
"centerscreen,chrome,modal,titlebar", arguments,
getter_AddRefs(dialog));
if (NS_FAILED(rv)) return rv;
// get back output parameters
PRInt32 tempValue;
block->GetInt(nsICookieAcceptDialog::ACCEPT_COOKIE, &tempValue);
*aAccept = tempValue;
// GetInt returns a PRInt32; we need to sanitize it into bool
block->GetInt(nsICookieAcceptDialog::REMEMBER_DECISION, &tempValue);
*aRememberDecision = (tempValue == 1);
return rv;
}