nsresult nsXBLProtoImplField::InstallField(nsIScriptContext* aContext, JSObject* aBoundNode, nsIPrincipal* aPrincipal, nsIURI* aBindingDocURI, PRBool* aDidInstall) const { NS_PRECONDITION(aBoundNode, "uh-oh, bound node should NOT be null or bad things will " "happen"); *aDidInstall = PR_FALSE; if (mFieldTextLength == 0) { return NS_OK; } jsval result = JSVAL_NULL; // EvaluateStringWithValue and JS_DefineUCProperty can both trigger GC, so // protect |result| here. nsresult rv; nsAutoGCRoot root(&result, &rv); if (NS_FAILED(rv)) return rv; nsCAutoString uriSpec; aBindingDocURI->GetSpec(uriSpec); JSContext* cx = (JSContext*) aContext->GetNativeContext(); NS_ASSERTION(!::JS_IsExceptionPending(cx), "Shouldn't get here when an exception is pending!"); // compile the literal string PRBool undefined; nsCOMPtr<nsIScriptContext> context = aContext; rv = context->EvaluateStringWithValue(nsDependentString(mFieldText, mFieldTextLength), aBoundNode, aPrincipal, uriSpec.get(), mLineNumber, JSVERSION_LATEST, (void*) &result, &undefined); if (NS_FAILED(rv)) return rv; // If EvaluateStringWithValue() threw an exception, just report it now. // Failure to evaluate a field should stop neither the get of the field value // nor an enumeration attempt. if (::JS_IsExceptionPending(cx)) { ::JS_ReportPendingException(cx); } if (undefined) { result = JSVAL_VOID; } // Define the evaluated result as a JS property nsDependentString name(mName); JSAutoRequest ar(cx); if (!::JS_DefineUCProperty(cx, aBoundNode, reinterpret_cast<const jschar*>(mName), name.Length(), result, nsnull, nsnull, mJSAttributes)) { return NS_ERROR_OUT_OF_MEMORY; } *aDidInstall = PR_TRUE; return NS_OK; }
void EmbedLiteApp::SendObserve(const char* aMessageName, const PRUnichar* aMessage) { LOGT("topic:%s", aMessageName); unused << STHREADAPP()->SendObserve(nsDependentCString(aMessageName), aMessage ? nsDependentString(aMessage) : nsString()); }
void nsCSSSelector::AppendToStringWithoutCombinatorsOrNegations (nsAString& aString, nsCSSStyleSheet* aSheet, PRBool aIsNegated) const { nsAutoString temp; PRBool isPseudoElement = IsPseudoElement(); // For non-pseudo-element selectors or for lone pseudo-elements, deal with // namespace prefixes. PRBool wroteNamespace = PR_FALSE; if (!isPseudoElement || !mNext) { // append the namespace prefix if needed nsXMLNameSpaceMap *sheetNS = aSheet ? aSheet->GetNameSpaceMap() : nsnull; // sheetNS is non-null if and only if we had an @namespace rule. If it's // null, that means that the only namespaces we could have are the // wildcard namespace (which can be implicit in this case) and the "none" // namespace, which then needs to be explicitly specified. if (!sheetNS) { NS_ASSERTION(mNameSpace == kNameSpaceID_Unknown || mNameSpace == kNameSpaceID_None, "How did we get this namespace?"); if (mNameSpace == kNameSpaceID_None) { aString.Append(PRUnichar('|')); wroteNamespace = PR_TRUE; } } else if (sheetNS->FindNameSpaceID(nsnull) == mNameSpace) { // We have the default namespace (possibly including the wildcard // namespace). Do nothing. NS_ASSERTION(mNameSpace == kNameSpaceID_Unknown || CanBeNamespaced(aIsNegated), "How did we end up with this namespace?"); } else if (mNameSpace == kNameSpaceID_None) { NS_ASSERTION(CanBeNamespaced(aIsNegated), "How did we end up with this namespace?"); aString.Append(PRUnichar('|')); wroteNamespace = PR_TRUE; } else if (mNameSpace != kNameSpaceID_Unknown) { NS_ASSERTION(CanBeNamespaced(aIsNegated), "How did we end up with this namespace?"); nsIAtom *prefixAtom = sheetNS->FindPrefix(mNameSpace); NS_ASSERTION(prefixAtom, "how'd we get a non-default namespace " "without a prefix?"); nsStyleUtil::AppendEscapedCSSIdent(nsDependentAtomString(prefixAtom), aString); aString.Append(PRUnichar('|')); wroteNamespace = PR_TRUE; } else { // A selector for an element in any namespace, while the default // namespace is something else. :not() is special in that the default // namespace is not implied for non-type selectors, so if this is a // negated non-type selector we don't need to output an explicit wildcard // namespace here, since those default to a wildcard namespace. if (CanBeNamespaced(aIsNegated)) { aString.AppendLiteral("*|"); wroteNamespace = PR_TRUE; } } } if (!mLowercaseTag) { // Universal selector: avoid writing the universal selector when we // can avoid it, especially since we're required to avoid it for the // inside of :not() if (wroteNamespace || (!mIDList && !mClassList && !mPseudoClassList && !mAttrList && (aIsNegated || !mNegations))) { aString.Append(PRUnichar('*')); } } else { // Append the tag name nsAutoString tag; (isPseudoElement ? mLowercaseTag : mCasedTag)->ToString(tag); if (isPseudoElement) { if (!mNext) { // Lone pseudo-element selector -- toss in a wildcard type selector // XXXldb Why? aString.Append(PRUnichar('*')); } if (!nsCSSPseudoElements::IsCSS2PseudoElement(mLowercaseTag)) { aString.Append(PRUnichar(':')); } // This should not be escaped since (a) the pseudo-element string // has a ":" that can't be escaped and (b) all pseudo-elements at // this point are known, and therefore we know they don't need // escaping. aString.Append(tag); } else { nsStyleUtil::AppendEscapedCSSIdent(tag, aString); } } // Append the id, if there is one if (mIDList) { nsAtomList* list = mIDList; while (list != nsnull) { list->mAtom->ToString(temp); aString.Append(PRUnichar('#')); nsStyleUtil::AppendEscapedCSSIdent(temp, aString); list = list->mNext; } } // Append each class in the linked list if (mClassList) { if (isPseudoElement) { #ifdef MOZ_XUL NS_ABORT_IF_FALSE(nsCSSAnonBoxes::IsTreePseudoElement(mLowercaseTag), "must be tree pseudo-element"); aString.Append(PRUnichar('(')); for (nsAtomList* list = mClassList; list; list = list->mNext) { nsStyleUtil::AppendEscapedCSSIdent(nsDependentAtomString(list->mAtom), aString); aString.Append(PRUnichar(',')); } // replace the final comma with a close-paren aString.Replace(aString.Length() - 1, 1, PRUnichar(')')); #else NS_ERROR("Can't happen"); #endif } else { nsAtomList* list = mClassList; while (list != nsnull) { list->mAtom->ToString(temp); aString.Append(PRUnichar('.')); nsStyleUtil::AppendEscapedCSSIdent(temp, aString); list = list->mNext; } } } // Append each attribute selector in the linked list if (mAttrList) { nsAttrSelector* list = mAttrList; while (list != nsnull) { aString.Append(PRUnichar('[')); // Append the namespace prefix if (list->mNameSpace == kNameSpaceID_Unknown) { aString.Append(PRUnichar('*')); aString.Append(PRUnichar('|')); } else if (list->mNameSpace != kNameSpaceID_None) { if (aSheet) { nsXMLNameSpaceMap *sheetNS = aSheet->GetNameSpaceMap(); nsIAtom *prefixAtom = sheetNS->FindPrefix(list->mNameSpace); // Default namespaces don't apply to attribute selectors, so // we must have a useful prefix. NS_ASSERTION(prefixAtom, "How did we end up with a namespace if the prefix " "is unknown?"); nsAutoString prefix; prefixAtom->ToString(prefix); nsStyleUtil::AppendEscapedCSSIdent(prefix, aString); aString.Append(PRUnichar('|')); } } // Append the attribute name list->mCasedAttr->ToString(temp); nsStyleUtil::AppendEscapedCSSIdent(temp, aString); if (list->mFunction != NS_ATTR_FUNC_SET) { // Append the function if (list->mFunction == NS_ATTR_FUNC_INCLUDES) aString.Append(PRUnichar('~')); else if (list->mFunction == NS_ATTR_FUNC_DASHMATCH) aString.Append(PRUnichar('|')); else if (list->mFunction == NS_ATTR_FUNC_BEGINSMATCH) aString.Append(PRUnichar('^')); else if (list->mFunction == NS_ATTR_FUNC_ENDSMATCH) aString.Append(PRUnichar('$')); else if (list->mFunction == NS_ATTR_FUNC_CONTAINSMATCH) aString.Append(PRUnichar('*')); aString.Append(PRUnichar('=')); // Append the value nsStyleUtil::AppendEscapedCSSString(list->mValue, aString); } aString.Append(PRUnichar(']')); list = list->mNext; } } // Append each pseudo-class in the linked list for (nsPseudoClassList* list = mPseudoClassList; list; list = list->mNext) { nsCSSPseudoClasses::PseudoTypeToString(list->mType, temp); // This should not be escaped since (a) the pseudo-class string // has a ":" that can't be escaped and (b) all pseudo-classes at // this point are known, and therefore we know they don't need // escaping. aString.Append(temp); if (list->u.mMemory) { aString.Append(PRUnichar('(')); if (nsCSSPseudoClasses::HasStringArg(list->mType)) { nsStyleUtil::AppendEscapedCSSIdent( nsDependentString(list->u.mString), aString); } else if (nsCSSPseudoClasses::HasNthPairArg(list->mType)) { PRInt32 a = list->u.mNumbers[0], b = list->u.mNumbers[1]; temp.Truncate(); if (a != 0) { if (a == -1) { temp.Append(PRUnichar('-')); } else if (a != 1) { temp.AppendInt(a); } temp.Append(PRUnichar('n')); } if (b != 0 || a == 0) { if (b >= 0 && a != 0) // check a != 0 for whether we printed above temp.Append(PRUnichar('+')); temp.AppendInt(b); } aString.Append(temp); } else { NS_ASSERTION(nsCSSPseudoClasses::HasSelectorListArg(list->mType), "unexpected pseudo-class"); nsString tmp; list->u.mSelectors->ToString(tmp, aSheet); aString.Append(tmp); } aString.Append(PRUnichar(')')); } } }
NS_IMETHODIMP nsXULTemplateQueryProcessorStorage::CompareResults(nsIXULTemplateResult* aLeft, nsIXULTemplateResult* aRight, nsIAtom* aVar, PRInt32* aResult) { *aResult = 0; if (!aVar) return NS_OK; // We're going to see if values are integers or float, to perform // a suitable comparison nsCOMPtr<nsISupports> leftValue, rightValue; if (aLeft) aLeft->GetBindingObjectFor(aVar, getter_AddRefs(leftValue)); if (aRight) aRight->GetBindingObjectFor(aVar, getter_AddRefs(rightValue)); if (leftValue && rightValue) { nsCOMPtr<nsIVariant> vLeftValue = do_QueryInterface(leftValue); nsCOMPtr<nsIVariant> vRightValue = do_QueryInterface(rightValue); if (vLeftValue && vRightValue) { nsresult rv1, rv2; PRUint16 vtypeL, vtypeR; vLeftValue->GetDataType(&vtypeL); vRightValue->GetDataType(&vtypeR); if (vtypeL == vtypeR) { if (vtypeL == nsIDataType::VTYPE_INT64) { PRInt64 leftValue, rightValue; rv1 = vLeftValue->GetAsInt64(&leftValue); rv2 = vRightValue->GetAsInt64(&rightValue); if (NS_SUCCEEDED(rv1) && NS_SUCCEEDED(rv2)) { if (leftValue > rightValue) *aResult = 1; else if (leftValue < rightValue) *aResult = -1; return NS_OK; } } else if (vtypeL == nsIDataType::VTYPE_DOUBLE) { double leftValue, rightValue; rv1 = vLeftValue->GetAsDouble(&leftValue); rv2 = vRightValue->GetAsDouble(&rightValue); if (NS_SUCCEEDED(rv1) && NS_SUCCEEDED(rv2)) { if (leftValue > rightValue) *aResult = 1; else if (leftValue < rightValue) *aResult = -1; return NS_OK; } } } } } // Values are not integers or floats, so we just compare them as simple strings nsAutoString leftVal; if (aLeft) aLeft->GetBindingFor(aVar, leftVal); nsAutoString rightVal; if (aRight) aRight->GetBindingFor(aVar, rightVal); *aResult = Compare(nsDependentString(leftVal), nsDependentString(rightVal), nsCaseInsensitiveStringComparator()); return NS_OK; }
nsresult nsXBLProtoImplField::InstallField(nsIScriptContext* aContext, JSObject* aBoundNode, nsIPrincipal* aPrincipal, nsIURI* aBindingDocURI, bool* aDidInstall) const { NS_TIME_FUNCTION_MIN(5); NS_PRECONDITION(aBoundNode, "uh-oh, bound node should NOT be null or bad things will " "happen"); *aDidInstall = false; // Empty fields are treated as not actually present. if (IsEmpty()) { return NS_OK; } nsAutoMicroTask mt; // EvaluateStringWithValue and JS_DefineUCProperty can both trigger GC, so // protect |result| here. nsresult rv; nsCAutoString uriSpec; aBindingDocURI->GetSpec(uriSpec); JSContext* cx = aContext->GetNativeContext(); NS_ASSERTION(!::JS_IsExceptionPending(cx), "Shouldn't get here when an exception is pending!"); // compile the literal string bool undefined; nsCOMPtr<nsIScriptContext> context = aContext; JSAutoRequest ar(cx); jsval result = JSVAL_NULL; rv = context->EvaluateStringWithValue(nsDependentString(mFieldText, mFieldTextLength), aBoundNode, aPrincipal, uriSpec.get(), mLineNumber, JSVERSION_LATEST, &result, &undefined); if (NS_FAILED(rv)) { return rv; } if (undefined) { result = JSVAL_VOID; } // Define the evaluated result as a JS property nsDependentString name(mName); if (!::JS_DefineUCProperty(cx, aBoundNode, reinterpret_cast<const jschar*>(mName), name.Length(), result, nsnull, nsnull, mJSAttributes)) { return NS_ERROR_OUT_OF_MEMORY; } *aDidInstall = true; return NS_OK; }
// parse and process a formatting attribute. If aStringArray is // non-NULL, return a list of the attributes from mNameFormat in // aStringArray. Otherwise, generate an autocomplete value from the // information in aMessage and append it to aValue. Any errors // (including failure to find a required attribute while building up aValue) // return an NS_ERROR_* up the stack so that the caller doesn't try and // generate an nsIAutoCompleteItem from this. // nsresult nsAbLDAPAutoCompFormatter::ProcessFormat(const nsAString & aFormat, nsILDAPMessage *aMessage, nsACString *aValue, nsCStringArray *aAttrs) { nsresult rv; // temp for return values // get some iterators to parse aFormat // const PRUnichar *iter = aFormat.BeginReading(); const PRUnichar *iterEnd = aFormat.EndReading(); // get the console service for error logging // nsCOMPtr<nsIConsoleService> consoleSvc = do_GetService("@mozilla.org/consoleservice;1", &rv); if (NS_FAILED(rv)) { NS_WARNING("nsAbLDAPAutoCompFormatter::ProcessFormat(): " "couldn't get console service"); } PRBool attrRequired = PR_FALSE; // is this attr required or optional? nsCAutoString attrName; // current attr to get // parse until we hit the end of the string // while (iter != iterEnd) { switch (*iter) { // process the next char case PRUnichar('{'): attrRequired = PR_TRUE; // this attribute is required /*FALLTHROUGH*/ case PRUnichar('['): rv = ParseAttrName(&iter, iterEnd, attrRequired, consoleSvc, attrName); if ( NS_FAILED(rv) ) { // something unrecoverable happened; stop parsing and // propagate the error up the stack // return rv; } // if we're building an array if ( aAttrs ) { // see if the string is already present in the array int i = 0, found = -1; while ( i < aAttrs->Count() ) { #ifdef MOZILLA_INTERNAL_API if (aAttrs->CStringAt(i)->Equals(attrName, nsCaseInsensitiveCStringComparator())) { #else if (aAttrs->CStringAt(i)->Equals(attrName, CaseInsensitiveCompare)) { #endif found = i; break; } ++i; } // and it doesn't already contain this string if (found == -1) { // add it if (!aAttrs->AppendCString(attrName)) { // current AppendCString always returns PR_TRUE; // if we hit this error, something has changed in // that code // NS_ERROR( "nsAbLDAPAutoCompFormatter::ProcessFormat():" " aAttrs->AppendCString(attrName) failed"); return NS_ERROR_UNEXPECTED; } } } else { // otherwise, append the first value of this attr to aValue // XXXdmose should do better than this; bug 76595 rv = AppendFirstAttrValue(attrName, aMessage, attrRequired, *aValue); if ( NS_FAILED(rv) ) { // something unrecoverable happened; stop parsing and // propagate the error up the stack // return rv; } } attrName.Truncate(); // clear out for next pass attrRequired = PR_FALSE; // reset to the default for the next pass break; case PRUnichar('\\'): // advance the iterator and be sure we haven't run off the end // ++iter; if (iter == iterEnd) { // abort; missing escaped char // if (consoleSvc) { consoleSvc->LogStringMessage( NS_LITERAL_STRING( "LDAP addressbook autocomplete formatter: error parsing format string: premature end of string after \\ escape").get()); NS_ERROR("LDAP addressbook autocomplete formatter: error " "parsing format string: premature end of string " "after \\ escape"); } return NS_ERROR_ILLEGAL_VALUE; } /*FALLTHROUGH*/ default: // if we're not just building an array of attribute names, append // this character to the item we're generating. // if (!aAttrs) { // this character gets treated as a literal // aValue->Append(NS_ConvertUTF16toUTF8(nsDependentString(iter,1))); } } ++iter; // advance the iterator } return NS_OK; }
PRBool nsClipboard::GetClipboardDataByID(ULONG ulFormatID, const char *aFlavor) { PVOID pDataMem; PRUint32 NumOfBytes; PRBool TempBufAllocated = PR_FALSE; PVOID pClipboardData = reinterpret_cast<PVOID>(WinQueryClipbrdData( 0, ulFormatID )); if (!pClipboardData) return PR_FALSE; if (strstr( aFlavor, "text/" )) // All text/.. flavors are null-terminated { pDataMem = pClipboardData; if (ulFormatID == CF_TEXT) // CF_TEXT is one byte character set { PRUint32 NumOfChars = strlen( static_cast<char*>(pDataMem) ); NumOfBytes = NumOfChars; if (!strcmp( aFlavor, kUnicodeMime )) // Asked for unicode, but only plain text available. Convert it! { nsAutoChar16Buffer buffer; PRInt32 bufLength; MultiByteToWideChar(0, static_cast<char*>(pDataMem), NumOfChars, buffer, bufLength); pDataMem = ToNewUnicode(nsDependentString(buffer.Elements())); TempBufAllocated = PR_TRUE; NumOfBytes = bufLength * sizeof(UniChar); } } else // All other text/.. flavors are in unicode { PRUint32 NumOfChars = UniStrlen( static_cast<UniChar*>(pDataMem) ); NumOfBytes = NumOfChars * sizeof(UniChar); PVOID pTempBuf = nsMemory::Alloc(NumOfBytes); memcpy(pTempBuf, pDataMem, NumOfBytes); pDataMem = pTempBuf; TempBufAllocated = PR_TRUE; } // DOM wants LF only, so convert from CRLF nsLinebreakHelpers::ConvertPlatformToDOMLinebreaks( aFlavor, &pDataMem, // pDataMem could be reallocated !! reinterpret_cast<PRInt32*>(&NumOfBytes) ); // yuck } else // Assume rest of flavors are binary data { if (ulFormatID == CF_BITMAP) { if (!strcmp( aFlavor, kJPEGImageMime )) { // OS2TODO Convert bitmap to jpg #ifdef DEBUG printf( "nsClipboard:: No JPG found on clipboard; need to convert BMP\n"); #endif } else if (!strcmp( aFlavor, kGIFImageMime )) { // OS2TODO Convert bitmap to gif #ifdef DEBUG printf( "nsClipboard:: No GIF found on clipboard; need to convert BMP\n"); #endif } else if (!strcmp( aFlavor, kPNGImageMime )) { // OS2TODO Convert bitmap to png #ifdef DEBUG printf( "nsClipboard:: No PNG found on clipboard; need to convert BMP\n"); #endif } } else { pDataMem = static_cast<PBYTE>(pClipboardData) + sizeof(PRUint32); NumOfBytes = *(static_cast<PRUint32*>(pClipboardData)); } } nsCOMPtr<nsISupports> genericDataWrapper; nsPrimitiveHelpers::CreatePrimitiveForData( aFlavor, pDataMem, NumOfBytes, getter_AddRefs(genericDataWrapper) ); #ifdef DEBUG nsresult errCode = #endif mTransferable->SetTransferData( aFlavor, genericDataWrapper, NumOfBytes ); #ifdef DEBUG if (errCode != NS_OK) printf( "nsClipboard:: Error setting data into transferable\n" ); #endif if (TempBufAllocated) nsMemory::Free(pDataMem); return PR_TRUE; }
PRInt32 nsString::RFind( const PRUnichar* aString, PRInt32 aOffset, PRInt32 aCount ) const { return RFind(nsDependentString(aString), aOffset, aCount); }
nsresult nsMapiHook::HandleAttachments (nsIMsgCompFields * aCompFields, PRInt32 aFileCount, lpnsMapiFileDesc aFiles, BOOL aIsUnicode) { nsresult rv = NS_OK ; nsCAutoString Attachments ; nsCAutoString TempFiles ; nsCOMPtr <nsILocalFile> pFile = do_CreateInstance (NS_LOCAL_FILE_CONTRACTID, &rv) ; if (NS_FAILED(rv) || (!pFile) ) return rv ; nsCOMPtr <nsILocalFile> pTempDir = do_CreateInstance (NS_LOCAL_FILE_CONTRACTID, &rv) ; if (NS_FAILED(rv) || (!pTempDir) ) return rv ; for (int i=0 ; i < aFileCount ; i++) { bool bTempFile = false ; if (aFiles[i].lpszPathName) { // check if attachment exists if (aIsUnicode) pFile->InitWithPath (nsDependentString(aFiles[i].lpszPathName)); else pFile->InitWithNativePath (nsDependentCString((const char*)aFiles[i].lpszPathName)); bool bExist ; rv = pFile->Exists(&bExist) ; PR_LOG(MAPI, PR_LOG_DEBUG, ("nsMapiHook::HandleAttachments: filename: %s path: %s exists = %s \n", (const char*)aFiles[i].lpszFileName, (const char*)aFiles[i].lpszPathName, bExist ? "true" : "false")); if (NS_FAILED(rv) || (!bExist) ) return NS_ERROR_FILE_TARGET_DOES_NOT_EXIST ; //Temp Directory nsCOMPtr <nsIFile> pTempFileDir; NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(pTempFileDir)); nsCOMPtr <nsILocalFile> pTempDir = do_QueryInterface(pTempFileDir); // create a new sub directory called moz_mapi underneath the temp directory pTempDir->AppendRelativePath(NS_LITERAL_STRING("moz_mapi")); pTempDir->Exists (&bExist) ; if (!bExist) { rv = pTempDir->Create(nsIFile::DIRECTORY_TYPE, 777) ; if (NS_FAILED(rv)) return rv ; } // rename or copy the existing temp file with the real file name nsAutoString leafName ; // convert to Unicode using Platform charset // leafName already contains a unicode leafName from lpszPathName. If we were given // a value for lpszFileName, use it. Otherwise stick with leafName if (aFiles[i].lpszFileName) { nsAutoString wholeFileName; if (aIsUnicode) wholeFileName.Assign(aFiles[i].lpszFileName); else ConvertToUnicode(nsMsgI18NFileSystemCharset(), (char *) aFiles[i].lpszFileName, wholeFileName); // need to find the last '\' and find the leafname from that. PRInt32 lastSlash = wholeFileName.RFindChar(PRUnichar('\\')); if (lastSlash != kNotFound) leafName.Assign(Substring(wholeFileName, lastSlash + 1)); else leafName.Assign(wholeFileName); } else pFile->GetLeafName (leafName); nsCOMPtr<nsIMsgAttachment> attachment = do_CreateInstance(NS_MSGATTACHMENT_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); attachment->SetName(leafName); nsCOMPtr<nsIFile> pTempFile; rv = pTempDir->Clone(getter_AddRefs(pTempFile)); if (NS_FAILED(rv) || !pTempFile) return rv; pTempFile->Append(leafName); pTempFile->Exists(&bExist); if (bExist) { rv = pTempFile->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0777); NS_ENSURE_SUCCESS(rv, rv); pTempFile->Remove(false); // remove so we can copy over it. pTempFile->GetLeafName(leafName); } // copy the file to its new location and file name pFile->CopyTo(pTempDir, leafName); // point pFile to the new location of the attachment pFile->InitWithFile(pTempDir); pFile->Append(leafName); // create MsgCompose attachment object attachment->SetTemporary(true); // this one is a temp file so set the flag for MsgCompose // now set the attachment object nsCAutoString pURL ; NS_GetURLSpecFromFile(pFile, pURL); attachment->SetUrl(pURL); // set the file size PRInt64 fileSize; pFile->GetFileSize(&fileSize); attachment->SetSize(fileSize); // add the attachment rv = aCompFields->AddAttachment (attachment); if (NS_FAILED(rv)) PR_LOG(MAPI, PR_LOG_DEBUG, ("nsMapiHook::HandleAttachments: AddAttachment rv = %lx\n", rv)); } } return rv ; }
// static nsresult IndexedDatabaseManager::CommonPostHandleEvent(EventChainPostVisitor& aVisitor, IDBFactory* aFactory) { MOZ_ASSERT(aVisitor.mDOMEvent); MOZ_ASSERT(aFactory); if (aVisitor.mEventStatus == nsEventStatus_eConsumeNoDefault) { return NS_OK; } Event* internalEvent = aVisitor.mDOMEvent->InternalDOMEvent(); MOZ_ASSERT(internalEvent); if (!internalEvent->IsTrusted()) { return NS_OK; } nsString type; MOZ_ALWAYS_SUCCEEDS(internalEvent->GetType(type)); MOZ_ASSERT(nsDependentString(kErrorEventType).EqualsLiteral("error")); if (!type.EqualsLiteral("error")) { return NS_OK; } nsCOMPtr<EventTarget> eventTarget = internalEvent->GetTarget(); MOZ_ASSERT(eventTarget); // Only mess with events that were originally targeted to an IDBRequest. RefPtr<IDBRequest> request; if (NS_FAILED(eventTarget->QueryInterface(kIDBRequestIID, getter_AddRefs(request))) || !request) { return NS_OK; } RefPtr<DOMError> error = request->GetErrorAfterResult(); nsString errorName; if (error) { error->GetName(errorName); } RootedDictionary<ErrorEventInit> init(nsContentUtils::RootingCxForThread()); request->GetCallerLocation(init.mFilename, &init.mLineno, &init.mColno); init.mMessage = errorName; init.mCancelable = true; init.mBubbles = true; nsEventStatus status = nsEventStatus_eIgnore; if (NS_IsMainThread()) { nsCOMPtr<nsIDOMWindow> window = do_QueryInterface(eventTarget->GetOwnerGlobal()); if (window) { nsCOMPtr<nsIScriptGlobalObject> sgo = do_QueryInterface(window); MOZ_ASSERT(sgo); if (NS_WARN_IF(NS_FAILED(sgo->HandleScriptError(init, &status)))) { status = nsEventStatus_eIgnore; } } else { // We don't fire error events at any global for non-window JS on the main // thread. } } else { // Not on the main thread, must be in a worker. WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate(); MOZ_ASSERT(workerPrivate); RefPtr<WorkerGlobalScope> globalScope = workerPrivate->GlobalScope(); MOZ_ASSERT(globalScope); RefPtr<ErrorEvent> errorEvent = ErrorEvent::Constructor(globalScope, nsDependentString(kErrorEventType), init); MOZ_ASSERT(errorEvent); errorEvent->SetTrusted(true); auto* target = static_cast<EventTarget*>(globalScope.get()); if (NS_WARN_IF(NS_FAILED( EventDispatcher::DispatchDOMEvent(target, /* aWidgetEvent */ nullptr, errorEvent, /* aPresContext */ nullptr, &status)))) { status = nsEventStatus_eIgnore; } } if (status == nsEventStatus_eConsumeNoDefault) { return NS_OK; } // Log the error to the error console. ScriptErrorHelper::Dump(errorName, init.mFilename, init.mLineno, init.mColno, nsIScriptError::errorFlag, aFactory->IsChrome(), aFactory->InnerWindowID()); return NS_OK; }
NS_IMETHODIMP nsCommandLine::ResolveFile(const nsAString& aArgument, nsIFile* *aResult) { NS_ENSURE_TRUE(mWorkingDir, NS_ERROR_NOT_INITIALIZED); // This is some seriously screwed-up code. nsIFile.appendRelativeNativePath // explicitly does not accept .. or . path parts, but that is exactly what we // need here. So we hack around it. nsresult rv; #if defined(MOZ_WIDGET_COCOA) nsCOMPtr<nsILocalFileMac> lfm (do_QueryInterface(mWorkingDir)); NS_ENSURE_TRUE(lfm, NS_ERROR_NO_INTERFACE); nsCOMPtr<nsILocalFileMac> newfile (do_CreateInstance(NS_LOCAL_FILE_CONTRACTID)); NS_ENSURE_TRUE(newfile, NS_ERROR_OUT_OF_MEMORY); CFURLRef baseurl; rv = lfm->GetCFURL(&baseurl); NS_ENSURE_SUCCESS(rv, rv); nsAutoCString path; NS_CopyUnicodeToNative(aArgument, path); CFURLRef newurl = CFURLCreateFromFileSystemRepresentationRelativeToBase(nullptr, (const UInt8*) path.get(), path.Length(), true, baseurl); CFRelease(baseurl); rv = newfile->InitWithCFURL(newurl); CFRelease(newurl); if (NS_FAILED(rv)) return rv; newfile.forget(aResult); return NS_OK; #elif defined(XP_UNIX) nsCOMPtr<nsIFile> lf (do_CreateInstance(NS_LOCAL_FILE_CONTRACTID)); NS_ENSURE_TRUE(lf, NS_ERROR_OUT_OF_MEMORY); if (aArgument.First() == '/') { // absolute path rv = lf->InitWithPath(aArgument); if (NS_FAILED(rv)) return rv; NS_ADDREF(*aResult = lf); return NS_OK; } nsAutoCString nativeArg; NS_CopyUnicodeToNative(aArgument, nativeArg); nsAutoCString newpath; mWorkingDir->GetNativePath(newpath); newpath.Append('/'); newpath.Append(nativeArg); rv = lf->InitWithNativePath(newpath); if (NS_FAILED(rv)) return rv; rv = lf->Normalize(); if (NS_FAILED(rv)) return rv; lf.forget(aResult); return NS_OK; #elif defined(XP_WIN32) nsCOMPtr<nsIFile> lf (do_CreateInstance(NS_LOCAL_FILE_CONTRACTID)); NS_ENSURE_TRUE(lf, NS_ERROR_OUT_OF_MEMORY); rv = lf->InitWithPath(aArgument); if (NS_FAILED(rv)) { // If it's a relative path, the Init is *going* to fail. We use string magic and // win32 _fullpath. Note that paths of the form "\Relative\To\CurDrive" are // going to fail, and I haven't figured out a way to work around this without // the PathCombine() function, which is not available in plain win95/nt4 nsAutoString fullPath; mWorkingDir->GetPath(fullPath); fullPath.Append('\\'); fullPath.Append(aArgument); WCHAR pathBuf[MAX_PATH]; if (!_wfullpath(pathBuf, fullPath.get(), MAX_PATH)) return NS_ERROR_FAILURE; rv = lf->InitWithPath(nsDependentString(pathBuf)); if (NS_FAILED(rv)) return rv; } lf.forget(aResult); return NS_OK; #else #error Need platform-specific logic here. #endif }
already_AddRefed<nsIAddrDatabase> GetAddressBook(const PRUnichar *name, PRBool makeNew) { nsresult rv = NS_OK; if (!makeNew) { // FIXME: How do I get the list of address books and look for a // specific name. Major bogosity! // For now, assume we didn't find anything with that name } IMPORT_LOG0( "In GetAddressBook\n"); nsIAddrDatabase * pDatabase = nsnull; /* Get the profile directory */ nsCOMPtr<nsILocalFile> dbPath; nsCOMPtr<nsIProxyObjectManager> proxyObjectManager = do_GetService(NS_XPCOMPROXY_CONTRACTID, &rv); if (NS_FAILED(rv)) return nsnull; nsCOMPtr<nsIAbManager> abMan = do_GetService(NS_ABMANAGER_CONTRACTID, &rv); if (NS_FAILED(rv)) return nsnull; nsCOMPtr<nsIAbManager> abManager; rv = proxyObjectManager->GetProxyForObject(NS_PROXY_TO_MAIN_THREAD, NS_GET_IID(nsIAbManager), abMan, NS_PROXY_SYNC, getter_AddRefs(abManager)); if (NS_SUCCEEDED(rv)) rv = abManager->GetUserProfileDirectory(getter_AddRefs(dbPath)); if (NS_SUCCEEDED(rv)) { // Create a new address book file - we don't care what the file // name is, as long as it's unique rv = dbPath->Append(NS_LITERAL_STRING("impab.mab")); if (NS_SUCCEEDED(rv)) { rv = dbPath->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0600); if (NS_SUCCEEDED(rv)) { IMPORT_LOG0( "Getting the address database factory\n"); nsCOMPtr<nsIAddrDatabase> addrDatabaseFactory = do_GetService(NS_ADDRDATABASE_CONTRACTID, &rv); if (NS_FAILED(rv)) return nsnull; nsCOMPtr<nsIAddrDatabase> addrDBFactory; rv = proxyObjectManager->GetProxyForObject(NS_PROXY_TO_MAIN_THREAD, NS_GET_IID(nsIAddrDatabase), addrDatabaseFactory, NS_PROXY_SYNC, getter_AddRefs(addrDBFactory)); if (NS_SUCCEEDED(rv) && addrDBFactory) { IMPORT_LOG0( "Opening the new address book\n"); nsCOMPtr<nsIAddrDatabase> nonProxyDatabase; rv = addrDBFactory->Open(dbPath, PR_TRUE, PR_TRUE, getter_AddRefs(nonProxyDatabase)); if (nonProxyDatabase) rv = proxyObjectManager->GetProxyForObject(NS_PROXY_TO_MAIN_THREAD, NS_GET_IID(nsIAddrDatabase), nonProxyDatabase, NS_PROXY_SYNC, (void**)&pDatabase); } } } } if (NS_FAILED(rv)) { IMPORT_LOG0( "Failed to get the user profile directory from the address book session\n"); } if (pDatabase) { // We made a database, add it to the UI?!?!?!?!?!?! // This is major bogosity again! Why doesn't the address book // just handle this properly for me? Uggggg... nsCOMPtr<nsIAbDirectory> nonProxyParentDir; abManager->GetDirectory(NS_LITERAL_CSTRING(kAllDirectoryRoot), getter_AddRefs(nonProxyParentDir)); nsCOMPtr<nsIAbDirectory> parentDir; /* * TODO * This may not be required in the future since the * primary listeners of the nsIAbDirectory will be * RDF directory datasource which propagates events to * RDF Observers. In the future the RDF directory datasource * will proxy the observers because asynchronous directory * implementations, such as LDAP, will assert results from * a thread other than the UI thread. * */ rv = proxyObjectManager->GetProxyForObject(NS_PROXY_TO_MAIN_THREAD, NS_GET_IID(nsIAbDirectory), nonProxyParentDir, NS_PROXY_SYNC | NS_PROXY_ALWAYS, getter_AddRefs(parentDir)); if (parentDir) { nsCAutoString URI("moz-abmdbdirectory://"); nsCAutoString leafName; rv = dbPath->GetNativeLeafName(leafName); if (NS_FAILED(rv)) IMPORT_LOG0( "*** Error: Unable to get name of database file\n"); else { URI.Append(leafName); rv = parentDir->CreateDirectoryByURI(nsDependentString(name), URI); if (NS_FAILED(rv)) IMPORT_LOG0( "*** Error: Unable to create address book directory\n"); } } if (NS_SUCCEEDED(rv)) IMPORT_LOG0( "Added new address book to the UI\n"); else IMPORT_LOG0( "*** Error: An error occurred while adding the address book to the UI\n"); } return pDatabase; }
static nsresult GetFileNameForPrintSettings(nsIPrintSettings* aPS) { // for testing #ifdef DEBUG_rods return NS_OK; #endif nsresult rv; nsCOMPtr<nsIFilePicker> filePicker = do_CreateInstance("@mozilla.org/filepicker;1", &rv); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIStringBundleService> bundleService = mozilla::services::GetStringBundleService(); if (!bundleService) return NS_ERROR_FAILURE; nsCOMPtr<nsIStringBundle> bundle; rv = bundleService->CreateBundle(NS_ERROR_GFX_PRINTER_BUNDLE_URL, getter_AddRefs(bundle)); NS_ENSURE_SUCCESS(rv, rv); nsXPIDLString title; rv = bundle->GetStringFromName(NS_LITERAL_STRING("PrintToFile").get(), getter_Copies(title)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIWindowWatcher> wwatch = (do_GetService(NS_WINDOWWATCHER_CONTRACTID, &rv)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIDOMWindow> window; wwatch->GetActiveWindow(getter_AddRefs(window)); rv = filePicker->Init(window, title, nsIFilePicker::modeSave); NS_ENSURE_SUCCESS(rv, rv); rv = filePicker->AppendFilters(nsIFilePicker::filterAll); NS_ENSURE_SUCCESS(rv, rv); PRUnichar* fileName; aPS->GetToFileName(&fileName); if (fileName) { if (*fileName) { nsAutoString leafName; nsCOMPtr<nsILocalFile> file(do_CreateInstance("@mozilla.org/file/local;1")); if (file) { rv = file->InitWithPath(nsDependentString(fileName)); if (NS_SUCCEEDED(rv)) { file->GetLeafName(leafName); filePicker->SetDisplayDirectory(file); } } if (!leafName.IsEmpty()) { rv = filePicker->SetDefaultString(leafName); } NS_ENSURE_SUCCESS(rv, rv); } nsMemory::Free(fileName); } PRInt16 dialogResult; filePicker->Show(&dialogResult); if (dialogResult == nsIFilePicker::returnCancel) { return NS_ERROR_ABORT; } nsCOMPtr<nsILocalFile> localFile; rv = filePicker->GetFile(getter_AddRefs(localFile)); NS_ENSURE_SUCCESS(rv, rv); if (dialogResult == nsIFilePicker::returnReplace) { // be extra safe and only delete when the file is really a file PRBool isFile; rv = localFile->IsFile(&isFile); if (NS_SUCCEEDED(rv) && isFile) { rv = localFile->Remove(PR_FALSE /* recursive delete */); NS_ENSURE_SUCCESS(rv, rv); } } nsAutoString unicodePath; rv = localFile->GetPath(unicodePath); NS_ENSURE_SUCCESS(rv,rv); if (unicodePath.IsEmpty()) { rv = NS_ERROR_ABORT; } if (NS_SUCCEEDED(rv)) aPS->SetToFileName(unicodePath.get()); return rv; }
bool TestInvariants(testcaseLine* testLine) { nsAutoString c1, c2, c3, c4, c5, normalized; c1 = nsDependentString((PRUnichar*)testLine->c1); c2 = nsDependentString((PRUnichar*)testLine->c2); c3 = nsDependentString((PRUnichar*)testLine->c3); c4 = nsDependentString((PRUnichar*)testLine->c4); c5 = nsDependentString((PRUnichar*)testLine->c5); bool rv = true; /* 1. The following invariants must be true for all conformant implementations NFC c2 == NFC(c1) == NFC(c2) == NFC(c3) */ DEBUG_TESTCASE(c2); NORMALIZE_AND_COMPARE(c2, c1, NFC, testLine->description); NORMALIZE_AND_COMPARE(c2, c2, NFC, testLine->description); NORMALIZE_AND_COMPARE(c2, c3, NFC, testLine->description); /* c4 == NFC(c4) == NFC(c5) */ DEBUG_TESTCASE(c4); NORMALIZE_AND_COMPARE(c4, c4, NFC, testLine->description); NORMALIZE_AND_COMPARE(c4, c5, NFC, testLine->description); /* NFD c3 == NFD(c1) == NFD(c2) == NFD(c3) */ DEBUG_TESTCASE(c3); NORMALIZE_AND_COMPARE(c3, c1, NFD, testLine->description); NORMALIZE_AND_COMPARE(c3, c2, NFD, testLine->description); NORMALIZE_AND_COMPARE(c3, c3, NFD, testLine->description); /* c5 == NFD(c4) == NFD(c5) */ DEBUG_TESTCASE(c5); NORMALIZE_AND_COMPARE(c5, c4, NFD, testLine->description); NORMALIZE_AND_COMPARE(c5, c5, NFD, testLine->description); /* NFKC c4 == NFKC(c1) == NFKC(c2) == NFKC(c3) == NFKC(c4) == NFKC(c5) */ DEBUG_TESTCASE(c4); NORMALIZE_AND_COMPARE(c4, c1, NFKC, testLine->description); NORMALIZE_AND_COMPARE(c4, c2, NFKC, testLine->description); NORMALIZE_AND_COMPARE(c4, c3, NFKC, testLine->description); NORMALIZE_AND_COMPARE(c4, c4, NFKC, testLine->description); NORMALIZE_AND_COMPARE(c4, c5, NFKC, testLine->description); /* NFKD c5 == NFKD(c1) == NFKD(c2) == NFKD(c3) == NFKD(c4) == NFKD(c5) */ DEBUG_TESTCASE(c5); NORMALIZE_AND_COMPARE(c5, c1, NFKD, testLine->description); NORMALIZE_AND_COMPARE(c5, c2, NFKD, testLine->description); NORMALIZE_AND_COMPARE(c5, c3, NFKD, testLine->description); NORMALIZE_AND_COMPARE(c5, c4, NFKD, testLine->description); NORMALIZE_AND_COMPARE(c5, c5, NFKD, testLine->description); return rv; }
AddHostToStringArray(nsUniCharEntry *aEntry, void *aArg) { static_cast<nsStringArray*>(aArg)->AppendString(nsDependentString(aEntry->GetKey())); return PL_DHASH_NEXT; }
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; }
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; }
already_AddRefed<nsIAddrDatabase> GetAddressBook(const char16_t *name, bool makeNew) { if (!makeNew) { // FIXME: How do I get the list of address books and look for a // specific name. Major bogosity! // For now, assume we didn't find anything with that name } IMPORT_LOG0("In GetAddressBook\n"); nsresult rv; nsCOMPtr<nsIAddrDatabase> pDatabase; nsCOMPtr<nsIFile> dbPath; nsCOMPtr<nsIAbManager> abManager = do_GetService(NS_ABMANAGER_CONTRACTID, &rv); if (NS_SUCCEEDED(rv)) { /* Get the profile directory */ rv = abManager->GetUserProfileDirectory(getter_AddRefs(dbPath)); if (NS_SUCCEEDED(rv)) { // Create a new address book file - we don't care what the file // name is, as long as it's unique rv = dbPath->Append(NS_LITERAL_STRING("impab.mab")); if (NS_SUCCEEDED(rv)) { rv = dbPath->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0600); if (NS_SUCCEEDED(rv)) { IMPORT_LOG0("Getting the address database factory\n"); nsCOMPtr<nsIAddrDatabase> addrDBFactory = do_GetService(NS_ADDRDATABASE_CONTRACTID, &rv); if (NS_FAILED(rv)) return nullptr; IMPORT_LOG0("Opening the new address book\n"); rv = addrDBFactory->Open(dbPath, true, true, getter_AddRefs(pDatabase)); } } } } if (NS_FAILED(rv)) { IMPORT_LOG0("Failed to get the user profile directory from the address book session\n"); } if (pDatabase && dbPath) { // We made a database, add it to the UI?!?!?!?!?!?! // This is major bogosity again! Why doesn't the address book // just handle this properly for me? Uggggg... nsCOMPtr<nsIAbDirectory> parentDir; abManager->GetDirectory(NS_LITERAL_CSTRING(kAllDirectoryRoot), getter_AddRefs(parentDir)); if (parentDir) { nsAutoCString URI("moz-abmdbdirectory://"); nsAutoCString leafName; rv = dbPath->GetNativeLeafName(leafName); if (NS_FAILED(rv)) IMPORT_LOG0("*** Error: Unable to get name of database file\n"); else { URI.Append(leafName); rv = parentDir->CreateDirectoryByURI(nsDependentString(name), URI); if (NS_FAILED(rv)) IMPORT_LOG0("*** Error: Unable to create address book directory\n"); } } if (NS_SUCCEEDED(rv)) IMPORT_LOG0("Added new address book to the UI\n"); else IMPORT_LOG0("*** Error: An error occurred while adding the address book to the UI\n"); } return pDatabase.forget(); }
PRBool nsAbIPCCard::Equals(nsABCOMCardStruct * card, nsStringArray & differingAttrs) { if(!card) return PR_FALSE; differingAttrs.Clear(); if(card->firstName) if (Compare(nsDependentString(card->firstName), m_FirstName, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kFirstNameColumn)); if(card->lastName) if (Compare(nsDependentString(card->lastName), m_LastName, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kLastNameColumn)); if(card->displayName) if (Compare(nsDependentString(card->displayName), m_DisplayName, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kDisplayNameColumn)); if(card->nickName) if (Compare(nsDependentString(card->nickName), m_NickName, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kNicknameColumn)); if(card->primaryEmail) if (Compare(nsDependentString(card->primaryEmail), m_PrimaryEmail, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kPriEmailColumn)); if(card->secondEmail) if (Compare(nsDependentString(card->secondEmail), m_SecondEmail, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(k2ndEmailColumn)); if(card->workPhone) if (Compare(nsDependentString(card->workPhone), m_WorkPhone, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kWorkPhoneColumn)); if(card->homePhone) if (Compare(nsDependentString(card->homePhone), m_HomePhone, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kHomePhoneColumn)); if(card->faxNumber) if (Compare(nsDependentString(card->faxNumber), m_FaxNumber, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kFaxColumn)); if(card->pagerNumber) if (Compare(nsDependentString(card->pagerNumber), m_PagerNumber, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kPagerColumn)); if(card->cellularNumber) if (Compare(nsDependentString(card->cellularNumber), m_CellularNumber, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kCellularColumn)); // card has home and work addresses joined, but "this" has them split if(card->homeAddress) if (Compare(nsDependentString(card->homeAddress), m_HomeAddress, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kHomeAddressColumn)); if(card->homeAddress2) if (Compare(nsDependentString(card->homeAddress2), m_HomeAddress2, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kHomeAddress2Column)); if(card->homeCity) if (Compare(nsDependentString(card->homeCity), m_HomeCity, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kHomeCityColumn)); if(card->homeState) if (Compare(nsDependentString(card->homeState), m_HomeState, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kHomeStateColumn)); if(card->homeZipCode) if (Compare(nsDependentString(card->homeZipCode), m_HomeZipCode, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kHomeZipCodeColumn)); if(card->homeCountry) if (Compare(nsDependentString(card->homeCountry), m_HomeCountry, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kHomeCountryColumn)); // card->workAddress is Joined, m_workAddress and m_workAddress2 are split if(card->workAddress) if (Compare(nsDependentString(card->workAddress), m_WorkAddress, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kWorkAddressColumn)); if(card->workAddress2) if (Compare(nsDependentString(card->workAddress2), m_WorkAddress2, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kWorkAddress2Column)); if(card->workCity) if (Compare(nsDependentString(card->workCity), m_WorkCity, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kWorkCityColumn)); if(card->workState) if (Compare(nsDependentString(card->workState), m_WorkState, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kWorkStateColumn)); if(card->workZipCode) if (Compare(nsDependentString(card->workZipCode), m_WorkZipCode, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kWorkZipCodeColumn)); if(card->workCountry) if (Compare(nsDependentString(card->workCountry), m_WorkCountry, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kWorkCountryColumn)); if(card->jobTitle) if (Compare(nsDependentString(card->jobTitle), m_JobTitle, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kJobTitleColumn)); if(card->department) if (Compare(nsDependentString(card->department), m_Department, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kDepartmentColumn)); if(card->company) if (Compare(nsDependentString(card->company), m_Company, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kCompanyColumn)); if(card->webPage1) if (Compare(nsDependentString(card->webPage1), m_WebPage1, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kWebPage1Column)); if(card->webPage2) if (Compare(nsDependentString(card->webPage2), m_WebPage2, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kWebPage2Column)); if(card->birthYear) if (Compare(nsDependentString(card->birthYear), m_BirthYear, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kBirthYearColumn)); if(card->birthMonth) if (Compare(nsDependentString(card->birthMonth), m_BirthMonth, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kBirthMonthColumn)); if(card->birthDay) if (Compare(nsDependentString(card->birthDay), m_BirthDay, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kBirthDayColumn)); if(card->custom1) if (Compare(nsDependentString(card->custom1), m_Custom1, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kCustom1Column)); if(card->custom2) if (Compare(nsDependentString(card->custom2), m_Custom2, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kCustom2Column)); if(card->custom3) if (Compare(nsDependentString(card->custom3), m_Custom3, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kCustom3Column)); if(card->custom4) if (Compare(nsDependentString(card->custom4), m_Custom4, nsCaseInsensitiveStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kCustom4Column)); if (card->isMailList != m_IsMailList) differingAttrs.AppendString(NS_LITERAL_STRING(kMailListName)); if(card->mailListURI) { nsCAutoString str(card->mailListURI); if (str.Equals(m_MailListURI, nsCaseInsensitiveCStringComparator())) differingAttrs.AppendString(NS_LITERAL_STRING(kMailListDescription)); } return (differingAttrs.Count() == 0); }
void nsCSSValue::AppendToString(nsCSSProperty aProperty, nsAString& aResult) const { // eCSSProperty_UNKNOWN gets used for some recursive calls below. NS_ABORT_IF_FALSE((0 <= aProperty && aProperty <= eCSSProperty_COUNT_no_shorthands) || aProperty == eCSSProperty_UNKNOWN, "property ID out of range"); nsCSSUnit unit = GetUnit(); if (unit == eCSSUnit_Null) { return; } if (eCSSUnit_String <= unit && unit <= eCSSUnit_Attr) { if (unit == eCSSUnit_Attr) { aResult.AppendLiteral("attr("); } nsAutoString buffer; GetStringValue(buffer); if (unit == eCSSUnit_String) { nsStyleUtil::AppendEscapedCSSString(buffer, aResult); } else if (unit == eCSSUnit_Families) { // XXX We really need to do *some* escaping. aResult.Append(buffer); } else { nsStyleUtil::AppendEscapedCSSIdent(buffer, aResult); } } else if (eCSSUnit_Array <= unit && unit <= eCSSUnit_Steps) { switch (unit) { case eCSSUnit_Counter: aResult.AppendLiteral("counter("); break; case eCSSUnit_Counters: aResult.AppendLiteral("counters("); break; case eCSSUnit_Cubic_Bezier: aResult.AppendLiteral("cubic-bezier("); break; case eCSSUnit_Steps: aResult.AppendLiteral("steps("); break; default: break; } nsCSSValue::Array *array = GetArrayValue(); bool mark = false; for (size_t i = 0, i_end = array->Count(); i < i_end; ++i) { if (mark && array->Item(i).GetUnit() != eCSSUnit_Null) { if (unit == eCSSUnit_Array && eCSSProperty_transition_timing_function != aProperty) aResult.AppendLiteral(" "); else aResult.AppendLiteral(", "); } if (unit == eCSSUnit_Steps && i == 1) { NS_ABORT_IF_FALSE(array->Item(i).GetUnit() == eCSSUnit_Enumerated && (array->Item(i).GetIntValue() == NS_STYLE_TRANSITION_TIMING_FUNCTION_STEP_START || array->Item(i).GetIntValue() == NS_STYLE_TRANSITION_TIMING_FUNCTION_STEP_END), "unexpected value"); if (array->Item(i).GetIntValue() == NS_STYLE_TRANSITION_TIMING_FUNCTION_STEP_START) { aResult.AppendLiteral("start"); } else { aResult.AppendLiteral("end"); } continue; } nsCSSProperty prop = ((eCSSUnit_Counter <= unit && unit <= eCSSUnit_Counters) && i == array->Count() - 1) ? eCSSProperty_list_style_type : aProperty; if (array->Item(i).GetUnit() != eCSSUnit_Null) { array->Item(i).AppendToString(prop, aResult); mark = true; } } if (eCSSUnit_Array == unit && aProperty == eCSSProperty_transition_timing_function) { aResult.AppendLiteral(")"); } } /* Although Function is backed by an Array, we'll handle it separately * because it's a bit quirky. */ else if (eCSSUnit_Function == unit) { const nsCSSValue::Array* array = GetArrayValue(); NS_ABORT_IF_FALSE(array->Count() >= 1, "Functions must have at least one element for the name."); /* Append the function name. */ const nsCSSValue& functionName = array->Item(0); if (functionName.GetUnit() == eCSSUnit_Enumerated) { // We assume that the first argument is always of nsCSSKeyword type. const nsCSSKeyword functionId = static_cast<nsCSSKeyword>(functionName.GetIntValue()); nsStyleUtil::AppendEscapedCSSIdent( NS_ConvertASCIItoUTF16(nsCSSKeywords::GetStringValue(functionId)), aResult); } else { functionName.AppendToString(aProperty, aResult); } aResult.AppendLiteral("("); /* Now, step through the function contents, writing each of them as we go. */ for (size_t index = 1; index < array->Count(); ++index) { array->Item(index).AppendToString(aProperty, aResult); /* If we're not at the final element, append a comma. */ if (index + 1 != array->Count()) aResult.AppendLiteral(", "); } /* Finally, append the closing parenthesis. */ aResult.AppendLiteral(")"); } else if (IsCalcUnit()) { NS_ABORT_IF_FALSE(GetUnit() == eCSSUnit_Calc, "unexpected unit"); CSSValueSerializeCalcOps ops(aProperty, aResult); css::SerializeCalc(*this, ops); } else if (eCSSUnit_Integer == unit) { aResult.AppendInt(GetIntValue(), 10); } else if (eCSSUnit_Enumerated == unit) { if (eCSSProperty_text_decoration_line == aProperty) { PRInt32 intValue = GetIntValue(); if (NS_STYLE_TEXT_DECORATION_LINE_NONE == intValue) { AppendASCIItoUTF16(nsCSSProps::LookupPropertyValue(aProperty, intValue), aResult); } else { // Ignore the "override all" internal value. // (It doesn't have a string representation.) intValue &= ~NS_STYLE_TEXT_DECORATION_LINE_OVERRIDE_ALL; nsStyleUtil::AppendBitmaskCSSValue( aProperty, intValue, NS_STYLE_TEXT_DECORATION_LINE_UNDERLINE, NS_STYLE_TEXT_DECORATION_LINE_PREF_ANCHORS, aResult); } } else if (eCSSProperty_marks == aProperty) { PRInt32 intValue = GetIntValue(); if (intValue == NS_STYLE_PAGE_MARKS_NONE) { AppendASCIItoUTF16(nsCSSProps::LookupPropertyValue(aProperty, intValue), aResult); } else { nsStyleUtil::AppendBitmaskCSSValue(aProperty, intValue, NS_STYLE_PAGE_MARKS_CROP, NS_STYLE_PAGE_MARKS_REGISTER, aResult); } } else if (eCSSProperty_unicode_bidi == aProperty) { PR_STATIC_ASSERT(NS_STYLE_UNICODE_BIDI_NORMAL == 0); PRInt32 intValue = GetIntValue(); if (NS_STYLE_UNICODE_BIDI_NORMAL == intValue) { AppendASCIItoUTF16(nsCSSProps::LookupPropertyValue(aProperty, intValue), aResult); } else { nsStyleUtil::AppendBitmaskCSSValue( aProperty, intValue, NS_STYLE_UNICODE_BIDI_EMBED, NS_STYLE_UNICODE_BIDI_PLAINTEXT, aResult); } } else { const nsAFlatCString& name = nsCSSProps::LookupPropertyValue(aProperty, GetIntValue()); AppendASCIItoUTF16(name, aResult); } } else if (eCSSUnit_EnumColor == unit) { // we can lookup the property in the ColorTable and then // get a string mapping the name nsCAutoString str; if (nsCSSProps::GetColorName(GetIntValue(), str)){ AppendASCIItoUTF16(str, aResult); } else { NS_ABORT_IF_FALSE(false, "bad color value"); } } else if (eCSSUnit_Color == unit) { nscolor color = GetColorValue(); if (color == NS_RGBA(0, 0, 0, 0)) { // Use the strictest match for 'transparent' so we do correct // round-tripping of all other rgba() values. aResult.AppendLiteral("transparent"); } else { PRUint8 a = NS_GET_A(color); if (a < 255) { aResult.AppendLiteral("rgba("); } else { aResult.AppendLiteral("rgb("); } NS_NAMED_LITERAL_STRING(comma, ", "); aResult.AppendInt(NS_GET_R(color), 10); aResult.Append(comma); aResult.AppendInt(NS_GET_G(color), 10); aResult.Append(comma); aResult.AppendInt(NS_GET_B(color), 10); if (a < 255) { aResult.Append(comma); aResult.AppendFloat(nsStyleUtil::ColorComponentToFloat(a)); } aResult.Append(PRUnichar(')')); } } else if (eCSSUnit_URL == unit || eCSSUnit_Image == unit) { aResult.Append(NS_LITERAL_STRING("url(")); nsStyleUtil::AppendEscapedCSSString( nsDependentString(GetOriginalURLValue()), aResult); aResult.Append(NS_LITERAL_STRING(")")); } else if (eCSSUnit_Element == unit) { aResult.Append(NS_LITERAL_STRING("-moz-element(#")); nsAutoString tmpStr; GetStringValue(tmpStr); nsStyleUtil::AppendEscapedCSSIdent(tmpStr, aResult); aResult.Append(NS_LITERAL_STRING(")")); } else if (eCSSUnit_Percent == unit) { aResult.AppendFloat(GetPercentValue() * 100.0f); } else if (eCSSUnit_Percent < unit) { // length unit aResult.AppendFloat(GetFloatValue()); } else if (eCSSUnit_Gradient == unit) { nsCSSValueGradient* gradient = GetGradientValue(); if (gradient->mIsRepeating) { if (gradient->mIsRadial) aResult.AppendLiteral("-moz-repeating-radial-gradient("); else aResult.AppendLiteral("-moz-repeating-linear-gradient("); } else { if (gradient->mIsRadial) aResult.AppendLiteral("-moz-radial-gradient("); else aResult.AppendLiteral("-moz-linear-gradient("); } if (gradient->mIsToCorner) { aResult.AppendLiteral("to"); NS_ABORT_IF_FALSE(gradient->mBgPos.mXValue.GetUnit() == eCSSUnit_Enumerated && gradient->mBgPos.mYValue.GetUnit() == eCSSUnit_Enumerated, "unexpected unit"); if (!(gradient->mBgPos.mXValue.GetIntValue() & NS_STYLE_BG_POSITION_CENTER)) { aResult.AppendLiteral(" "); gradient->mBgPos.mXValue.AppendToString(eCSSProperty_background_position, aResult); } if (!(gradient->mBgPos.mYValue.GetIntValue() & NS_STYLE_BG_POSITION_CENTER)) { aResult.AppendLiteral(" "); gradient->mBgPos.mYValue.AppendToString(eCSSProperty_background_position, aResult); } aResult.AppendLiteral(", "); } else if (gradient->mBgPos.mXValue.GetUnit() != eCSSUnit_None || gradient->mBgPos.mYValue.GetUnit() != eCSSUnit_None || gradient->mAngle.GetUnit() != eCSSUnit_None) { if (gradient->mBgPos.mXValue.GetUnit() != eCSSUnit_None) { gradient->mBgPos.mXValue.AppendToString(eCSSProperty_background_position, aResult); aResult.AppendLiteral(" "); } if (gradient->mBgPos.mXValue.GetUnit() != eCSSUnit_None) { gradient->mBgPos.mYValue.AppendToString(eCSSProperty_background_position, aResult); aResult.AppendLiteral(" "); } if (gradient->mAngle.GetUnit() != eCSSUnit_None) { gradient->mAngle.AppendToString(aProperty, aResult); } aResult.AppendLiteral(", "); } if (gradient->mIsRadial && (gradient->mRadialShape.GetUnit() != eCSSUnit_None || gradient->mRadialSize.GetUnit() != eCSSUnit_None)) { if (gradient->mRadialShape.GetUnit() != eCSSUnit_None) { NS_ABORT_IF_FALSE(gradient->mRadialShape.GetUnit() == eCSSUnit_Enumerated, "bad unit for radial gradient shape"); PRInt32 intValue = gradient->mRadialShape.GetIntValue(); NS_ABORT_IF_FALSE(intValue != NS_STYLE_GRADIENT_SHAPE_LINEAR, "radial gradient with linear shape?!"); AppendASCIItoUTF16(nsCSSProps::ValueToKeyword(intValue, nsCSSProps::kRadialGradientShapeKTable), aResult); aResult.AppendLiteral(" "); } if (gradient->mRadialSize.GetUnit() != eCSSUnit_None) { NS_ABORT_IF_FALSE(gradient->mRadialSize.GetUnit() == eCSSUnit_Enumerated, "bad unit for radial gradient size"); PRInt32 intValue = gradient->mRadialSize.GetIntValue(); AppendASCIItoUTF16(nsCSSProps::ValueToKeyword(intValue, nsCSSProps::kRadialGradientSizeKTable), aResult); } aResult.AppendLiteral(", "); } for (PRUint32 i = 0 ;;) { gradient->mStops[i].mColor.AppendToString(aProperty, aResult); if (gradient->mStops[i].mLocation.GetUnit() != eCSSUnit_None) { aResult.AppendLiteral(" "); gradient->mStops[i].mLocation.AppendToString(aProperty, aResult); } if (++i == gradient->mStops.Length()) { break; } aResult.AppendLiteral(", "); } aResult.AppendLiteral(")"); } else if (eCSSUnit_Pair == unit) { GetPairValue().AppendToString(aProperty, aResult); } else if (eCSSUnit_Triplet == unit) { GetTripletValue().AppendToString(aProperty, aResult); } else if (eCSSUnit_Rect == unit) { GetRectValue().AppendToString(aProperty, aResult); } else if (eCSSUnit_List == unit || eCSSUnit_ListDep == unit) { GetListValue()->AppendToString(aProperty, aResult); } else if (eCSSUnit_PairList == unit || eCSSUnit_PairListDep == unit) { GetPairListValue()->AppendToString(aProperty, aResult); } switch (unit) { case eCSSUnit_Null: break; case eCSSUnit_Auto: aResult.AppendLiteral("auto"); break; case eCSSUnit_Inherit: aResult.AppendLiteral("inherit"); break; case eCSSUnit_Initial: aResult.AppendLiteral("-moz-initial"); break; case eCSSUnit_None: aResult.AppendLiteral("none"); break; case eCSSUnit_Normal: aResult.AppendLiteral("normal"); break; case eCSSUnit_System_Font: aResult.AppendLiteral("-moz-use-system-font"); break; case eCSSUnit_All: aResult.AppendLiteral("all"); break; case eCSSUnit_Dummy: case eCSSUnit_DummyInherit: NS_ABORT_IF_FALSE(false, "should never serialize"); break; case eCSSUnit_String: break; case eCSSUnit_Ident: break; case eCSSUnit_Families: break; case eCSSUnit_URL: break; case eCSSUnit_Image: break; case eCSSUnit_Element: break; case eCSSUnit_Array: break; case eCSSUnit_Attr: case eCSSUnit_Cubic_Bezier: case eCSSUnit_Steps: case eCSSUnit_Counter: case eCSSUnit_Counters: aResult.Append(PRUnichar(')')); break; case eCSSUnit_Local_Font: break; case eCSSUnit_Font_Format: break; case eCSSUnit_Function: break; case eCSSUnit_Calc: break; case eCSSUnit_Calc_Plus: break; case eCSSUnit_Calc_Minus: break; case eCSSUnit_Calc_Times_L: break; case eCSSUnit_Calc_Times_R: break; case eCSSUnit_Calc_Divided: break; case eCSSUnit_Integer: break; case eCSSUnit_Enumerated: break; case eCSSUnit_EnumColor: break; case eCSSUnit_Color: break; case eCSSUnit_Percent: aResult.Append(PRUnichar('%')); break; case eCSSUnit_Number: break; case eCSSUnit_Gradient: break; case eCSSUnit_Pair: break; case eCSSUnit_Triplet: break; case eCSSUnit_Rect: break; case eCSSUnit_List: break; case eCSSUnit_ListDep: break; case eCSSUnit_PairList: break; case eCSSUnit_PairListDep: break; case eCSSUnit_Inch: aResult.AppendLiteral("in"); break; case eCSSUnit_Millimeter: aResult.AppendLiteral("mm"); break; case eCSSUnit_PhysicalMillimeter: aResult.AppendLiteral("mozmm"); break; case eCSSUnit_Centimeter: aResult.AppendLiteral("cm"); break; case eCSSUnit_Point: aResult.AppendLiteral("pt"); break; case eCSSUnit_Pica: aResult.AppendLiteral("pc"); break; case eCSSUnit_EM: aResult.AppendLiteral("em"); break; case eCSSUnit_XHeight: aResult.AppendLiteral("ex"); break; case eCSSUnit_Char: aResult.AppendLiteral("ch"); break; case eCSSUnit_RootEM: aResult.AppendLiteral("rem"); break; case eCSSUnit_Pixel: aResult.AppendLiteral("px"); break; case eCSSUnit_Degree: aResult.AppendLiteral("deg"); break; case eCSSUnit_Grad: aResult.AppendLiteral("grad"); break; case eCSSUnit_Radian: aResult.AppendLiteral("rad"); break; case eCSSUnit_Hertz: aResult.AppendLiteral("Hz"); break; case eCSSUnit_Kilohertz: aResult.AppendLiteral("kHz"); break; case eCSSUnit_Seconds: aResult.Append(PRUnichar('s')); break; case eCSSUnit_Milliseconds: aResult.AppendLiteral("ms"); break; } }
NS_IMETHODIMP nsCertPicker::PickByUsage(nsIInterfaceRequestor *ctx, const PRUnichar *selectedNickname, PRInt32 certUsage, bool allowInvalid, bool allowDuplicateNicknames, bool *canceled, nsIX509Cert **_retval) { nsNSSShutDownPreventionLock locker; PRInt32 selectedIndex = -1; bool selectionFound = false; PRUnichar **certNicknameList = nsnull; PRUnichar **certDetailsList = nsnull; CERTCertListNode* node = nsnull; nsresult rv = NS_OK; { // Iterate over all certs. This assures that user is logged in to all hardware tokens. CERTCertList *allcerts = nsnull; nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext(); allcerts = PK11_ListCerts(PK11CertListUnique, ctx); CERT_DestroyCertList(allcerts); } /* find all user certs that are valid and for SSL */ /* note that we are allowing expired certs in this list */ CERTCertList *certList = CERT_FindUserCertsByUsage(CERT_GetDefaultCertDB(), (SECCertUsage)certUsage, !allowDuplicateNicknames, !allowInvalid, ctx); CERTCertListCleaner clc(certList); if (!certList) { return NS_ERROR_NOT_AVAILABLE; } CERTCertNicknames *nicknames = getNSSCertNicknamesFromCertList(certList); CERTCertNicknamesCleaner cnc(nicknames); if (!nicknames) { return NS_ERROR_NOT_AVAILABLE; } certNicknameList = (PRUnichar **)nsMemory::Alloc(sizeof(PRUnichar *) * nicknames->numnicknames); certDetailsList = (PRUnichar **)nsMemory::Alloc(sizeof(PRUnichar *) * nicknames->numnicknames); if (!certNicknameList || !certDetailsList) { nsMemory::Free(certNicknameList); nsMemory::Free(certDetailsList); return NS_ERROR_OUT_OF_MEMORY; } PRInt32 CertsToUse; for (CertsToUse = 0, node = CERT_LIST_HEAD(certList); !CERT_LIST_END(node, certList) && CertsToUse < nicknames->numnicknames; node = CERT_LIST_NEXT(node) ) { nsNSSCertificate *tempCert = nsNSSCertificate::Create(node->cert); if (tempCert) { // XXX we really should be using an nsCOMPtr instead of manually add-refing, // but nsNSSCertificate does not have a default constructor. NS_ADDREF(tempCert); nsAutoString i_nickname(NS_ConvertUTF8toUTF16(nicknames->nicknames[CertsToUse])); nsAutoString nickWithSerial; nsAutoString details; if (!selectionFound) { if (i_nickname == nsDependentString(selectedNickname)) { selectedIndex = CertsToUse; selectionFound = PR_TRUE; } } if (NS_SUCCEEDED(tempCert->FormatUIStrings(i_nickname, nickWithSerial, details))) { certNicknameList[CertsToUse] = ToNewUnicode(nickWithSerial); certDetailsList[CertsToUse] = ToNewUnicode(details); } else { certNicknameList[CertsToUse] = nsnull; certDetailsList[CertsToUse] = nsnull; } NS_RELEASE(tempCert); ++CertsToUse; } } if (CertsToUse) { nsICertPickDialogs *dialogs = nsnull; rv = getNSSDialogs((void**)&dialogs, NS_GET_IID(nsICertPickDialogs), NS_CERTPICKDIALOGS_CONTRACTID); if (NS_SUCCEEDED(rv)) { nsPSMUITracker tracker; if (tracker.isUIForbidden()) { rv = NS_ERROR_NOT_AVAILABLE; } else { /* Throw up the cert picker dialog and get back the index of the selected cert */ rv = dialogs->PickCertificate(ctx, (const PRUnichar**)certNicknameList, (const PRUnichar**)certDetailsList, CertsToUse, &selectedIndex, canceled); } NS_RELEASE(dialogs); } } PRInt32 i; for (i = 0; i < CertsToUse; ++i) { nsMemory::Free(certNicknameList[i]); nsMemory::Free(certDetailsList[i]); } nsMemory::Free(certNicknameList); nsMemory::Free(certDetailsList); if (!CertsToUse) { return NS_ERROR_NOT_AVAILABLE; } if (NS_SUCCEEDED(rv) && !*canceled) { for (i = 0, node = CERT_LIST_HEAD(certList); !CERT_LIST_END(node, certList); ++i, node = CERT_LIST_NEXT(node)) { if (i == selectedIndex) { nsNSSCertificate *cert = nsNSSCertificate::Create(node->cert); if (!cert) { rv = NS_ERROR_OUT_OF_MEMORY; break; } nsIX509Cert *x509 = 0; nsresult rv = cert->QueryInterface(NS_GET_IID(nsIX509Cert), (void**)&x509); if (NS_FAILED(rv)) { break; } NS_ADDREF(x509); *_retval = x509; NS_RELEASE(cert); break; } } } return rv; }
static bool strEquals(const PRUnichar* utf16, const char* ascii) { nsCString utf8; NS_UTF16ToCString(nsDependentString(utf16), NS_CSTRING_ENCODING_UTF8, utf8); return strcmp(ascii, utf8.get()) == 0; }
/* set the Dictionary. * This also Loads the dictionary and initializes the converter using the dictionaries converter */ NS_IMETHODIMP mozHunspell::SetDictionary(const PRUnichar *aDictionary) { NS_ENSURE_ARG_POINTER(aDictionary); if (mDictionary.Equals(aDictionary)) return NS_OK; nsIFile* affFile = mDictionaries.GetWeak(nsDependentString(aDictionary)); if (!affFile) return NS_ERROR_FILE_NOT_FOUND; nsCAutoString dictFileName, affFileName; // XXX This isn't really good. nsIFile->NativePath isn't safe for all // character sets on Windows. // A better way would be to QI to nsILocalFile, and get a filehandle // from there. Only problem is that hunspell wants a path nsresult rv = affFile->GetNativePath(affFileName); NS_ENSURE_SUCCESS(rv, rv); dictFileName = affFileName; PRInt32 dotPos = dictFileName.RFindChar('.'); if (dotPos == -1) return NS_ERROR_FAILURE; dictFileName.SetLength(dotPos); dictFileName.AppendLiteral(".dic"); // SetDictionary can be called multiple times, so we might have a // valid mHunspell instance which needs cleaned up. delete mHunspell; mDictionary = aDictionary; mHunspell = new Hunspell(affFileName.get(), dictFileName.get()); if (!mHunspell) return NS_ERROR_OUT_OF_MEMORY; nsCOMPtr<nsICharsetConverterManager> ccm = do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); rv = ccm->GetUnicodeDecoder(mHunspell->get_dic_encoding(), getter_AddRefs(mDecoder)); NS_ENSURE_SUCCESS(rv, rv); rv = ccm->GetUnicodeEncoder(mHunspell->get_dic_encoding(), getter_AddRefs(mEncoder)); NS_ENSURE_SUCCESS(rv, rv); if (mEncoder) mEncoder->SetOutputErrorBehavior(mEncoder->kOnError_Signal, nsnull, '?'); PRInt32 pos = mDictionary.FindChar('-'); if (pos == -1) pos = mDictionary.FindChar('_'); if (pos == -1) mLanguage.Assign(mDictionary); else mLanguage = Substring(mDictionary, 0, pos); return NS_OK; }
// A little helper function to add the key to the list. // This is not threadsafe, and only safe if the consumer does not // modify the list. static PLDHashOperator AddHostToStringArray(nsUniCharEntry *aEntry, void *aArg) { static_cast<nsTArray<nsString>*>(aArg)->AppendElement(nsDependentString(aEntry->GetKey())); return PL_DHASH_NEXT; }
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; }
int nsExpatDriver::HandleExternalEntityRef(const char16_t *openEntityNames, const char16_t *base, const char16_t *systemId, const char16_t *publicId) { if (mInInternalSubset && !mInExternalDTD && openEntityNames) { mInternalSubset.Append(char16_t('%')); mInternalSubset.Append(nsDependentString(openEntityNames)); mInternalSubset.Append(char16_t(';')); } // Load the external entity into a buffer. nsCOMPtr<nsIInputStream> in; nsAutoString absURL; nsresult rv = OpenInputStreamFromExternalDTD(publicId, systemId, base, getter_AddRefs(in), absURL); if (NS_FAILED(rv)) { #ifdef DEBUG nsCString message("Failed to open external DTD: publicId \""); AppendUTF16toUTF8(publicId, message); message += "\" systemId \""; AppendUTF16toUTF8(systemId, message); message += "\" base \""; AppendUTF16toUTF8(base, message); message += "\" URL \""; AppendUTF16toUTF8(absURL, message); message += "\""; NS_WARNING(message.get()); #endif return 1; } nsCOMPtr<nsIUnicharInputStream> uniIn; rv = nsSimpleUnicharStreamFactory::GetInstance()-> CreateInstanceFromUTF8Stream(in, getter_AddRefs(uniIn)); NS_ENSURE_SUCCESS(rv, 1); int result = 1; if (uniIn) { XML_Parser entParser = XML_ExternalEntityParserCreate(mExpatParser, 0, kUTF16); if (entParser) { XML_SetBase(entParser, absURL.get()); mInExternalDTD = true; uint32_t totalRead; do { rv = uniIn->ReadSegments(ExternalDTDStreamReaderFunc, entParser, uint32_t(-1), &totalRead); } while (NS_SUCCEEDED(rv) && totalRead > 0); result = XML_Parse(entParser, nullptr, 0, 1); mInExternalDTD = false; XML_ParserFree(entParser); } } return result; }
nsresult nsOutlookMail::CreateList(const PRUnichar * pName, nsIAddrDatabase *pDb, LPMAPIPROP pUserList, nsIImportFieldMap *pFieldMap) { // If no name provided then we're done. if (!pName || !(*pName)) return NS_OK; nsresult rv = NS_ERROR_FAILURE; // Make sure we have db to work with. if (!pDb) return rv; nsCOMPtr <nsIMdbRow> newListRow; rv = pDb->GetNewListRow(getter_AddRefs(newListRow)); NS_ENSURE_SUCCESS(rv, rv); nsAutoCString column; LossyCopyUTF16toASCII(nsDependentString(pName), column); rv = pDb->AddListName(newListRow, column.get()); NS_ENSURE_SUCCESS(rv, rv); HRESULT hr; LPSPropValue value = NULL; ULONG valueCount = 0; LPSPropTagArray properties = NULL; m_mapi.MAPIAllocateBuffer(CbNewSPropTagArray(1), (void **)&properties); properties->cValues = 1; properties->aulPropTag [0] = m_mapi.GetEmailPropertyTag(pUserList, 0x8054); hr = pUserList->GetProps(properties, 0, &valueCount, &value); m_mapi.MAPIFreeBuffer(properties); if (HR_FAILED(hr)) return NS_ERROR_FAILURE; if (!value) return NS_ERROR_NOT_AVAILABLE; // XXX from here out, value must be freed with MAPIFreeBuffer SBinaryArray *sa=(SBinaryArray *)&value->Value.bin; if (!sa || !sa->lpbin) { m_mapi.MAPIFreeBuffer(value); return NS_ERROR_NULL_POINTER; } LPENTRYID lpEid; ULONG cbEid; int32_t idx; LPMESSAGE lpMsg; nsCString type; LPSPropValue pVal; nsString subject; uint32_t total; total=sa->cValues; for (idx = 0; idx < sa->cValues; idx++) { lpEid= (LPENTRYID) sa->lpbin[idx].lpb; cbEid = sa->lpbin[idx].cb; if (!m_mapi.OpenEntry(cbEid, lpEid, (LPUNKNOWN *) &lpMsg)) { IMPORT_LOG1("*** Error opening messages in mailbox: %S\n", pName); m_mapi.MAPIFreeBuffer(value); return NS_ERROR_FAILURE; } // This is a contact, add it to the address book! subject.Truncate(); pVal = m_mapi.GetMapiProperty(lpMsg, PR_SUBJECT); if (pVal) m_mapi.GetStringFromProp(pVal, subject); nsCOMPtr <nsIMdbRow> newRow; nsCOMPtr <nsIMdbRow> oldRow; pDb->GetNewRow(getter_AddRefs(newRow)); if (newRow) { if (BuildCard(subject.get(), pDb, newRow, lpMsg, pFieldMap)) { nsCOMPtr <nsIAbCard> userCard; nsCOMPtr <nsIAbCard> newCard; userCard = do_CreateInstance(NS_ABMDBCARD_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); pDb->InitCardFromRow(userCard,newRow); //add card to db bool bl=false; pDb->FindRowByCard(userCard,getter_AddRefs(oldRow)); if (oldRow) newRow = oldRow; else pDb->AddCardRowToDB(newRow); //add card list pDb->AddListCardColumnsToRow(userCard, newListRow,idx+1, getter_AddRefs(newCard), true, nullptr, nullptr); } } } m_mapi.MAPIFreeBuffer(value); rv = pDb->AddCardRowToDB(newListRow); NS_ENSURE_SUCCESS(rv, rv); rv = pDb->SetListAddressTotal(newListRow, total); rv = pDb->AddListDirNode(newListRow); return rv; }
nsresult GetSpecialSystemDirectory(SystemDirectories aSystemSystemDirectory, nsILocalFile** aFile) { #if defined(XP_WIN) WCHAR path[MAX_PATH]; #else char path[MAXPATHLEN]; #endif switch (aSystemSystemDirectory) { case OS_CurrentWorkingDirectory: #if defined(XP_WIN) if (!_wgetcwd(path, MAX_PATH)) return NS_ERROR_FAILURE; return NS_NewLocalFile(nsDependentString(path), PR_TRUE, aFile); #elif defined(XP_OS2) if (DosQueryPathInfo( ".", FIL_QUERYFULLNAME, path, MAXPATHLEN)) return NS_ERROR_FAILURE; #else if(!getcwd(path, MAXPATHLEN)) return NS_ERROR_FAILURE; #endif #if !defined(XP_WIN) return NS_NewNativeLocalFile(nsDependentCString(path), PR_TRUE, aFile); #endif case OS_DriveDirectory: #if defined (WINCE) { return NS_NewLocalFile(nsDependentString(L"\\"), PR_TRUE, aFile); } #elif defined (XP_WIN) { PRInt32 len = ::GetWindowsDirectoryW(path, MAX_PATH); if (len == 0) break; if (path[1] == PRUnichar(':') && path[2] == PRUnichar('\\')) path[3] = 0; return NS_NewLocalFile(nsDependentString(path), PR_TRUE, aFile); } #elif defined(XP_OS2) { ULONG ulBootDrive = 0; char buffer[] = " :\\OS2\\"; DosQuerySysInfo( QSV_BOOT_DRIVE, QSV_BOOT_DRIVE, &ulBootDrive, sizeof ulBootDrive); buffer[0] = 'A' - 1 + ulBootDrive; // duh, 1-based index... return NS_NewNativeLocalFile(nsDependentCString(buffer), PR_TRUE, aFile); } #else return NS_NewNativeLocalFile(nsDependentCString("/"), PR_TRUE, aFile); #endif case OS_TemporaryDirectory: #if defined (XP_WIN) { DWORD len = ::GetTempPathW(MAX_PATH, path); if (len == 0) break; return NS_NewLocalFile(nsDependentString(path, len), PR_TRUE, aFile); } #elif defined(XP_OS2) { char *tPath = PR_GetEnv("TMP"); if (!tPath || !*tPath) { tPath = PR_GetEnv("TEMP"); if (!tPath || !*tPath) { // if an OS/2 system has neither TMP nor TEMP defined // then it is severely broken, so this will never happen. return NS_ERROR_UNEXPECTED; } } nsCString tString = nsDependentCString(tPath); if (tString.Find("/", PR_FALSE, 0, -1)) { tString.ReplaceChar('/','\\'); } return NS_NewNativeLocalFile(tString, PR_TRUE, aFile); } #elif defined(XP_MACOSX) { return GetOSXFolderType(kUserDomain, kTemporaryFolderType, aFile); } #elif defined(XP_AMIGAOS) { return NS_NewNativeLocalFile(nsDependentCString("T:"), PR_TRUE, aFile); } #elif defined(XP_UNIX) || defined(XP_BEOS) { static const char *tPath = nsnull; if (!tPath) { tPath = PR_GetEnv("TMPDIR"); if (!tPath || !*tPath) { tPath = PR_GetEnv("TMP"); if (!tPath || !*tPath) { tPath = PR_GetEnv("TEMP"); if (!tPath || !*tPath) { tPath = "/tmp/"; } } } } return NS_NewNativeLocalFile(nsDependentCString(tPath), PR_TRUE, aFile); } #else break; #endif #if defined (XP_WIN) case Win_SystemDirectory: { #ifdef WINCE PRUnichar winDirBuf[MAX_PATH]; nsAutoString winDir; if (SHGetSpecialFolderPath(NULL, winDirBuf, CSIDL_WINDOWS, PR_TRUE)) winDir.Assign(winDirBuf); else winDir.Assign(L"\\Windows"); return NS_NewLocalFile(winDir, PR_TRUE, aFile); #else PRInt32 len = ::GetSystemDirectoryW(path, MAX_PATH); // Need enough space to add the trailing backslash if (!len || len > MAX_PATH - 2) break; path[len] = L'\\'; path[++len] = L'\0'; return NS_NewLocalFile(nsDependentString(path, len), PR_TRUE, aFile); #endif } case Win_WindowsDirectory: { #ifdef WINCE PRUnichar winDirBuf[MAX_PATH]; nsAutoString winDir; if (SHGetSpecialFolderPath(NULL, winDirBuf, CSIDL_WINDOWS, PR_TRUE)) winDir.Assign(winDirBuf); else winDir.Assign(L"\\Windows"); return NS_NewLocalFile(winDir, PR_TRUE, aFile); #else PRInt32 len = ::GetWindowsDirectoryW(path, MAX_PATH); // Need enough space to add the trailing backslash if (!len || len > MAX_PATH - 2) break; path[len] = L'\\'; path[++len] = L'\0'; return NS_NewLocalFile(nsDependentString(path, len), PR_TRUE, aFile); #endif } case Win_ProgramFiles: { return GetWindowsFolder(CSIDL_PROGRAM_FILES, aFile); } case Win_HomeDirectory: { PRInt32 len; if ((len = ::GetEnvironmentVariableW(L"HOME", path, MAX_PATH)) > 0) { // Need enough space to add the trailing backslash if (len > MAX_PATH - 2) break; path[len] = L'\\'; path[++len] = L'\0'; return NS_NewLocalFile(nsDependentString(path, len), PR_TRUE, aFile); } len = ::GetEnvironmentVariableW(L"HOMEDRIVE", path, MAX_PATH); if (0 < len && len < MAX_PATH) { WCHAR temp[MAX_PATH]; DWORD len2 = ::GetEnvironmentVariableW(L"HOMEPATH", temp, MAX_PATH); if (0 < len2 && len + len2 < MAX_PATH) wcsncat(path, temp, len2); len = wcslen(path); // Need enough space to add the trailing backslash if (len > MAX_PATH - 2) break; path[len] = L'\\'; path[++len] = L'\0'; return NS_NewLocalFile(nsDependentString(path, len), PR_TRUE, aFile); } } case Win_Desktop: { return GetWindowsFolder(CSIDL_DESKTOP, aFile); } case Win_Programs: { return GetWindowsFolder(CSIDL_PROGRAMS, aFile); } case Win_Downloads: { // Defined in KnownFolders.h. GUID folderid_downloads = {0x374de290, 0x123f, 0x4565, {0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b}}; nsresult rv = GetKnownFolder(&folderid_downloads, aFile); // On WinXP and 2k, there is no downloads folder, default // to 'Desktop'. if(NS_ERROR_FAILURE == rv) { rv = GetWindowsFolder(CSIDL_DESKTOP, aFile); } return rv; } case Win_Controls: { return GetWindowsFolder(CSIDL_CONTROLS, aFile); } case Win_Printers: { return GetWindowsFolder(CSIDL_PRINTERS, aFile); } case Win_Personal: { return GetWindowsFolder(CSIDL_PERSONAL, aFile); } case Win_Favorites: { return GetWindowsFolder(CSIDL_FAVORITES, aFile); } case Win_Startup: { return GetWindowsFolder(CSIDL_STARTUP, aFile); } case Win_Recent: { return GetWindowsFolder(CSIDL_RECENT, aFile); } case Win_Sendto: { return GetWindowsFolder(CSIDL_SENDTO, aFile); } case Win_Bitbucket: { return GetWindowsFolder(CSIDL_BITBUCKET, aFile); } case Win_Startmenu: { return GetWindowsFolder(CSIDL_STARTMENU, aFile); } case Win_Desktopdirectory: { return GetWindowsFolder(CSIDL_DESKTOPDIRECTORY, aFile); } case Win_Drives: { return GetWindowsFolder(CSIDL_DRIVES, aFile); } case Win_Network: { return GetWindowsFolder(CSIDL_NETWORK, aFile); } case Win_Nethood: { return GetWindowsFolder(CSIDL_NETHOOD, aFile); } case Win_Fonts: { return GetWindowsFolder(CSIDL_FONTS, aFile); } case Win_Templates: { return GetWindowsFolder(CSIDL_TEMPLATES, aFile); } #ifndef WINCE case Win_Common_Startmenu: { return GetWindowsFolder(CSIDL_COMMON_STARTMENU, aFile); } case Win_Common_Programs: { return GetWindowsFolder(CSIDL_COMMON_PROGRAMS, aFile); } case Win_Common_Startup: { return GetWindowsFolder(CSIDL_COMMON_STARTUP, aFile); } case Win_Common_Desktopdirectory: { return GetWindowsFolder(CSIDL_COMMON_DESKTOPDIRECTORY, aFile); } case Win_Printhood: { return GetWindowsFolder(CSIDL_PRINTHOOD, aFile); } case Win_Cookies: { return GetWindowsFolder(CSIDL_COOKIES, aFile); } #endif case Win_Appdata: { nsresult rv = GetWindowsFolder(CSIDL_APPDATA, aFile); #ifndef WINCE if (NS_FAILED(rv)) rv = GetRegWindowsAppDataFolder(PR_FALSE, aFile); #endif return rv; } case Win_LocalAppdata: { nsresult rv = GetWindowsFolder(CSIDL_LOCAL_APPDATA, aFile); #ifndef WINCE if (NS_FAILED(rv)) rv = GetRegWindowsAppDataFolder(PR_TRUE, aFile); #endif return rv; } #endif // XP_WIN #if defined(XP_AMIGAOS) case AmigaOS_HomeDirectory: return NS_NewNativeLocalFile(nsDependentCString("CURRENTUSER:"******"CURRENTUSER:"******"SYS:"), PR_TRUE, aFile); case AmigaOS_DesktopDirectory: return NS_NewNativeLocalFile(nsDependentCString("CURRENTUSER:"******"/usr/local/netscape/"), PR_TRUE, aFile); case Unix_LibDirectory: return NS_NewNativeLocalFile(nsDependentCString("/usr/local/lib/netscape/"), PR_TRUE, aFile); case Unix_HomeDirectory: return GetUnixHomeDir(aFile); case Unix_XDG_Desktop: case Unix_XDG_Documents: case Unix_XDG_Download: case Unix_XDG_Music: case Unix_XDG_Pictures: case Unix_XDG_PublicShare: case Unix_XDG_Templates: case Unix_XDG_Videos: return GetUnixXDGUserDirectory(aSystemSystemDirectory, aFile); #endif #ifdef XP_BEOS case BeOS_SettingsDirectory: { return GetBeOSFolder(B_USER_SETTINGS_DIRECTORY,0, aFile); } case BeOS_HomeDirectory: { return GetBeOSFolder(B_USER_DIRECTORY,0, aFile); } case BeOS_DesktopDirectory: { /* Get the user's desktop folder, which in the future may differ from the boot desktop */ char path[MAXPATHLEN]; if (find_directory(B_USER_DIRECTORY, 0, false, path, MAXPATHLEN) != B_OK ) break; return GetBeOSFolder(B_DESKTOP_DIRECTORY, dev_for_path(path), aFile); } case BeOS_SystemDirectory: { return GetBeOSFolder(B_BEOS_DIRECTORY,0, aFile); } #endif #ifdef XP_OS2 case OS2_SystemDirectory: { ULONG ulBootDrive = 0; char buffer[] = " :\\OS2\\System\\"; DosQuerySysInfo( QSV_BOOT_DRIVE, QSV_BOOT_DRIVE, &ulBootDrive, sizeof ulBootDrive); buffer[0] = 'A' - 1 + ulBootDrive; // duh, 1-based index... return NS_NewNativeLocalFile(nsDependentCString(buffer), PR_TRUE, aFile); } case OS2_OS2Directory: { ULONG ulBootDrive = 0; char buffer[] = " :\\OS2\\"; DosQuerySysInfo( QSV_BOOT_DRIVE, QSV_BOOT_DRIVE, &ulBootDrive, sizeof ulBootDrive); buffer[0] = 'A' - 1 + ulBootDrive; // duh, 1-based index... return NS_NewNativeLocalFile(nsDependentCString(buffer), PR_TRUE, aFile); } case OS2_HomeDirectory: { nsresult rv; char *tPath = PR_GetEnv("MOZILLA_HOME"); char buffer[CCHMAXPATH]; /* If MOZILLA_HOME is not set, use GetCurrentProcessDirectory */ /* To ensure we get a long filename system */ if (!tPath || !*tPath) { PPIB ppib; PTIB ptib; DosGetInfoBlocks( &ptib, &ppib); DosQueryModuleName( ppib->pib_hmte, CCHMAXPATH, buffer); *strrchr( buffer, '\\') = '\0'; // XXX DBCS misery tPath = buffer; } rv = NS_NewNativeLocalFile(nsDependentCString(tPath), PR_TRUE, aFile); PrfWriteProfileString(HINI_USERPROFILE, "Mozilla", "Home", tPath); return rv; } case OS2_DesktopDirectory: { char szPath[CCHMAXPATH + 1]; BOOL fSuccess; fSuccess = WinQueryActiveDesktopPathname (szPath, sizeof(szPath)); if (!fSuccess) { // this could happen if we are running without the WPS, return // the Home directory instead return GetSpecialSystemDirectory(OS2_HomeDirectory, aFile); } int len = strlen (szPath); if (len > CCHMAXPATH -1) break; szPath[len] = '\\'; szPath[len + 1] = '\0'; return NS_NewNativeLocalFile(nsDependentCString(szPath), PR_TRUE, aFile); } #endif default: break; } return NS_ERROR_NOT_AVAILABLE; }
nsresult nsXREDirProvider::GetUpdateRootDir(nsIFile* *aResult) { nsCOMPtr<nsIFile> updRoot; #if defined(MOZ_WIDGET_GONK) nsresult rv = NS_NewNativeLocalFile(nsDependentCString("/data/local"), true, getter_AddRefs(updRoot)); NS_ENSURE_SUCCESS(rv, rv); #else nsCOMPtr<nsIFile> appFile; bool per = false; nsresult rv = GetFile(XRE_EXECUTABLE_FILE, &per, getter_AddRefs(appFile)); NS_ENSURE_SUCCESS(rv, rv); rv = appFile->GetParent(getter_AddRefs(updRoot)); NS_ENSURE_SUCCESS(rv, rv); #ifdef XP_MACOSX nsCOMPtr<nsIFile> appRootDirFile; nsCOMPtr<nsIFile> localDir; nsAutoString appDirPath; if (NS_FAILED(appFile->GetParent(getter_AddRefs(appRootDirFile))) || NS_FAILED(appRootDirFile->GetPath(appDirPath)) || NS_FAILED(GetUserDataDirectoryHome(getter_AddRefs(localDir), true))) { return NS_ERROR_FAILURE; } int32_t dotIndex = appDirPath.RFind(".app"); if (dotIndex == kNotFound) { dotIndex = appDirPath.Length(); } appDirPath = Substring(appDirPath, 1, dotIndex - 1); bool hasVendor = gAppData->vendor && strlen(gAppData->vendor) != 0; if (hasVendor || gAppData->name) { if (NS_FAILED(localDir->AppendNative(nsDependentCString(hasVendor ? gAppData->vendor : gAppData->name)))) { return NS_ERROR_FAILURE; } } else if (NS_FAILED(localDir->AppendNative(NS_LITERAL_CSTRING("Mozilla")))) { return NS_ERROR_FAILURE; } if (NS_FAILED(localDir->Append(NS_LITERAL_STRING("updates"))) || NS_FAILED(localDir->AppendRelativePath(appDirPath))) { return NS_ERROR_FAILURE; } localDir.forget(aResult); return NS_OK; #elif XP_WIN nsAutoString pathHash; bool pathHashResult = false; bool hasVendor = gAppData->vendor && strlen(gAppData->vendor) != 0; nsAutoString appDirPath; if (SUCCEEDED(updRoot->GetPath(appDirPath))) { // Figure out where we should check for a cached hash value. If the // application doesn't have the nsXREAppData vendor value defined check // under SOFTWARE\Mozilla. wchar_t regPath[1024] = { L'\0' }; swprintf_s(regPath, mozilla::ArrayLength(regPath), L"SOFTWARE\\%S\\%S\\TaskBarIDs", (hasVendor ? gAppData->vendor : "Mozilla"), MOZ_APP_BASENAME); // If we pre-computed the hash, grab it from the registry. pathHashResult = GetCachedHash(HKEY_LOCAL_MACHINE, nsDependentString(regPath), appDirPath, pathHash); if (!pathHashResult) { pathHashResult = GetCachedHash(HKEY_CURRENT_USER, nsDependentString(regPath), appDirPath, pathHash); } } // Get the local app data directory and if a vendor name exists append it. // If only a product name exists, append it. If neither exist fallback to // old handling. We don't use the product name on purpose because we want a // shared update directory for different apps run from the same path. nsCOMPtr<nsIFile> localDir; if (pathHashResult && (hasVendor || gAppData->name) && NS_SUCCEEDED(GetUserDataDirectoryHome(getter_AddRefs(localDir), true)) && NS_SUCCEEDED(localDir->AppendNative(nsDependentCString(hasVendor ? gAppData->vendor : gAppData->name))) && NS_SUCCEEDED(localDir->Append(NS_LITERAL_STRING("updates"))) && NS_SUCCEEDED(localDir->Append(pathHash))) { localDir.forget(aResult); return NS_OK; } nsAutoString appPath; rv = updRoot->GetPath(appPath); NS_ENSURE_SUCCESS(rv, rv); // AppDir may be a short path. Convert to long path to make sure // the consistency of the update folder location nsString longPath; wchar_t* buf; uint32_t bufLength = longPath.GetMutableData(&buf, MAXPATHLEN); NS_ENSURE_TRUE(bufLength >= MAXPATHLEN, NS_ERROR_OUT_OF_MEMORY); DWORD len = GetLongPathNameW(appPath.get(), buf, bufLength); // Failing GetLongPathName() is not fatal. if (len <= 0 || len >= bufLength) longPath.Assign(appPath); else longPath.SetLength(len); // Use <UserLocalDataDir>\updates\<relative path to app dir from // Program Files> if app dir is under Program Files to avoid the // folder virtualization mess on Windows Vista nsAutoString programFiles; rv = GetShellFolderPath(CSIDL_PROGRAM_FILES, programFiles); NS_ENSURE_SUCCESS(rv, rv); programFiles.Append('\\'); uint32_t programFilesLen = programFiles.Length(); nsAutoString programName; if (_wcsnicmp(programFiles.get(), longPath.get(), programFilesLen) == 0) { programName = Substring(longPath, programFilesLen); } else { // We need the update root directory to live outside of the installation // directory, because otherwise the updater writing the log file can cause // the directory to be locked, which prevents it from being replaced after // background updates. programName.AssignASCII(MOZ_APP_NAME); } rv = GetUserLocalDataDirectory(getter_AddRefs(updRoot)); NS_ENSURE_SUCCESS(rv, rv); rv = updRoot->AppendRelativePath(programName); NS_ENSURE_SUCCESS(rv, rv); #endif // XP_WIN #endif updRoot.forget(aResult); return NS_OK; }
void nsXBLPrototypeHandler::ConstructPrototype(nsIContent* aKeyElement, const PRUnichar* aEvent, const PRUnichar* aPhase, const PRUnichar* aAction, const PRUnichar* aCommand, const PRUnichar* aKeyCode, const PRUnichar* aCharCode, const PRUnichar* aModifiers, const PRUnichar* aButton, const PRUnichar* aClickCount, const PRUnichar* aGroup, const PRUnichar* aPreventDefault, const PRUnichar* aAllowUntrusted) { mType = 0; if (aKeyElement) { mType |= NS_HANDLER_TYPE_XUL; nsCOMPtr<nsIWeakReference> weak = do_GetWeakReference(aKeyElement); if (!weak) { return; } weak.swap(mHandlerElement); } else { mType |= aCommand ? NS_HANDLER_TYPE_XBL_COMMAND : NS_HANDLER_TYPE_XBL_JS; mHandlerText = nsnull; } mDetail = -1; mMisc = 0; mKeyMask = 0; mPhase = NS_PHASE_BUBBLING; if (aAction) mHandlerText = ToNewUnicode(nsDependentString(aAction)); else if (aCommand) mHandlerText = ToNewUnicode(nsDependentString(aCommand)); nsAutoString event(aEvent); if (event.IsEmpty()) { if (mType & NS_HANDLER_TYPE_XUL) GetEventType(event); if (event.IsEmpty()) return; } mEventName = do_GetAtom(event); if (aPhase) { const nsDependentString phase(aPhase); if (phase.EqualsLiteral("capturing")) mPhase = NS_PHASE_CAPTURING; else if (phase.EqualsLiteral("target")) mPhase = NS_PHASE_TARGET; } // Button and clickcount apply only to XBL handlers and don't apply to XUL key // handlers. if (aButton && *aButton) mDetail = *aButton - '0'; if (aClickCount && *aClickCount) mMisc = *aClickCount - '0'; // Modifiers are supported by both types of handlers (XUL and XBL). nsAutoString modifiers(aModifiers); if (mType & NS_HANDLER_TYPE_XUL) aKeyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::modifiers, modifiers); if (!modifiers.IsEmpty()) { mKeyMask = cAllModifiers; char* str = ToNewCString(modifiers); char* newStr; char* token = nsCRT::strtok( str, ", \t", &newStr ); while( token != NULL ) { if (PL_strcmp(token, "shift") == 0) mKeyMask |= cShift | cShiftMask; else if (PL_strcmp(token, "alt") == 0) mKeyMask |= cAlt | cAltMask; else if (PL_strcmp(token, "meta") == 0) mKeyMask |= cMeta | cMetaMask; else if (PL_strcmp(token, "control") == 0) mKeyMask |= cControl | cControlMask; else if (PL_strcmp(token, "accel") == 0) mKeyMask |= KeyToMask(kAccelKey); else if (PL_strcmp(token, "access") == 0) mKeyMask |= KeyToMask(kMenuAccessKey); else if (PL_strcmp(token, "any") == 0) mKeyMask &= ~(mKeyMask << 4); token = nsCRT::strtok( newStr, ", \t", &newStr ); } nsMemory::Free(str); } nsAutoString key(aCharCode); if (key.IsEmpty()) { if (mType & NS_HANDLER_TYPE_XUL) { aKeyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::key, key); if (key.IsEmpty()) aKeyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::charcode, key); } } if (!key.IsEmpty()) { if (mKeyMask == 0) mKeyMask = cAllModifiers; ToLowerCase(key); // We have a charcode. mMisc = 1; mDetail = key[0]; const PRUint8 GTK2Modifiers = cShift | cControl | cShiftMask | cControlMask; if ((mKeyMask & GTK2Modifiers) == GTK2Modifiers && modifiers.First() != PRUnichar(',') && (mDetail == 'u' || mDetail == 'U')) ReportKeyConflict(key.get(), modifiers.get(), aKeyElement, "GTK2Conflict"); const PRUint8 WinModifiers = cControl | cAlt | cControlMask | cAltMask; if ((mKeyMask & WinModifiers) == WinModifiers && modifiers.First() != PRUnichar(',') && (('A' <= mDetail && mDetail <= 'Z') || ('a' <= mDetail && mDetail <= 'z'))) ReportKeyConflict(key.get(), modifiers.get(), aKeyElement, "WinConflict"); } else { key.Assign(aKeyCode); if (mType & NS_HANDLER_TYPE_XUL) aKeyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::keycode, key); if (!key.IsEmpty()) { if (mKeyMask == 0) mKeyMask = cAllModifiers; mDetail = GetMatchingKeyCode(key); } } if (aGroup && nsDependentString(aGroup).EqualsLiteral("system")) mType |= NS_HANDLER_TYPE_SYSTEM; if (aPreventDefault && nsDependentString(aPreventDefault).EqualsLiteral("true")) mType |= NS_HANDLER_TYPE_PREVENTDEFAULT; if (aAllowUntrusted) { mType |= NS_HANDLER_HAS_ALLOW_UNTRUSTED_ATTR; if (nsDependentString(aAllowUntrusted).EqualsLiteral("true")) { mType |= NS_HANDLER_ALLOW_UNTRUSTED; } else { mType &= ~NS_HANDLER_ALLOW_UNTRUSTED; } } }