void nsPageFrame::ProcessSpecialCodes(const nsString& aStr, nsString& aNewStr) { aNewStr = aStr; // Search to see if the &D code is in the string // then subst in the current date/time NS_NAMED_LITERAL_STRING(kDate, "&D"); if (aStr.Find(kDate) != kNotFound) { if (mPD->mDateTimeStr != nsnull) { aNewStr.ReplaceSubstring(kDate.get(), mPD->mDateTimeStr); } else { aNewStr.ReplaceSubstring(kDate.get(), EmptyString().get()); } } // NOTE: Must search for &PT before searching for &P // // Search to see if the "page number and page" total code are in the string // and replace the page number and page total code with the actual // values NS_NAMED_LITERAL_STRING(kPageAndTotal, "&PT"); if (aStr.Find(kPageAndTotal) != kNotFound) { PRUnichar * uStr = nsTextFormatter::smprintf(mPD->mPageNumAndTotalsFormat, mPageNum, mTotNumPages); aNewStr.ReplaceSubstring(kPageAndTotal.get(), uStr); nsMemory::Free(uStr); } // Search to see if the page number code is in the string // and replace the page number code with the actual value NS_NAMED_LITERAL_STRING(kPage, "&P"); if (aStr.Find(kPage) != kNotFound) { PRUnichar * uStr = nsTextFormatter::smprintf(mPD->mPageNumFormat, mPageNum); aNewStr.ReplaceSubstring(kPage.get(), uStr); nsMemory::Free(uStr); } NS_NAMED_LITERAL_STRING(kTitle, "&T"); if (aStr.Find(kTitle) != kNotFound) { if (mPD->mDocTitle != nsnull) { aNewStr.ReplaceSubstring(kTitle.get(), mPD->mDocTitle); } else { aNewStr.ReplaceSubstring(kTitle.get(), EmptyString().get()); } } NS_NAMED_LITERAL_STRING(kDocURL, "&U"); if (aStr.Find(kDocURL) != kNotFound) { if (mPD->mDocURL != nsnull) { aNewStr.ReplaceSubstring(kDocURL.get(), mPD->mDocURL); } else { aNewStr.ReplaceSubstring(kDocURL.get(), EmptyString().get()); } } NS_NAMED_LITERAL_STRING(kPageTotal, "&L"); if (aStr.Find(kPageTotal) != kNotFound) { PRUnichar * uStr = nsTextFormatter::smprintf(mPD->mPageNumFormat, mTotNumPages); aNewStr.ReplaceSubstring(kPageTotal.get(), uStr); nsMemory::Free(uStr); } }
void MediaDocument::UpdateTitleAndCharset(const nsACString& aTypeStr, const char* const* aFormatNames, int32_t aWidth, int32_t aHeight, const nsAString& aStatus) { nsXPIDLString fileStr; GetFileName(fileStr); NS_ConvertASCIItoUTF16 typeStr(aTypeStr); nsXPIDLString title; if (mStringBundle) { // if we got a valid size (not all media have a size) if (aWidth != 0 && aHeight != 0) { nsAutoString widthStr; nsAutoString heightStr; widthStr.AppendInt(aWidth); heightStr.AppendInt(aHeight); // If we got a filename, display it if (!fileStr.IsEmpty()) { const char16_t *formatStrings[4] = {fileStr.get(), typeStr.get(), widthStr.get(), heightStr.get()}; NS_ConvertASCIItoUTF16 fmtName(aFormatNames[eWithDimAndFile]); mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 4, getter_Copies(title)); } else { const char16_t *formatStrings[3] = {typeStr.get(), widthStr.get(), heightStr.get()}; NS_ConvertASCIItoUTF16 fmtName(aFormatNames[eWithDim]); mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 3, getter_Copies(title)); } } else { // If we got a filename, display it if (!fileStr.IsEmpty()) { const char16_t *formatStrings[2] = {fileStr.get(), typeStr.get()}; NS_ConvertASCIItoUTF16 fmtName(aFormatNames[eWithFile]); mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 2, getter_Copies(title)); } else { const char16_t *formatStrings[1] = {typeStr.get()}; NS_ConvertASCIItoUTF16 fmtName(aFormatNames[eWithNoInfo]); mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 1, getter_Copies(title)); } } } // set it on the document if (aStatus.IsEmpty()) { SetTitle(title); } else { nsXPIDLString titleWithStatus; const nsPromiseFlatString& status = PromiseFlatString(aStatus); const char16_t *formatStrings[2] = {title.get(), status.get()}; NS_NAMED_LITERAL_STRING(fmtName, "TitleWithStatus"); mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 2, getter_Copies(titleWithStatus)); SetTitle(titleWithStatus); } }
Maybe<bool> Compatibility::OnUIAMessage(WPARAM aWParam, LPARAM aLParam) { auto clearUiaRemotePid = MakeScopeExit([]() { sUiaRemotePid = Nothing(); }); Telemetry::AutoTimer<Telemetry::A11Y_UIA_DETECTION_TIMING_MS> timer; // UIA creates a section containing the substring "HOOK_SHMEM_" NS_NAMED_LITERAL_STRING(kStrHookShmem, "HOOK_SHMEM_"); // The section name always ends with this suffix, which is derived from the // current thread id and the UIA message's WPARAM and LPARAM. nsAutoString partialSectionSuffix; partialSectionSuffix.AppendPrintf("_%08x_%08x_%08x", ::GetCurrentThreadId(), static_cast<DWORD>(aLParam), aWParam); // Find any named Section that matches the naming convention of the UIA shared // memory. nsAutoHandle section; auto comparator = [&](const nsDependentSubstring& aName, const nsDependentSubstring& aType) -> bool { if (aType.Equals(NS_LITERAL_STRING("Section")) && FindInReadable(kStrHookShmem, aName) && StringEndsWith(aName, partialSectionSuffix)) { section.own(::OpenFileMapping(GENERIC_READ, FALSE, PromiseFlatString(aName).get())); return false; } return true; }; if (!FindNamedObject(comparator) || !section) { return Nothing(); } NTSTATUS ntStatus; // First we must query for a list of all the open handles in the system. UniquePtr<char[]> handleInfoBuf; ULONG handleInfoBufLen = sizeof(SYSTEM_HANDLE_INFORMATION_EX) + 1024 * sizeof(SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX); // We must query for handle information in a loop, since we are effectively // asking the kernel to take a snapshot of all the handles on the system; // the size of the required buffer may fluctuate between successive calls. while (true) { // These allocations can be hundreds of megabytes on some computers, so // we should use fallible new here. handleInfoBuf = MakeUniqueFallible<char[]>(handleInfoBufLen); if (!handleInfoBuf) { return Nothing(); } ntStatus = ::NtQuerySystemInformation( (SYSTEM_INFORMATION_CLASS) SystemExtendedHandleInformation, handleInfoBuf.get(), handleInfoBufLen, &handleInfoBufLen); if (ntStatus == STATUS_INFO_LENGTH_MISMATCH) { continue; } if (!NT_SUCCESS(ntStatus)) { return Nothing(); } break; } const DWORD ourPid = ::GetCurrentProcessId(); Maybe<PVOID> kernelObject; static Maybe<USHORT> sectionObjTypeIndex; nsTHashtable<nsUint32HashKey> nonSectionObjTypes; nsDataHashtable<nsVoidPtrHashKey, DWORD> objMap; auto handleInfo = reinterpret_cast<SYSTEM_HANDLE_INFORMATION_EX*>(handleInfoBuf.get()); for (ULONG index = 0; index < handleInfo->mHandleCount; ++index) { SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX& curHandle = handleInfo->mHandles[index]; HANDLE handle = reinterpret_cast<HANDLE>(curHandle.mHandle); // The mapping of the curHandle.mObjectTypeIndex field depends on the // underlying OS kernel. As we scan through the handle list, we record the // type indices such that we may use those values to skip over handles that // refer to non-section objects. if (sectionObjTypeIndex) { // If we know the type index for Sections, that's the fastest check... if (sectionObjTypeIndex.value() != curHandle.mObjectTypeIndex) { // Not a section continue; } } else if (nonSectionObjTypes.Contains(static_cast<uint32_t>( curHandle.mObjectTypeIndex))) { // Otherwise we check whether or not the object type is definitely _not_ // a Section... continue; } else if (ourPid == curHandle.mPid) { // Otherwise we need to issue some system calls to find out the object // type corresponding to the current handle's type index. ULONG objTypeBufLen; ntStatus = ::NtQueryObject(handle, ObjectTypeInformation, nullptr, 0, &objTypeBufLen); if (ntStatus != STATUS_INFO_LENGTH_MISMATCH) { continue; } auto objTypeBuf = MakeUnique<char[]>(objTypeBufLen); ntStatus = ::NtQueryObject(handle, ObjectTypeInformation, objTypeBuf.get(), objTypeBufLen, &objTypeBufLen); if (!NT_SUCCESS(ntStatus)) { continue; } auto objType = reinterpret_cast<PUBLIC_OBJECT_TYPE_INFORMATION*>(objTypeBuf.get()); // Now we check whether the object's type name matches "Section" nsDependentSubstring objTypeName(objType->TypeName.Buffer, objType->TypeName.Length / sizeof(wchar_t)); if (!objTypeName.Equals(NS_LITERAL_STRING("Section"))) { nonSectionObjTypes.PutEntry(static_cast<uint32_t>(curHandle.mObjectTypeIndex)); continue; } sectionObjTypeIndex = Some(curHandle.mObjectTypeIndex); } // At this point we know that curHandle references a Section object. // Now we can do some actual tests on it. if (ourPid != curHandle.mPid) { if (kernelObject && kernelObject.value() == curHandle.mObject) { // The kernel objects match -- we have found the remote pid! sUiaRemotePid = Some(curHandle.mPid); break; } // An object that is not ours. Since we do not yet know which kernel // object we're interested in, we'll save the current object for later. objMap.Put(curHandle.mObject, curHandle.mPid); } else if (handle == section.get()) { // This is the file mapping that we opened above. We save this mObject // in order to compare to Section objects opened by other processes. kernelObject = Some(curHandle.mObject); } } if (!kernelObject) { return Nothing(); } if (!sUiaRemotePid) { // We found kernelObject *after* we saw the remote process's copy. Now we // must look it up in objMap. DWORD pid; if (objMap.Get(kernelObject.value(), &pid)) { sUiaRemotePid = Some(pid); } } if (!sUiaRemotePid) { return Nothing(); } a11y::SetInstantiator(sUiaRemotePid.value()); // Block if necessary nsCOMPtr<nsIFile> instantiator; if (a11y::GetInstantiator(getter_AddRefs(instantiator)) && ShouldBlockUIAClient(instantiator)) { return Some(false); } return Some(true); }
nsresult nsCollationUnix::Initialize(nsILocale* locale) { #define kPlatformLocaleLength 64 NS_ASSERTION(mCollation == NULL, "Should only be initialized once"); nsresult res; mCollation = new nsCollation; if (mCollation == NULL) { NS_ASSERTION(0, "mCollation creation failed"); return NS_ERROR_OUT_OF_MEMORY; } // default platform locale mLocale.Assign('C'); nsAutoString localeStr; NS_NAMED_LITERAL_STRING(aCategory, "NSILOCALE_COLLATE##PLATFORM"); // get locale string, use app default if no locale specified if (locale == nsnull) { nsCOMPtr<nsILocaleService> localeService = do_GetService(NS_LOCALESERVICE_CONTRACTID, &res); if (NS_SUCCEEDED(res)) { nsCOMPtr<nsILocale> appLocale; res = localeService->GetApplicationLocale(getter_AddRefs(appLocale)); if (NS_SUCCEEDED(res)) { res = appLocale->GetCategory(aCategory, localeStr); NS_ASSERTION(NS_SUCCEEDED(res), "failed to get app locale info"); } } } else { res = locale->GetCategory(aCategory, localeStr); NS_ASSERTION(NS_SUCCEEDED(res), "failed to get locale info"); } // Get platform locale and charset name from locale, if available if (NS_SUCCEEDED(res)) { // keep the same behavior as 4.x as well as avoiding Linux collation key problem if (localeStr.LowerCaseEqualsLiteral("en_us")) { // note: locale is in platform format localeStr.AssignLiteral("C"); } nsCOMPtr <nsIPosixLocale> posixLocale = do_GetService(NS_POSIXLOCALE_CONTRACTID, &res); if (NS_SUCCEEDED(res)) { res = posixLocale->GetPlatformLocale(localeStr, mLocale); } nsCOMPtr <nsIPlatformCharset> platformCharset = do_GetService(NS_PLATFORMCHARSET_CONTRACTID, &res); if (NS_SUCCEEDED(res)) { nsCAutoString mappedCharset; res = platformCharset->GetDefaultCharsetForLocale(localeStr, mappedCharset); if (NS_SUCCEEDED(res)) { mCollation->SetCharset(mappedCharset.get()); } } } return NS_OK; }
static bool test_comparisons() { bool result; // nsString NS_NAMED_LITERAL_STRING(shortString1, "Foo"); NS_NAMED_LITERAL_STRING(shortString2, "Bar"); NS_NAMED_LITERAL_STRING(shortString3, "Bar"); NS_NAMED_LITERAL_STRING(shortString4, "bar"); NS_NAMED_LITERAL_STRING(longString, "FooBar"); // == result = (shortString1 == shortString2); if (result) return false; result = (shortString2 == shortString3); if (!result) return false; result = (shortString3 == shortString4); if (result) return false; result = (shortString1 == longString); if (result) return false; result = (longString == shortString1); if (result) return false; // != result = (shortString1 != shortString2); if (!result) return false; result = (shortString2 != shortString3); if (result) return false; result = (shortString3 != shortString4); if (!result) return false; result = (shortString1 != longString); if (!result) return false; result = (longString != shortString1); if (!result) return false; // < result = (shortString1 < shortString2); if (result) return false; result = (shortString2 < shortString1); if (!result) return false; result = (shortString1 < longString); if (!result) return false; result = (longString < shortString1); if (result) return false; result = (shortString2 < shortString3); if (result) return false; result = (shortString3 < shortString4); if (!result) return false; result = (shortString4 < shortString3); if (result) return false; // <= result = (shortString1 <= shortString2); if (result) return false; result = (shortString2 <= shortString1); if (!result) return false; result = (shortString1 <= longString); if (!result) return false; result = (longString <= shortString1); if (result) return false; result = (shortString2 <= shortString3); if (!result) return false; result = (shortString3 <= shortString4); if (!result) return false; result = (shortString4 <= shortString3); if (result) return false; // > result = (shortString1 > shortString2); if (!result) return false; result = (shortString2 > shortString1); if (result) return false; result = (shortString1 > longString); if (result) return false; result = (longString > shortString1); if (!result) return false; result = (shortString2 > shortString3); if (result) return false; result = (shortString3 > shortString4); if (result) return false; result = (shortString4 > shortString3); if (!result) return false; // >= result = (shortString1 >= shortString2); if (!result) return false; result = (shortString2 >= shortString1); if (result) return false; result = (shortString1 >= longString); if (result) return false; result = (longString >= shortString1); if (!result) return false; result = (shortString2 >= shortString3); if (!result) return false; result = (shortString3 >= shortString4); if (result) return false; result = (shortString4 >= shortString3); if (!result) return false; // nsCString NS_NAMED_LITERAL_CSTRING(shortCString1, "Foo"); NS_NAMED_LITERAL_CSTRING(shortCString2, "Bar"); NS_NAMED_LITERAL_CSTRING(shortCString3, "Bar"); NS_NAMED_LITERAL_CSTRING(shortCString4, "bar"); NS_NAMED_LITERAL_CSTRING(longCString, "FooBar"); // == result = (shortCString1 == shortCString2); if (result) return false; result = (shortCString2 == shortCString3); if (!result) return false; result = (shortCString3 == shortCString4); if (result) return false; result = (shortCString1 == longCString); if (result) return false; result = (longCString == shortCString1); if (result) return false; // != result = (shortCString1 != shortCString2); if (!result) return false; result = (shortCString2 != shortCString3); if (result) return false; result = (shortCString3 != shortCString4); if (!result) return false; result = (shortCString1 != longCString); if (!result) return false; result = (longCString != shortCString1); if (!result) return false; // < result = (shortCString1 < shortCString2); if (result) return false; result = (shortCString2 < shortCString1); if (!result) return false; result = (shortCString1 < longCString); if (!result) return false; result = (longCString < shortCString1); if (result) return false; result = (shortCString2 < shortCString3); if (result) return false; result = (shortCString3 < shortCString4); if (!result) return false; result = (shortCString4 < shortCString3); if (result) return false; // <= result = (shortCString1 <= shortCString2); if (result) return false; result = (shortCString2 <= shortCString1); if (!result) return false; result = (shortCString1 <= longCString); if (!result) return false; result = (longCString <= shortCString1); if (result) return false; result = (shortCString2 <= shortCString3); if (!result) return false; result = (shortCString3 <= shortCString4); if (!result) return false; result = (shortCString4 <= shortCString3); if (result) return false; // > result = (shortCString1 > shortCString2); if (!result) return false; result = (shortCString2 > shortCString1); if (result) return false; result = (shortCString1 > longCString); if (result) return false; result = (longCString > shortCString1); if (!result) return false; result = (shortCString2 > shortCString3); if (result) return false; result = (shortCString3 > shortCString4); if (result) return false; result = (shortCString4 > shortCString3); if (!result) return false; // >= result = (shortCString1 >= shortCString2); if (!result) return false; result = (shortCString2 >= shortCString1); if (result) return false; result = (shortCString1 >= longCString); if (result) return false; result = (longCString >= shortCString1); if (!result) return false; result = (shortCString2 >= shortCString3); if (!result) return false; result = (shortCString3 >= shortCString4); if (result) return false; result = (shortCString4 >= shortCString3); if (!result) return false; return true; }
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_INTERFACE_MAP_END // nsIDOMCSSValue NS_IMETHODIMP nsROCSSPrimitiveValue::GetCssText(nsAString& aCssText) { nsAutoString tmpStr; aCssText.Truncate(); nsresult result = NS_OK; switch (mType) { case CSS_PX : { float val = nsPresContext::AppUnitsToFloatCSSPixels(mValue.mAppUnits); tmpStr.AppendFloat(val); tmpStr.AppendLiteral("px"); break; } case CSS_IDENT : { AppendUTF8toUTF16(nsCSSKeywords::GetStringValue(mValue.mKeyword), tmpStr); break; } case CSS_STRING : case CSS_COUNTER : /* FIXME: COUNTER should use an object */ { tmpStr.Append(mValue.mString); break; } case CSS_URI : { if (mValue.mURI) { nsCAutoString specUTF8; mValue.mURI->GetSpec(specUTF8); tmpStr.AssignLiteral("url("); nsStyleUtil::AppendEscapedCSSString(NS_ConvertUTF8toUTF16(specUTF8), tmpStr); tmpStr.AppendLiteral(")"); } else { // XXXldb Any better ideas? It's good to have something that // doesn't parse so that things round-trip "correctly". tmpStr.Assign(NS_LITERAL_STRING("url(invalid-url:)")); } break; } case CSS_ATTR : { tmpStr.AppendLiteral("attr("); tmpStr.Append(mValue.mString); tmpStr.Append(PRUnichar(')')); break; } case CSS_PERCENTAGE : { tmpStr.AppendFloat(mValue.mFloat * 100); tmpStr.Append(PRUnichar('%')); break; } case CSS_NUMBER : { tmpStr.AppendFloat(mValue.mFloat); break; } case CSS_RECT : { NS_ASSERTION(mValue.mRect, "mValue.mRect should never be null"); NS_NAMED_LITERAL_STRING(comma, ", "); nsCOMPtr<nsIDOMCSSPrimitiveValue> sideCSSValue; nsAutoString sideValue; tmpStr.AssignLiteral("rect("); // get the top result = mValue.mRect->GetTop(getter_AddRefs(sideCSSValue)); if (NS_FAILED(result)) break; result = sideCSSValue->GetCssText(sideValue); if (NS_FAILED(result)) break; tmpStr.Append(sideValue + comma); // get the right result = mValue.mRect->GetRight(getter_AddRefs(sideCSSValue)); if (NS_FAILED(result)) break; result = sideCSSValue->GetCssText(sideValue); if (NS_FAILED(result)) break; tmpStr.Append(sideValue + comma); // get the bottom result = mValue.mRect->GetBottom(getter_AddRefs(sideCSSValue)); if (NS_FAILED(result)) break; result = sideCSSValue->GetCssText(sideValue); if (NS_FAILED(result)) break; tmpStr.Append(sideValue + comma); // get the left result = mValue.mRect->GetLeft(getter_AddRefs(sideCSSValue)); if (NS_FAILED(result)) break; result = sideCSSValue->GetCssText(sideValue); if (NS_FAILED(result)) break; tmpStr.Append(sideValue + NS_LITERAL_STRING(")")); break; } case CSS_RGBCOLOR : { NS_ASSERTION(mValue.mColor, "mValue.mColor should never be null"); NS_NAMED_LITERAL_STRING(comma, ", "); nsCOMPtr<nsIDOMCSSPrimitiveValue> colorCSSValue; nsAutoString colorValue; if (mValue.mColor->HasAlpha()) tmpStr.AssignLiteral("rgba("); else tmpStr.AssignLiteral("rgb("); // get the red component result = mValue.mColor->GetRed(getter_AddRefs(colorCSSValue)); if (NS_FAILED(result)) break; result = colorCSSValue->GetCssText(colorValue); if (NS_FAILED(result)) break; tmpStr.Append(colorValue + comma); // get the green component result = mValue.mColor->GetGreen(getter_AddRefs(colorCSSValue)); if (NS_FAILED(result)) break; result = colorCSSValue->GetCssText(colorValue); if (NS_FAILED(result)) break; tmpStr.Append(colorValue + comma); // get the blue component result = mValue.mColor->GetBlue(getter_AddRefs(colorCSSValue)); if (NS_FAILED(result)) break; result = colorCSSValue->GetCssText(colorValue); if (NS_FAILED(result)) break; tmpStr.Append(colorValue); if (mValue.mColor->HasAlpha()) { // get the alpha component result = mValue.mColor->GetAlpha(getter_AddRefs(colorCSSValue)); if (NS_FAILED(result)) break; result = colorCSSValue->GetCssText(colorValue); if (NS_FAILED(result)) break; tmpStr.Append(comma + colorValue); } tmpStr.Append(NS_LITERAL_STRING(")")); break; } case CSS_S : { tmpStr.AppendFloat(mValue.mFloat); tmpStr.AppendLiteral("s"); break; } case CSS_CM : case CSS_MM : case CSS_IN : case CSS_PT : case CSS_PC : case CSS_UNKNOWN : case CSS_EMS : case CSS_EXS : case CSS_DEG : case CSS_RAD : case CSS_GRAD : case CSS_MS : case CSS_HZ : case CSS_KHZ : case CSS_DIMENSION : NS_ERROR("We have a bogus value set. This should not happen"); return NS_ERROR_DOM_INVALID_ACCESS_ERR; } if (NS_SUCCEEDED(result)) { aCssText.Assign(tmpStr); } return NS_OK; }
NS_IMETHODIMP ChangeCSSInlineStyleTxn::DoTransaction(void) { NS_ASSERTION(mEditor && mElement, "bad state"); if (!mEditor || !mElement) { return NS_ERROR_NOT_INITIALIZED; } nsCOMPtr<nsIDOMElementCSSInlineStyle> inlineStyles = do_QueryInterface(mElement); NS_ENSURE_TRUE(inlineStyles, NS_ERROR_NULL_POINTER); nsCOMPtr<nsIDOMCSSStyleDeclaration> cssDecl; nsresult result = inlineStyles->GetStyle(getter_AddRefs(cssDecl)); NS_ENSURE_SUCCESS(result, result); NS_ENSURE_TRUE(cssDecl, NS_ERROR_NULL_POINTER); nsAutoString propertyNameString; mProperty->ToString(propertyNameString); NS_NAMED_LITERAL_STRING(styleAttr, "style"); result = mElement->HasAttribute(styleAttr, &mUndoAttributeWasSet); NS_ENSURE_SUCCESS(result, result); nsAutoString values; result = cssDecl->GetPropertyValue(propertyNameString, values); NS_ENSURE_SUCCESS(result, result); mUndoValue.Assign(values); // does this property accept more than 1 value ? // we need to know that because of bug 62682 bool multiple = AcceptsMoreThanOneValue(mProperty); if (mRemoveProperty) { nsAutoString returnString; if (multiple) { // the property can have more than one value, let's remove only // the value we have to remove and not the others // the 2 lines below are a workaround because nsDOMCSSDeclaration::GetPropertyCSSValue // is not yet implemented (bug 62682) RemoveValueFromListOfValues(values, NS_LITERAL_STRING("none")); RemoveValueFromListOfValues(values, mValue); if (values.IsEmpty()) { result = cssDecl->RemoveProperty(propertyNameString, returnString); NS_ENSURE_SUCCESS(result, result); } else { nsAutoString priority; result = cssDecl->GetPropertyPriority(propertyNameString, priority); NS_ENSURE_SUCCESS(result, result); result = cssDecl->SetProperty(propertyNameString, values, priority); NS_ENSURE_SUCCESS(result, result); } } else { result = cssDecl->RemoveProperty(propertyNameString, returnString); NS_ENSURE_SUCCESS(result, result); } } else { nsAutoString priority; result = cssDecl->GetPropertyPriority(propertyNameString, priority); NS_ENSURE_SUCCESS(result, result); if (multiple) { // the property can have more than one value, let's add // the value we have to add to the others // the line below is a workaround because nsDOMCSSDeclaration::GetPropertyCSSValue // is not yet implemented (bug 62682) AddValueToMultivalueProperty(values, mValue); } else values.Assign(mValue); result = cssDecl->SetProperty(propertyNameString, values, priority); NS_ENSURE_SUCCESS(result, result); } // let's be sure we don't keep an empty style attribute PRUint32 length; result = cssDecl->GetLength(&length); NS_ENSURE_SUCCESS(result, result); if (!length) { result = mElement->RemoveAttribute(styleAttr); NS_ENSURE_SUCCESS(result, result); } else mRedoAttributeWasSet = true; return cssDecl->GetPropertyValue(propertyNameString, mRedoValue); }
already_AddRefed<Promise> ServiceWorkerContainer::Register(const nsAString& aScriptURL, const RegistrationOptions& aOptions, ErrorResult& aRv) { nsCOMPtr<nsISupports> promise; nsCOMPtr<nsIServiceWorkerManager> swm = mozilla::services::GetServiceWorkerManager(); if (!swm) { aRv.Throw(NS_ERROR_FAILURE); return nullptr; } nsCOMPtr<nsIURI> baseURI; nsIDocument* doc = GetEntryDocument(); if (doc) { baseURI = doc->GetBaseURI(); } else { // XXXnsm. One of our devtools browser test calls register() from a content // script where there is no valid entry document. Use the window to resolve // the uri in that case. nsCOMPtr<nsPIDOMWindow> window = GetOwner(); nsCOMPtr<nsPIDOMWindow> outerWindow; if (window && (outerWindow = window->GetOuterWindow()) && outerWindow->GetServiceWorkersTestingEnabled()) { baseURI = window->GetDocBaseURI(); } } nsresult rv; nsCOMPtr<nsIURI> scriptURI; rv = NS_NewURI(getter_AddRefs(scriptURI), aScriptURL, nullptr, baseURI); if (NS_WARN_IF(NS_FAILED(rv))) { aRv.ThrowTypeError<MSG_INVALID_URL>(&aScriptURL); return nullptr; } aRv = CheckForSlashEscapedCharsInPath(scriptURI); if (NS_WARN_IF(aRv.Failed())) { return nullptr; } // In ServiceWorkerContainer.register() the scope argument is parsed against // different base URLs depending on whether it was passed or not. nsCOMPtr<nsIURI> scopeURI; // Step 4. If none passed, parse against script's URL if (!aOptions.mScope.WasPassed()) { NS_NAMED_LITERAL_STRING(defaultScope, "./"); rv = NS_NewURI(getter_AddRefs(scopeURI), defaultScope, nullptr, scriptURI); if (NS_WARN_IF(NS_FAILED(rv))) { nsAutoCString spec; scriptURI->GetSpec(spec); NS_ConvertUTF8toUTF16 wSpec(spec); aRv.ThrowTypeError<MSG_INVALID_SCOPE>(&defaultScope, &wSpec); return nullptr; } } else { // Step 5. Parse against entry settings object's base URL. rv = NS_NewURI(getter_AddRefs(scopeURI), aOptions.mScope.Value(), nullptr, baseURI); if (NS_WARN_IF(NS_FAILED(rv))) { nsAutoCString spec; baseURI->GetSpec(spec); NS_ConvertUTF8toUTF16 wSpec(spec); aRv.ThrowTypeError<MSG_INVALID_SCOPE>(&aOptions.mScope.Value(), &wSpec); return nullptr; } aRv = CheckForSlashEscapedCharsInPath(scopeURI); if (NS_WARN_IF(aRv.Failed())) { return nullptr; } } // The spec says that the "client" passed to Register() must be the global // where the ServiceWorkerContainer was retrieved from. aRv = swm->Register(GetOwner(), scopeURI, scriptURI, getter_AddRefs(promise)); if (NS_WARN_IF(aRv.Failed())) { return nullptr; } RefPtr<Promise> ret = static_cast<Promise*>(promise.get()); MOZ_ASSERT(ret); return ret.forget(); }
void nsScriptPaginator::AdjustNextPageBreak () { NS_NAMED_LITERAL_STRING(kClassStr, "class"); NS_NAMED_LITERAL_STRING(kSoftBreakStr, "softbreak"); NS_NAMED_LITERAL_STRING(kHardBreakStr, "hardbreak"); NS_NAMED_LITERAL_STRING(kActStr, "act"); NS_NAMED_LITERAL_STRING(kDivStr, "div"); // Allow an extra line per page to accommodate bottom margins const PRInt32 kPageHeight = PRInt32(mLineHeight * (mLinesPerPage + 1)); nsCOMPtr<nsIDOMNode> node = mNextPageStartsAt; if (! node) { nsCOMPtr<nsIDOMHTMLDocument> hdoc(do_QueryInterface(mScript)); nsCOMPtr<nsIDOMHTMLElement> body; hdoc->GetBody(getter_AddRefs(body)); if (! body) { return; } body->GetFirstChild(getter_AddRefs(node)); mCurPageBreakNum = 0; if (! node) { return; } } nsCOMPtr<nsIDOMNSHTMLElement> element(do_QueryInterface(node)); if (! element) return; PRInt32 offset = 0; element->GetOffsetTop(&offset); PRUint32 pageEnd = PRUint32(offset + kPageHeight); nsCOMPtr<nsIDOMNSHTMLElement> innerBreak(nsnull); // Adjust for height of page break if we start at one nsString className; { nsCOMPtr<nsIDOMElement> elemnode(do_QueryInterface(node)); elemnode->GetAttribute(kClassStr, className); if (className.Equals(kSoftBreakStr) || className.Equals(kHardBreakStr)) { PRInt32 height; element->GetClientHeight(&height); pageEnd += height; } } // Basic strategy: // 1. Get the next node // 2. If the next node is undefined // 2.1. If the page break cache extends further // 2.1.1. Splice the remaining page breaks // 2.2. Exit // 3. Else if the next node is a hard break (or act) // 3.1. Advance the page cursor // 3.2. Exit // 4. Else if the next node is a soft break // 4.1. If a soft break is cached as |innerBreak| // 4.1.1. Remove |innerBreak| // 4.2. Cache the node as |innerBreak| // 5. Else if the node does not fit the page // 5.1. Find the last node (inclusive) that allows a break before it // 5.2. If a soft break is cached as |innerBreak| // 5.2.1. If |innerBreak| occurs as the previous sibling to the last node // 5.2.1.1. Advance the page cursor // 5.2.1.2. Exit // 5.2.2. Else // 5.2.2.1. Remove |innerBreak| // 5.2.2.2. Insert a new soft page break // 5.2.2.3. Advance the page cursor // 5.2.2.4. Exit // 5.3. Else // 5.3.1. Insert a new soft page break // 5.3.2. Advance the page cursor // 5.3.3. Exit // 6. Else // 6.1. Continue nsCOMPtr<nsIDOMNode> tmpnode; PRUint16 nodeType = 0; nsCOMPtr<nsIDOMNode> elemnode(do_QueryInterface(element)); elemnode->GetNextSibling(getter_AddRefs(tmpnode)); if (tmpnode) tmpnode->GetNodeType(&nodeType); while (tmpnode && nodeType != nsIDOMNode::ELEMENT_NODE) { nsCOMPtr<nsIDOMNode> tmpnode2; tmpnode->GetNextSibling(getter_AddRefs(tmpnode2)); tmpnode = tmpnode2; if (tmpnode) tmpnode->GetNodeType(&nodeType); } if (tmpnode) element = do_QueryInterface(tmpnode); else element = nsnull; while (element) { nsCOMPtr<nsIDOMElement> elemnode(do_QueryInterface(element)); elemnode->GetAttribute(kClassStr, className); element->GetOffsetTop(&offset); // If it's an act, make sure it's got a page break before it, unless // it's the first element in the script. if (className.Equals(kActStr)) { // Get the previous element to this act that isn't a page break elemnode->GetPreviousSibling(getter_AddRefs(tmpnode)); /* if (tmpnode) tmpnode->GetNodeType(&nodeType); while (tmpnode && nodeType != nsIDOMNode::ELEMENT_NODE) { nsCOMPtr<nsIDOMNode> tmpnode2; tmpnode->GetPreviousSibling(getter_AddRefs(tmpnode2)); tmpnode = tmpnode2; if (tmpnode) tmpnode->GetNodeType(&nodeType); } */ while (tmpnode) { nsCOMPtr<nsIDOMHTMLParagraphElement> para(do_QueryInterface(tmpnode)); if (para) break; nsCOMPtr<nsIDOMNode> tmpnode2; tmpnode->GetPreviousSibling(getter_AddRefs(tmpnode2)); tmpnode = tmpnode2; } nsCOMPtr<nsIDOMElement> prev(do_QueryInterface(tmpnode)); // If no previous element, then this isn't important if (prev) { // Otherwise, make sure the act is preceded by a page break prev->GetAttribute(kClassStr, className); if (! className.Equals(kSoftBreakStr) && ! className.Equals(kHardBreakStr)) { // Make a break! nsCOMPtr<nsIDOMElement> breaknode; mScript->CreateElement(kDivStr, getter_AddRefs(breaknode)); prev = do_QueryInterface(breaknode); prev->SetAttribute(kClassStr, kSoftBreakStr); nsCOMPtr<nsIDOMText> text; mScript->CreateTextNode(NS_LITERAL_STRING(" "), getter_AddRefs(text)); nsCOMPtr<nsIDOMNode> dummy; prev->AppendChild(text, getter_AddRefs(dummy)); nsCOMPtr<nsIDOMNode> parent; elemnode->GetParentNode(getter_AddRefs(parent)); parent->InsertBefore(prev, elemnode, getter_AddRefs(dummy)); } nsCOMPtr<nsIDOMNSHTMLElement> htmlprev(do_QueryInterface(prev)); htmlprev->GetOffsetTop(&offset); if (mCurPageBreakNum >= mPageBreakOffsets.Length()) mPageBreakOffsets.AppendElement((PRUint32) offset); else mPageBreakOffsets[mCurPageBreakNum] = (PRUint32) offset; ++mCurPageBreakNum; mNextPageStartsAt = do_QueryInterface(element); return; } } // Hard breaks don't move. Just record the offset and keep going. if (className.Equals(kHardBreakStr)) { element->GetOffsetTop(&offset); if (mCurPageBreakNum >= mPageBreakOffsets.Length()) mPageBreakOffsets.AppendElement(offset); else mPageBreakOffsets[mCurPageBreakNum] = offset; ++mCurPageBreakNum; mNextPageStartsAt = do_QueryInterface(element); return; } element->GetOffsetTop(&offset); PRInt32 height; element->GetClientHeight(&height); if (className.Equals(kSoftBreakStr)) { // Soft break! Make sure it's in the right position, and eliminate // or move up any preceding soft break that isn't necessary. if (innerBreak) { // Remove the last inner break, and make this one the new inner // break. No need to adjust pageEnd, because the removed page break // balances the current page break. nsCOMPtr<nsIDOMNode> parent; nsCOMPtr<nsIDOMNode> innernode(do_QueryInterface(innerBreak)); nsCOMPtr<nsIDOMNode> dummy; innernode->GetParentNode(getter_AddRefs(parent)); parent->RemoveChild(innernode, getter_AddRefs(dummy)); } else { elemnode->GetNextSibling(getter_AddRefs(tmpnode)); if (tmpnode) tmpnode->GetNodeType(&nodeType); while (tmpnode && nodeType != nsIDOMNode::ELEMENT_NODE) { nsCOMPtr<nsIDOMNode> tmpnode2; tmpnode->GetNextSibling(getter_AddRefs(tmpnode2)); tmpnode = tmpnode2; if (tmpnode) tmpnode->GetNodeType(&nodeType); } if (tmpnode) { nsCOMPtr<nsIDOMNSHTMLElement> next(do_QueryInterface(tmpnode)); PRInt32 nextOffset = 0; next->GetOffsetTop(&nextOffset); // pageEnd += PRUint32(nextOffset - offset); } } innerBreak = element; } else if (PRUint32(offset + height) > pageEnd) { // Not a soft break, but it exceeds the page length so // we need to paginate. // If we can't break here, rewind until we reach a node where we can. tmpnode = do_QueryInterface(element); while (! CanBreakBeforeNode(tmpnode) && tmpnode != mNextPageStartsAt) { nsCOMPtr<nsIDOMNode> prev; tmpnode->GetPreviousSibling(getter_AddRefs(prev)); if (! prev) break; prev->GetNodeType(&nodeType); while (prev && nodeType != nsIDOMNode::ELEMENT_NODE) { nsCOMPtr<nsIDOMNode> tmpnode2; prev->GetPreviousSibling(getter_AddRefs(tmpnode2)); if (tmpnode2) tmpnode2->GetNodeType(&nodeType); prev = tmpnode2; } tmpnode = prev; } // If |tmpnode| == |mNextPageStartsAt|, we've backtracked to the // previous page. This generally happens when an element is too big // to fit on the page. Until we can break long elements in half, keep // going forward until the next opportunity to insert a break. if (tmpnode == mNextPageStartsAt) { // Set |element| to the next element elemnode->GetNextSibling(getter_AddRefs(tmpnode)); if (tmpnode) tmpnode->GetNodeType(&nodeType); while (tmpnode && nodeType != nsIDOMNode::ELEMENT_NODE) { nsCOMPtr<nsIDOMNode> tmpnode2; tmpnode->GetNextSibling(getter_AddRefs(tmpnode2)); tmpnode = tmpnode2; if (tmpnode) tmpnode->GetNodeType(&nodeType); } if (tmpnode) element = do_QueryInterface(tmpnode); else element = nsnull; continue; } if (innerBreak) { // Move up the inner break to the current position (unless it's // already the previous element) nsCOMPtr<nsIDOMNode> prev; tmpnode->GetPreviousSibling(getter_AddRefs(prev)); if (! prev) break; prev->GetNodeType(&nodeType); while (prev && nodeType != nsIDOMNode::ELEMENT_NODE) { nsCOMPtr<nsIDOMNode> tmpnode2; prev->GetPreviousSibling(getter_AddRefs(tmpnode2)); if (tmpnode2) tmpnode2->GetNodeType(&nodeType); prev = tmpnode2; } nsCOMPtr<nsIDOMNode> innernode(do_QueryInterface(innerBreak)); if (prev != innernode) { nsCOMPtr<nsIDOMNode> parent; tmpnode->GetParentNode(getter_AddRefs(parent)); nsCOMPtr<nsIDOMNode> dummy; parent->InsertBefore(innernode, tmpnode, getter_AddRefs(dummy)); } } else { nsCOMPtr<nsIDOMElement> pagebreak; mScript->CreateElement(kDivStr, getter_AddRefs(pagebreak)); pagebreak->SetAttribute(kClassStr, kSoftBreakStr); nsCOMPtr<nsIDOMText> text; nsCOMPtr<nsIDOMNode> dummy; mScript->CreateTextNode(NS_LITERAL_STRING(" "), getter_AddRefs(text)); pagebreak->AppendChild(text, getter_AddRefs(dummy)); nsCOMPtr<nsIDOMNode> parent; tmpnode->GetParentNode(getter_AddRefs(parent)); parent->InsertBefore(pagebreak, tmpnode, getter_AddRefs(dummy)); innerBreak = do_QueryInterface(pagebreak); } innerBreak->GetOffsetTop(&offset); if (mCurPageBreakNum >= mPageBreakOffsets.Length()) mPageBreakOffsets.AppendElement(offset); else mPageBreakOffsets[mCurPageBreakNum] = offset; ++mCurPageBreakNum; mNextPageStartsAt = tmpnode; return; } // set |element| to the next element // Man does XPCOM make some conventions difficult! e.g., expressing // while (element = element.nextSibling && element.nodeType != ...) elemnode->GetNextSibling(getter_AddRefs(tmpnode)); if (tmpnode) tmpnode->GetNodeType(&nodeType); while (tmpnode && nodeType != nsIDOMNode::ELEMENT_NODE) { nsCOMPtr<nsIDOMNode> tmpnode2; tmpnode->GetNextSibling(getter_AddRefs(tmpnode2)); tmpnode = tmpnode2; if (tmpnode) tmpnode->GetNodeType(&nodeType); } if (tmpnode) element = do_QueryInterface(tmpnode); else element = nsnull; } // This should be guaranteed if (! element) { // Strip away any remaining page break offsets if (mPageBreakOffsets.Length() > 0 && mPageBreakOffsets.Length() > mCurPageBreakNum + 1) { mPageBreakOffsets.SetLength(mCurPageBreakNum + 1); } if (innerBreak) { nsCOMPtr<nsIDOMNode> parent; nsCOMPtr<nsIDOMNode> innernode(do_QueryInterface(innerBreak)); nsCOMPtr<nsIDOMNode> dummy; innernode->GetParentNode(getter_AddRefs(parent)); parent->RemoveChild(innernode, getter_AddRefs(dummy)); } mNextPageStartsAt = nsnull; } }
nsresult PluginDocument::CreateSyntheticPluginDocument() { NS_ASSERTION(!GetShell() || !GetShell()->DidInitialReflow(), "Creating synthetic plugin document content too late"); // make our generic document nsresult rv = MediaDocument::CreateSyntheticDocument(); NS_ENSURE_SUCCESS(rv, rv); // then attach our plugin Element* body = GetBodyElement(); if (!body) { NS_WARNING("no body on plugin document!"); return NS_ERROR_FAILURE; } // remove margins from body NS_NAMED_LITERAL_STRING(zero, "0"); body->SetAttr(kNameSpaceID_None, nsGkAtoms::marginwidth, zero, PR_FALSE); body->SetAttr(kNameSpaceID_None, nsGkAtoms::marginheight, zero, PR_FALSE); // make plugin content nsCOMPtr<nsINodeInfo> nodeInfo; nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::embed, nsnull, kNameSpaceID_XHTML, nsIDOMNode::ELEMENT_NODE); NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY); rv = NS_NewHTMLElement(getter_AddRefs(mPluginContent), nodeInfo.forget(), NOT_FROM_PARSER); NS_ENSURE_SUCCESS(rv, rv); // make it a named element mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::name, NS_LITERAL_STRING("plugin"), PR_FALSE); // fill viewport and auto-resize NS_NAMED_LITERAL_STRING(percent100, "100%"); mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::width, percent100, PR_FALSE); mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::height, percent100, PR_FALSE); // set URL nsCAutoString src; mDocumentURI->GetSpec(src); mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::src, NS_ConvertUTF8toUTF16(src), PR_FALSE); // set mime type mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::type, NS_ConvertUTF8toUTF16(mMimeType), PR_FALSE); // This will not start the load because nsObjectLoadingContent checks whether // its document is an nsIPluginDocument body->AppendChildTo(mPluginContent, PR_FALSE); return NS_OK; }
// init this interface to a specified locale nsresult nsDateTimeFormatUnix::Initialize(nsILocale* locale) { nsAutoString localeStr; NS_NAMED_LITERAL_STRING(aCategory, "NSILOCALE_TIME##PLATFORM"); nsresult res = NS_OK; // use cached info if match with stored locale if (!locale) { if (!mLocale.IsEmpty() && mLocale.Equals(mAppLocale, nsCaseInsensitiveStringComparator())) { return NS_OK; } } else { res = locale->GetCategory(aCategory, localeStr); if (NS_SUCCEEDED(res) && !localeStr.IsEmpty()) { if (!mLocale.IsEmpty() && mLocale.Equals(localeStr, nsCaseInsensitiveStringComparator())) { return NS_OK; } } } mCharset.AssignLiteral("ISO-8859-1"); mPlatformLocale.Assign("en_US"); // get locale name string, use app default if no locale specified if (!locale) { nsCOMPtr<nsILocaleService> localeService = do_GetService(NS_LOCALESERVICE_CONTRACTID, &res); if (NS_SUCCEEDED(res)) { nsCOMPtr<nsILocale> appLocale; res = localeService->GetApplicationLocale(getter_AddRefs(appLocale)); if (NS_SUCCEEDED(res)) { res = appLocale->GetCategory(aCategory, localeStr); if (NS_SUCCEEDED(res) && !localeStr.IsEmpty()) { NS_ASSERTION(NS_SUCCEEDED(res), "failed to get app locale info"); mAppLocale = localeStr; // cache app locale name } } } } else { res = locale->GetCategory(aCategory, localeStr); NS_ASSERTION(NS_SUCCEEDED(res), "failed to get locale info"); } if (NS_SUCCEEDED(res) && !localeStr.IsEmpty()) { mLocale = localeStr; // cache locale name nsPosixLocale::GetPlatformLocale(mLocale, mPlatformLocale); nsCOMPtr <nsIPlatformCharset> platformCharset = do_GetService(NS_PLATFORMCHARSET_CONTRACTID, &res); if (NS_SUCCEEDED(res)) { nsAutoCString mappedCharset; res = platformCharset->GetDefaultCharsetForLocale(mLocale, mappedCharset); if (NS_SUCCEEDED(res)) { mCharset = mappedCharset; } } } // Initialize unicode decoder nsCOMPtr <nsICharsetConverterManager> charsetConverterManager; charsetConverterManager = do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID, &res); if (NS_SUCCEEDED(res)) { res = charsetConverterManager->GetUnicodeDecoder(mCharset.get(), getter_AddRefs(mDecoder)); } LocalePreferred24hour(); return res; }
nsresult nsProfileLock::Lock(nsIFile* aProfileDir, nsIProfileUnlocker* *aUnlocker) { #if defined (XP_MACOSX) NS_NAMED_LITERAL_STRING(LOCKFILE_NAME, ".parentlock"); NS_NAMED_LITERAL_STRING(OLD_LOCKFILE_NAME, "parent.lock"); #elif defined (XP_UNIX) NS_NAMED_LITERAL_STRING(OLD_LOCKFILE_NAME, "lock"); NS_NAMED_LITERAL_STRING(LOCKFILE_NAME, ".parentlock"); #else NS_NAMED_LITERAL_STRING(LOCKFILE_NAME, "parent.lock"); #endif nsresult rv; if (aUnlocker) *aUnlocker = nullptr; NS_ENSURE_STATE(!mHaveLock); bool isDir; rv = aProfileDir->IsDirectory(&isDir); if (NS_FAILED(rv)) return rv; if (!isDir) return NS_ERROR_FILE_NOT_DIRECTORY; nsCOMPtr<nsIFile> lockFile; rv = aProfileDir->Clone(getter_AddRefs(lockFile)); if (NS_FAILED(rv)) return rv; rv = lockFile->Append(LOCKFILE_NAME); if (NS_FAILED(rv)) return rv; #if defined(XP_MACOSX) // First, try locking using fcntl. It is more reliable on // a local machine, but may not be supported by an NFS server. rv = LockWithFcntl(lockFile); if (NS_FAILED(rv) && (rv != NS_ERROR_FILE_ACCESS_DENIED)) { // If that failed for any reason other than NS_ERROR_FILE_ACCESS_DENIED, // assume we tried an NFS that does not support it. Now, try with symlink. rv = LockWithSymlink(lockFile, false); } if (NS_SUCCEEDED(rv)) { // Check for the old-style lock used by pre-mozilla 1.3 builds. // Those builds used an earlier check to prevent the application // from launching if another instance was already running. Because // of that, we don't need to create an old-style lock as well. struct LockProcessInfo { ProcessSerialNumber psn; unsigned long launchDate; }; PRFileDesc *fd = nullptr; int32_t ioBytes; ProcessInfoRec processInfo; LockProcessInfo lockProcessInfo; rv = lockFile->SetLeafName(OLD_LOCKFILE_NAME); if (NS_FAILED(rv)) return rv; rv = lockFile->OpenNSPRFileDesc(PR_RDONLY, 0, &fd); if (NS_SUCCEEDED(rv)) { ioBytes = PR_Read(fd, &lockProcessInfo, sizeof(LockProcessInfo)); PR_Close(fd); if (ioBytes == sizeof(LockProcessInfo)) { #ifdef __LP64__ processInfo.processAppRef = nullptr; #else processInfo.processAppSpec = nullptr; #endif processInfo.processName = nullptr; processInfo.processInfoLength = sizeof(ProcessInfoRec); if (::GetProcessInformation(&lockProcessInfo.psn, &processInfo) == noErr && processInfo.processLaunchDate == lockProcessInfo.launchDate) { return NS_ERROR_FILE_ACCESS_DENIED; } } else { NS_WARNING("Could not read lock file - ignoring lock"); } } rv = NS_OK; // Don't propagate error from OpenNSPRFileDesc. } #elif defined(XP_UNIX) // Get the old lockfile name nsCOMPtr<nsIFile> oldLockFile; rv = aProfileDir->Clone(getter_AddRefs(oldLockFile)); if (NS_FAILED(rv)) return rv; rv = oldLockFile->Append(OLD_LOCKFILE_NAME); if (NS_FAILED(rv)) return rv; // First, try locking using fcntl. It is more reliable on // a local machine, but may not be supported by an NFS server. rv = LockWithFcntl(lockFile); if (NS_SUCCEEDED(rv)) { // Check to see whether there is a symlink lock held by an older // Firefox build, and also place our own symlink lock --- but // mark it "obsolete" so that other newer builds can break the lock // if they obtain the fcntl lock rv = LockWithSymlink(oldLockFile, true); // If the symlink failed for some reason other than it already // exists, then something went wrong e.g. the file system // doesn't support symlinks, or we don't have permission to // create a symlink there. In such cases we should just // continue because it's unlikely there is an old build // running with a symlink there and we've already successfully // placed a fcntl lock. if (rv != NS_ERROR_FILE_ACCESS_DENIED) rv = NS_OK; } else if (rv != NS_ERROR_FILE_ACCESS_DENIED) { // If that failed for any reason other than NS_ERROR_FILE_ACCESS_DENIED, // assume we tried an NFS that does not support it. Now, try with symlink // using the old symlink path rv = LockWithSymlink(oldLockFile, false); } #elif defined(XP_WIN) nsAutoString filePath; rv = lockFile->GetPath(filePath); if (NS_FAILED(rv)) return rv; lockFile->GetLastModifiedTime(&mReplacedLockTime); // always create the profile lock and never delete it so we can use its // modification timestamp to detect startup crashes mLockFileHandle = CreateFileW(filePath.get(), GENERIC_READ | GENERIC_WRITE, 0, // no sharing - of course nullptr, CREATE_ALWAYS, 0, nullptr); if (mLockFileHandle == INVALID_HANDLE_VALUE) { if (aUnlocker) { RefPtr<mozilla::ProfileUnlockerWin> unlocker( new mozilla::ProfileUnlockerWin(filePath)); if (NS_SUCCEEDED(unlocker->Init())) { nsCOMPtr<nsIProfileUnlocker> unlockerInterface( do_QueryObject(unlocker)); unlockerInterface.forget(aUnlocker); } } return NS_ERROR_FILE_ACCESS_DENIED; } #elif defined(XP_OS2) nsAutoCString filePath; rv = lockFile->GetNativePath(filePath); if (NS_FAILED(rv)) return rv; lockFile->GetLastModifiedTime(&mReplacedLockTime); ULONG ulAction = 0; APIRET rc; rc = DosOpen(filePath.get(), &mLockFileHandle, &ulAction, 0, FILE_NORMAL, OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS, OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYREADWRITE | OPEN_FLAGS_NOINHERIT, 0 ); if (rc != NO_ERROR) { mLockFileHandle = -1; return NS_ERROR_FILE_ACCESS_DENIED; } #elif defined(VMS) nsAutoCString filePath; rv = lockFile->GetNativePath(filePath); if (NS_FAILED(rv)) return rv; lockFile->GetLastModifiedTime(&mReplacedLockTime); mLockFileDesc = open_noshr(filePath.get(), O_CREAT, 0666); if (mLockFileDesc == -1) { if ((errno == EVMSERR) && (vaxc$errno == RMS$_FLK)) { return NS_ERROR_FILE_ACCESS_DENIED; } else { NS_ERROR("Failed to open lock file."); return NS_ERROR_FAILURE; } } #endif mHaveLock = true; return rv; }
/* wstring getAcceptLangFromLocale (in wstring aLocale); */ NS_IMETHODIMP nsAcceptLang::GetAcceptLangFromLocale(const PRUnichar *aLocale, PRUnichar **_retval) { nsDependentString lc_name(aLocale); if (lc_name.Length() <=0) { #ifdef DEBUG printf("nsAcceptLang::GetAcceptLangFromLocale: aLocale is empty!"); #endif // TODO: don't return; instead, use system locale: lc_name=... return NS_ERROR_FAILURE; } nsresult res; nsCOMPtr<nsIStringBundleService> sBundleService = do_GetService(kStringBundleServiceCID, &res); if (NS_FAILED(res) || (nsnull == sBundleService)) { return NS_ERROR_FAILURE; } nsCOMPtr<nsIStringBundle> bundle; #if 1 res = sBundleService->CreateBundle("resource://gre/res/language.properties", getter_AddRefs(bundle)); #else res = sBundleService->CreateBundle("chrome://global/locale/languageNames.properties", getter_AddRefs(bundle)); #endif PRUnichar *ptrv = nsnull; nsAutoString lc_tmp(aLocale); NS_NAMED_LITERAL_STRING(sAccept, ".accept"); NS_NAMED_LITERAL_STRING(sTrue, "true"); ToLowerCase(lc_tmp); lc_tmp.Append(sAccept); if (NS_OK == (res = bundle->GetStringFromName(lc_tmp.get(), &ptrv))) { if (sTrue.Equals(ptrv)) { // valid name already *_retval = ToNewUnicode(lc_name); return res; } } /* not in languageNames.properties; lang only? */ PRInt32 dash = lc_tmp.FindChar('-'); nsAutoString lang; nsAutoString country; if (dash > 0) { /* lang-country */ PRInt32 count = 0; count = lc_tmp.Left(lang, dash); count = lc_tmp.Right(country, (lc_tmp.Length()-dash-1)); /* ja-JP -> ja*/ } else { /* ja ?? en-JP en-JP ->ja (how about product locale or syste, locale ???) ja-EN ->ja */ lang = lc_name; } // lang always in lower case; don't convert *_retval = ToNewUnicode(lang); lang.Append(sAccept); if (NS_OK == (res = bundle->GetStringFromName(lang.get(), &ptrv))) { if (sTrue.Equals(ptrv)) { /* lang is accepted */ return res; } } /* unsupported lang */ *_retval = nsnull; return NS_ERROR_FAILURE; }
void nsHTMLContentSerializer::SerializeAttributes(nsIContent* aContent, nsIDOMElement *aOriginalElement, nsAString& aTagPrefix, const nsAString& aTagNamespaceURI, nsIAtom* aTagName, nsAString& aStr) { PRInt32 count = aContent->GetAttrCount(); if (!count) return; nsresult rv; nsAutoString nameStr, valueStr; NS_NAMED_LITERAL_STRING(_mozStr, "_moz"); // HTML5 parser stored them in the order they were parsed so we want to // loop forward in that case. nsIDocument* doc = aContent->GetOwnerDocument(); PRBool caseSensitive = doc && doc->IsCaseSensitive(); PRBool loopForward = PR_FALSE; if (!caseSensitive) { nsCOMPtr<nsIHTMLDocument> htmlDoc(do_QueryInterface(doc)); if (htmlDoc) { loopForward = nsHtml5Module::sEnabled; } } PRInt32 index, limit, step; if (loopForward) { index = 0; limit = count; step = 1; } else { // Loop backward over the attributes, since the order they are stored in is // the opposite of the order they were parsed in (see bug 213347 for reason). index = count - 1; limit = -1; step = -1; } for (; index != limit; index += step) { const nsAttrName* name = aContent->GetAttrNameAt(index); PRInt32 namespaceID = name->NamespaceID(); nsIAtom* attrName = name->LocalName(); // Filter out any attribute starting with [-|_]moz const char* sharedName; attrName->GetUTF8String(&sharedName); if ((('_' == *sharedName) || ('-' == *sharedName)) && !nsCRT::strncmp(sharedName+1, kMozStr, PRUint32(sizeof(kMozStr)-1))) { continue; } aContent->GetAttr(namespaceID, attrName, valueStr); // // Filter out special case of <br type="_moz"> or <br _moz*>, // used by the editor. Bug 16988. Yuck. // if (aTagName == nsGkAtoms::br && attrName == nsGkAtoms::type && StringBeginsWith(valueStr, _mozStr)) { continue; } if (mIsCopying && mIsFirstChildOfOL && (aTagName == nsGkAtoms::li) && (attrName == nsGkAtoms::value)){ // This is handled separately in SerializeLIValueAttribute() continue; } PRBool isJS = IsJavaScript(aContent, attrName, namespaceID, valueStr); if (((attrName == nsGkAtoms::href) || (attrName == nsGkAtoms::src))) { // Make all links absolute when converting only the selection: if (mFlags & nsIDocumentEncoder::OutputAbsoluteLinks) { // Would be nice to handle OBJECT and APPLET tags, // but that gets more complicated since we have to // search the tag list for CODEBASE as well. // For now, just leave them relative. nsCOMPtr<nsIURI> uri = aContent->GetBaseURI(); if (uri) { nsAutoString absURI; rv = NS_MakeAbsoluteURI(absURI, valueStr, uri); if (NS_SUCCEEDED(rv)) { valueStr = absURI; } } } // Need to escape URI. nsAutoString tempURI(valueStr); if (!isJS && NS_FAILED(EscapeURI(aContent, tempURI, valueStr))) valueStr = tempURI; } if (mRewriteEncodingDeclaration && aTagName == nsGkAtoms::meta && attrName == nsGkAtoms::content) { // If we're serializing a <meta http-equiv="content-type">, // use the proper value, rather than what's in the document. nsAutoString header; aContent->GetAttr(kNameSpaceID_None, nsGkAtoms::httpEquiv, header); if (header.LowerCaseEqualsLiteral("content-type")) { valueStr = NS_LITERAL_STRING("text/html; charset=") + NS_ConvertASCIItoUTF16(mCharset); } } attrName->ToString(nameStr); // Expand shorthand attribute. if (IsShorthandAttr(attrName, aTagName) && valueStr.IsEmpty()) { valueStr = nameStr; } SerializeAttr(EmptyString(), nameStr, valueStr, aStr, !isJS); } }
/* * Query the font used for various CSS properties (aID) from the system. * For OS/2, only very few fonts are defined in the system, so most of the IDs * resolve to the same system font. * The font queried will give back a string like * 9.WarpSans Bold * 12.Times New Roman Bold Italic * 10.Times New Roman.Strikeout.Underline * 20.Bitstream Vera Sans Mono Obli * (always restricted to 32 chars, at least before the second dot) * We use the value before the dot as the font size (in pt, and convert it to * px using the screen resolution) and then try to use the rest of the string * to determine the font style from it. */ nsresult nsSystemFontsOS2::GetSystemFont(nsSystemFontID aID, nsString* aFontName, gfxFontStyle *aFontStyle) const { #ifdef DEBUG_thebes printf("nsSystemFontsOS2::GetSystemFont: "); #endif char szFontNameSize[MAXNAMEL]; switch (aID) { case eSystemFont_Icon: QueryFontFromINI("IconText", szFontNameSize, MAXNAMEL); #ifdef DEBUG_thebes printf("IconText "); #endif break; case eSystemFont_Menu: QueryFontFromINI("Menus", szFontNameSize, MAXNAMEL); #ifdef DEBUG_thebes printf("Menus "); #endif break; case eSystemFont_Caption: case eSystemFont_MessageBox: case eSystemFont_SmallCaption: case eSystemFont_StatusBar: case eSystemFont_Tooltips: case eSystemFont_Widget: case eSystemFont_Window: // css3 case eSystemFont_Document: case eSystemFont_Workspace: case eSystemFont_Desktop: case eSystemFont_Info: case eSystemFont_Dialog: case eSystemFont_Button: case eSystemFont_PullDownMenu: case eSystemFont_List: case eSystemFont_Field: QueryFontFromINI("WindowText", szFontNameSize, MAXNAMEL); #ifdef DEBUG_thebes printf("WindowText "); #endif break; default: NS_WARNING("None of the listed font types, using WarpSans"); if (!IsDBCS()) { strcpy(szFontNameSize, "9.WarpSans"); } else { strcpy(szFontNameSize, "9.WarpSans Combined"); } } // switch #ifdef DEBUG_thebes printf(" (%s)\n", szFontNameSize); #endif char *szFacename = strchr(szFontNameSize, '.'); if (!szFacename || (*(szFacename++) == '\0')) return NS_ERROR_FAILURE; // local DPI for size will be taken into account below aFontStyle->size = atof(szFontNameSize); // determine DPI resolution of screen device to compare compute // font size in pixels HPS ps = WinGetScreenPS(HWND_DESKTOP); HDC dc = GpiQueryDevice(ps); // effective vertical resolution in DPI LONG vertScreenRes = 120; // assume 120 dpi as default DevQueryCaps(dc, CAPS_VERTICAL_FONT_RES, 1, &vertScreenRes); WinReleasePS(ps); // now scale to make pixels from points (1 pt = 1/72in) aFontStyle->size *= vertScreenRes / 72.0; NS_ConvertUTF8toUTF16 fontFace(szFacename); int pos = 0; // this is a system font in any case aFontStyle->systemFont = true; // bold fonts should have " Bold" in their names, at least we hope that they // do, otherwise it's bad luck NS_NAMED_LITERAL_CSTRING(spcBold, " Bold"); if ((pos = fontFace.Find(spcBold.get(), false, 0, -1)) > -1) { aFontStyle->weight = FONT_WEIGHT_BOLD; // strip the attribute, now that we have set it in the gfxFontStyle fontFace.Cut(pos, spcBold.Length()); } else { aFontStyle->weight = FONT_WEIGHT_NORMAL; } // FIXME: Set aFontStyle->stretch correctly! aFontStyle->stretch = NS_FONT_STRETCH_NORMAL; // similar hopes for italic and oblique fonts... NS_NAMED_LITERAL_CSTRING(spcItalic, " Italic"); NS_NAMED_LITERAL_CSTRING(spcOblique, " Oblique"); NS_NAMED_LITERAL_CSTRING(spcObli, " Obli"); if ((pos = fontFace.Find(spcItalic.get(), false, 0, -1)) > -1) { aFontStyle->style = FONT_STYLE_ITALIC; fontFace.Cut(pos, spcItalic.Length()); } else if ((pos = fontFace.Find(spcOblique.get(), false, 0, -1)) > -1) { // oblique fonts are rare on OS/2 and not specially supported by // the GPI system, but at least we are trying... aFontStyle->style = FONT_STYLE_OBLIQUE; fontFace.Cut(pos, spcOblique.Length()); } else if ((pos = fontFace.Find(spcObli.get(), false, 0, -1)) > -1) { // especially oblique often gets cut by the 32 char limit to "Obli", // so search for that, too (anything shorter would be ambiguous) aFontStyle->style = FONT_STYLE_OBLIQUE; // In this case, assume that this is the last property in the line // and cut off everything else, too // This is needed in case it was really Obliq or Obliqu... fontFace.Cut(pos, fontFace.Length()); } else { aFontStyle->style = FONT_STYLE_NORMAL; } // just throw away any modifiers that are separated by dots (which are either // .Strikeout, .Underline, or .Outline, none of which have a corresponding // gfxFont property) if ((pos = fontFace.Find(".", false, 0, -1)) > -1) { fontFace.Cut(pos, fontFace.Length()); } #ifdef DEBUG_thebes printf(" after=%s\n", NS_LossyConvertUTF16toASCII(fontFace).get()); printf(" style: %s %s %s\n", (aFontStyle->weight == FONT_WEIGHT_BOLD) ? "BOLD" : "", (aFontStyle->style == FONT_STYLE_ITALIC) ? "ITALIC" : "", (aFontStyle->style == FONT_STYLE_OBLIQUE) ? "OBLIQUE" : ""); #endif NS_NAMED_LITERAL_STRING(quote, "\""); // seems like we need quotes around the font name *aFontName = quote + fontFace + quote; return NS_OK; }
nsresult PluginDocument::CreateSyntheticPluginDocument() { NS_ASSERTION(!GetShell() || !GetShell()->DidInitialize(), "Creating synthetic plugin document content too late"); // make our generic document nsresult rv = MediaDocument::CreateSyntheticDocument(); NS_ENSURE_SUCCESS(rv, rv); // then attach our plugin Element* body = GetBodyElement(); if (!body) { NS_WARNING("no body on plugin document!"); return NS_ERROR_FAILURE; } // remove margins from body NS_NAMED_LITERAL_STRING(zero, "0"); body->SetAttr(kNameSpaceID_None, nsGkAtoms::marginwidth, zero, false); body->SetAttr(kNameSpaceID_None, nsGkAtoms::marginheight, zero, false); // make plugin content RefPtr<mozilla::dom::NodeInfo> nodeInfo; nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::embed, nullptr, kNameSpaceID_XHTML, nsIDOMNode::ELEMENT_NODE); rv = NS_NewHTMLElement(getter_AddRefs(mPluginContent), nodeInfo.forget(), NOT_FROM_PARSER); NS_ENSURE_SUCCESS(rv, rv); // make it a named element mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::name, NS_LITERAL_STRING("plugin"), false); // fill viewport and auto-resize NS_NAMED_LITERAL_STRING(percent100, "100%"); mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::width, percent100, false); mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::height, percent100, false); // set URL nsAutoCString src; mDocumentURI->GetSpec(src); mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::src, NS_ConvertUTF8toUTF16(src), false); // set mime type mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::type, NS_ConvertUTF8toUTF16(mMimeType), false); // nsHTML(Shared)ObjectElement does not kick off a load on BindToTree if it is // to a PluginDocument body->AppendChildTo(mPluginContent, false); return NS_OK; }
nsresult sbLocalDatabaseLibraryFactory::InitalizeLibrary(nsIFile* aDatabaseFile, const nsAString &aResourceGUID) { nsresult rv; PRInt32 dbOk; nsCOMPtr<nsIFile> parentDirectory; rv = aDatabaseFile->GetParent(getter_AddRefs(parentDirectory)); NS_ENSURE_SUCCESS(rv, rv); PRBool parentExists; rv = parentDirectory->Exists(&parentExists); NS_ENSURE_SUCCESS(rv, rv); if (!parentExists) { rv = CreateDirectory(parentDirectory); NS_ENSURE_SUCCESS(rv, rv); } PRBool parentIsWritable = IsDirectoryWritable(parentDirectory); NS_ENSURE_TRUE(parentIsWritable, NS_ERROR_FILE_ACCESS_DENIED); // Now that we know we have appropriate permissions make a new query. nsCOMPtr<sbIDatabaseQuery> query = do_CreateInstance(SONGBIRD_DATABASEQUERY_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); rv = query->SetAsyncQuery(PR_FALSE); NS_ENSURE_SUCCESS(rv, rv); rv = SetQueryDatabaseFile(query, aDatabaseFile); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIURI> schemaURI; rv = NS_NewURI(getter_AddRefs(schemaURI), NS_LITERAL_CSTRING(SCHEMA_URL)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIInputStream> input; rv = NS_OpenURI(getter_AddRefs(input), schemaURI); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIConverterInputStream> converterStream = do_CreateInstance("@mozilla.org/intl/converter-input-stream;1", &rv); NS_ENSURE_SUCCESS(rv, rv); rv = converterStream->Init(input, "UTF-8", CONVERTER_BUFFER_SIZE, nsIConverterInputStream:: DEFAULT_REPLACEMENT_CHARACTER); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIUnicharInputStream> unichar = do_QueryInterface(converterStream, &rv); NS_ENSURE_SUCCESS(rv, rv); PRUint32 read; nsString response, result; rv = unichar->ReadString(PR_UINT32_MAX, result, &read); NS_ENSURE_SUCCESS(rv, rv); NS_ASSERTION(read, "Schema file zero bytes?"); while (read > 0) { response.Append(result); rv = unichar->ReadString(PR_UINT32_MAX, result, &read); NS_ENSURE_SUCCESS(rv, rv); } rv = unichar->Close(); NS_ENSURE_SUCCESS(rv, rv); NS_NAMED_LITERAL_STRING(colonNewline, ";\n"); PRInt32 posStart = 0; PRInt32 posEnd = response.Find(colonNewline, posStart); while (posEnd >= 0) { rv = query->AddQuery(Substring(response, posStart, posEnd - posStart)); NS_ENSURE_SUCCESS(rv, rv); posStart = posEnd + 2; posEnd = response.Find(colonNewline, posStart); } rv = query->Execute(&dbOk); NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_TRUE(dbOk == 0, NS_ERROR_FAILURE); nsString guid(aResourceGUID); if(guid.IsEmpty()) { // Create a resource guid for this database. nsCOMPtr<nsIUUIDGenerator> uuidGen = do_GetService("@mozilla.org/uuid-generator;1", &rv); NS_ENSURE_SUCCESS(rv, rv); nsID id; rv = uuidGen->GenerateUUIDInPlace(&id); NS_ENSURE_SUCCESS(rv, rv); char guidChars[NSID_LENGTH]; id.ToProvidedString(guidChars); guid = NS_ConvertASCIItoUTF16(nsDependentCString(guidChars + 1, NSID_LENGTH - 3)); } // Insert the guid into the database. nsCOMPtr<sbISQLInsertBuilder> insert = do_CreateInstance(SB_SQLBUILDER_INSERT_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); rv = insert->SetIntoTableName(NS_LITERAL_STRING("library_metadata")); NS_ENSURE_SUCCESS(rv, rv); rv = insert->AddColumn(NS_LITERAL_STRING("name")); NS_ENSURE_SUCCESS(rv, rv); rv = insert->AddColumn(NS_LITERAL_STRING("value")); NS_ENSURE_SUCCESS(rv, rv); rv = insert->AddValueString(NS_LITERAL_STRING("resource-guid")); NS_ENSURE_SUCCESS(rv, rv); rv = insert->AddValueString(guid); NS_ENSURE_SUCCESS(rv, rv); nsAutoString sql; rv = insert->ToString(sql); NS_ENSURE_SUCCESS(rv, rv); rv = query->ResetQuery(); NS_ENSURE_SUCCESS(rv, rv); rv = query->AddQuery(sql); NS_ENSURE_SUCCESS(rv, rv); rv = query->Execute(&dbOk); NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_TRUE(dbOk == 0, NS_ERROR_FAILURE); nsString now; sbLocalDatabaseLibrary::GetNowString(now); nsCOMPtr<nsIURI> fileURI; rv = NS_NewFileURI(getter_AddRefs(fileURI), aDatabaseFile); NS_ENSURE_SUCCESS(rv, rv); nsCString uriSpec; rv = fileURI->GetSpec(uriSpec); NS_ENSURE_SUCCESS(rv, rv); // Add the default library media item properties insert = do_CreateInstance(SB_SQLBUILDER_INSERT_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); rv = insert->SetIntoTableName(NS_LITERAL_STRING("library_media_item")); NS_ENSURE_SUCCESS(rv, rv); rv = insert->AddColumn(NS_LITERAL_STRING("guid")); NS_ENSURE_SUCCESS(rv, rv); rv = insert->AddValueString(guid); NS_ENSURE_SUCCESS(rv, rv); rv = insert->AddColumn(NS_LITERAL_STRING("created")); NS_ENSURE_SUCCESS(rv, rv); rv = insert->AddValueString(now); NS_ENSURE_SUCCESS(rv, rv); rv = insert->AddColumn(NS_LITERAL_STRING("updated")); NS_ENSURE_SUCCESS(rv, rv); rv = insert->AddValueString(now); NS_ENSURE_SUCCESS(rv, rv); rv = insert->AddColumn(NS_LITERAL_STRING("content_url")); NS_ENSURE_SUCCESS(rv, rv); rv = insert->AddValueString(NS_ConvertUTF8toUTF16(uriSpec)); NS_ENSURE_SUCCESS(rv, rv); rv = insert->AddColumn(NS_LITERAL_STRING("hidden")); NS_ENSURE_SUCCESS(rv, rv); rv = insert->AddValueLong(0); NS_ENSURE_SUCCESS(rv, rv); rv = insert->AddColumn(NS_LITERAL_STRING("is_list")); NS_ENSURE_SUCCESS(rv, rv); rv = insert->AddValueLong(0); NS_ENSURE_SUCCESS(rv, rv); rv = insert->ToString(sql); NS_ENSURE_SUCCESS(rv, rv); rv = query->ResetQuery(); NS_ENSURE_SUCCESS(rv, rv); rv = query->AddQuery(sql); NS_ENSURE_SUCCESS(rv, rv); rv = query->Execute(&dbOk); NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_TRUE(dbOk == 0, NS_ERROR_FAILURE); return NS_OK; }
// Return a fully populated command string based on // passing information. Used in launchWithFile to trace // back to the full handler path based on the dll. // (dll, targetfile, return args, open/edit) bool nsMIMEInfoWin::GetDllLaunchInfo(nsIFile * aDll, nsILocalFile * aFile, nsAString& args, bool edit) { if (!aDll || !aFile) return false; nsCOMPtr<nsILocalFile> localDll(do_QueryInterface(aDll)); if (!localDll) return false; nsString appExeName; localDll->GetLeafName(appExeName); nsCOMPtr<nsIWindowsRegKey> appKey = do_CreateInstance("@mozilla.org/windows-registry-key;1"); if (!appKey) return false; // HKEY_CLASSES_ROOT\Applications\iexplore.exe nsAutoString applicationsPath; applicationsPath.AppendLiteral("Applications\\"); applicationsPath.Append(appExeName); nsresult rv = appKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, applicationsPath, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_FAILED(rv)) return false; // Check for the NoOpenWith flag, if it exists PRUint32 value; rv = appKey->ReadIntValue(NS_LITERAL_STRING("NoOpenWith"), &value); if (NS_SUCCEEDED(rv) && value == 1) return false; nsAutoString dummy; if (NS_SUCCEEDED(appKey->ReadStringValue(NS_LITERAL_STRING("NoOpenWith"), dummy))) return false; appKey->Close(); // HKEY_CLASSES_ROOT\Applications\iexplore.exe\shell\open\command applicationsPath.AssignLiteral("Applications\\"); applicationsPath.Append(appExeName); if (!edit) applicationsPath.AppendLiteral("\\shell\\open\\command"); else applicationsPath.AppendLiteral("\\shell\\edit\\command"); rv = appKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, applicationsPath, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_FAILED(rv)) return false; nsAutoString appFilesystemCommand; if (NS_SUCCEEDED(appKey->ReadStringValue(EmptyString(), appFilesystemCommand))) { // Replace embedded environment variables. PRUint32 bufLength = ::ExpandEnvironmentStringsW(appFilesystemCommand.get(), L"", 0); if (bufLength == 0) // Error return false; nsAutoArrayPtr<PRUnichar> destination(new PRUnichar[bufLength]); if (!destination) return false; if (!::ExpandEnvironmentStringsW(appFilesystemCommand.get(), destination, bufLength)) return false; appFilesystemCommand = destination; // C:\Windows\System32\rundll32.exe "C:\Program Files\Windows // Photo Gallery\PhotoViewer.dll", ImageView_Fullscreen %1 nsAutoString params; NS_NAMED_LITERAL_STRING(rundllSegment, "rundll32.exe "); PRInt32 index = appFilesystemCommand.Find(rundllSegment); if (index > kNotFound) { params.Append(Substring(appFilesystemCommand, index + rundllSegment.Length())); } else { params.Append(appFilesystemCommand); } // check to make sure we have a %1 and fill it NS_NAMED_LITERAL_STRING(percentOneParam, "%1"); index = params.Find(percentOneParam); if (index == kNotFound) // no parameter return false; nsString target; aFile->GetTarget(target); params.Replace(index, 2, target); args = params; return true; } return false; }
bool nsXHTMLContentSerializer::SerializeAttributes(nsIContent* aContent, nsIContent *aOriginalElement, nsAString& aTagPrefix, const nsAString& aTagNamespaceURI, nsIAtom* aTagName, nsAString& aStr, uint32_t aSkipAttr, bool aAddNSAttr) { nsresult rv; uint32_t index, count; nsAutoString prefixStr, uriStr, valueStr; nsAutoString xmlnsStr; xmlnsStr.AssignLiteral(kXMLNS); int32_t contentNamespaceID = aContent->GetNameSpaceID(); // this method is not called by nsHTMLContentSerializer // so we don't have to check HTML element, just XHTML if (mIsCopying && kNameSpaceID_XHTML == contentNamespaceID) { // Need to keep track of OL and LI elements in order to get ordinal number // for the LI. if (aTagName == nsGkAtoms::ol) { // We are copying and current node is an OL; // Store its start attribute value in olState->startVal. nsAutoString start; int32_t startAttrVal = 0; aContent->GetAttr(kNameSpaceID_None, nsGkAtoms::start, start); if (!start.IsEmpty()) { nsresult rv = NS_OK; startAttrVal = start.ToInteger(&rv); //If OL has "start" attribute, first LI element has to start with that value //Therefore subtracting 1 as all the LI elements are incrementing it before using it; //In failure of ToInteger(), default StartAttrValue to 0. if (NS_SUCCEEDED(rv)) --startAttrVal; else startAttrVal = 0; } olState state (startAttrVal, true); mOLStateStack.AppendElement(state); } else if (aTagName == nsGkAtoms::li) { mIsFirstChildOfOL = IsFirstChildOfOL(aOriginalElement); if (mIsFirstChildOfOL) { // If OL is parent of this LI, serialize attributes in different manner. NS_ENSURE_TRUE(SerializeLIValueAttribute(aContent, aStr), false); } } } // If we had to add a new namespace declaration, serialize // and push it on the namespace stack if (aAddNSAttr) { if (aTagPrefix.IsEmpty()) { // Serialize default namespace decl NS_ENSURE_TRUE(SerializeAttr(EmptyString(), xmlnsStr, aTagNamespaceURI, aStr, true), false); } else { // Serialize namespace decl NS_ENSURE_TRUE(SerializeAttr(xmlnsStr, aTagPrefix, aTagNamespaceURI, aStr, true), false); } PushNameSpaceDecl(aTagPrefix, aTagNamespaceURI, aOriginalElement); } NS_NAMED_LITERAL_STRING(_mozStr, "_moz"); count = aContent->GetAttrCount(); // Now serialize each of the attributes // XXX Unfortunately we need a namespace manager to get // attribute URIs. for (index = 0; index < count; index++) { if (aSkipAttr == index) { continue; } mozilla::dom::BorrowedAttrInfo info = aContent->GetAttrInfoAt(index); const nsAttrName* name = info.mName; int32_t namespaceID = name->NamespaceID(); nsIAtom* attrName = name->LocalName(); nsIAtom* attrPrefix = name->GetPrefix(); // Filter out any attribute starting with [-|_]moz nsDependentAtomString attrNameStr(attrName); if (StringBeginsWith(attrNameStr, NS_LITERAL_STRING("_moz")) || StringBeginsWith(attrNameStr, NS_LITERAL_STRING("-moz"))) { continue; } if (attrPrefix) { attrPrefix->ToString(prefixStr); } else { prefixStr.Truncate(); } bool addNSAttr = false; if (kNameSpaceID_XMLNS != namespaceID) { nsContentUtils::NameSpaceManager()->GetNameSpaceURI(namespaceID, uriStr); addNSAttr = ConfirmPrefix(prefixStr, uriStr, aOriginalElement, true); } info.mValue->ToString(valueStr); nsDependentAtomString nameStr(attrName); bool isJS = false; if (kNameSpaceID_XHTML == contentNamespaceID) { // // Filter out special case of <br type="_moz"> or <br _moz*>, // used by the editor. Bug 16988. Yuck. // if (namespaceID == kNameSpaceID_None && aTagName == nsGkAtoms::br && attrName == nsGkAtoms::type && StringBeginsWith(valueStr, _mozStr)) { continue; } if (mIsCopying && mIsFirstChildOfOL && (aTagName == nsGkAtoms::li) && (attrName == nsGkAtoms::value)) { // This is handled separately in SerializeLIValueAttribute() continue; } isJS = IsJavaScript(aContent, attrName, namespaceID, valueStr); if (namespaceID == kNameSpaceID_None && ((attrName == nsGkAtoms::href) || (attrName == nsGkAtoms::src))) { // Make all links absolute when converting only the selection: if (mFlags & nsIDocumentEncoder::OutputAbsoluteLinks) { // Would be nice to handle OBJECT tags, // but that gets more complicated since we have to // search the tag list for CODEBASE as well. // For now, just leave them relative. nsCOMPtr<nsIURI> uri = aContent->GetBaseURI(); if (uri) { nsAutoString absURI; rv = NS_MakeAbsoluteURI(absURI, valueStr, uri); if (NS_SUCCEEDED(rv)) { valueStr = absURI; } } } } if (mRewriteEncodingDeclaration && aTagName == nsGkAtoms::meta && attrName == nsGkAtoms::content) { // If we're serializing a <meta http-equiv="content-type">, // use the proper value, rather than what's in the document. nsAutoString header; aContent->GetAttr(kNameSpaceID_None, nsGkAtoms::httpEquiv, header); if (header.LowerCaseEqualsLiteral("content-type")) { valueStr = NS_LITERAL_STRING("text/html; charset=") + NS_ConvertASCIItoUTF16(mCharset); } } // Expand shorthand attribute. if (namespaceID == kNameSpaceID_None && IsShorthandAttr(attrName, aTagName) && valueStr.IsEmpty()) { valueStr = nameStr; } } else { isJS = IsJavaScript(aContent, attrName, namespaceID, valueStr); } NS_ENSURE_TRUE(SerializeAttr(prefixStr, nameStr, valueStr, aStr, !isJS), false); if (addNSAttr) { NS_ASSERTION(!prefixStr.IsEmpty(), "Namespaced attributes must have a prefix"); NS_ENSURE_TRUE(SerializeAttr(xmlnsStr, prefixStr, uriStr, aStr, true), false); PushNameSpaceDecl(prefixStr, uriStr, aOriginalElement); } } return true; }
NS_IMETHODIMP nsInstallTrigger::HandleContent(const char * aContentType, nsIInterfaceRequestor* aWindowContext, nsIRequest* aRequest) { nsresult rv = NS_OK; if (!aRequest) return NS_ERROR_NULL_POINTER; if (nsCRT::strcasecmp(aContentType, "application/x-xpinstall") != 0) { // We only support content-type application/x-xpinstall return NS_ERROR_WONT_HANDLE_CONTENT; } // Save the URI so nsXPInstallManager can re-load it later nsCOMPtr<nsIURI> uri; nsCAutoString urispec; nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest); if (channel) { rv = channel->GetURI(getter_AddRefs(uri)); if (NS_SUCCEEDED(rv) && uri) rv = uri->GetSpec(urispec); } if (NS_FAILED(rv)) return rv; if (urispec.IsEmpty()) return NS_ERROR_ILLEGAL_VALUE; // Save the referrer if any, for permission checks NS_NAMED_LITERAL_STRING(referrerProperty, "docshell.internalReferrer"); PRBool useReferrer = PR_FALSE; nsCOMPtr<nsIURI> referringURI; nsCOMPtr<nsIPropertyBag2> channelprops(do_QueryInterface(channel)); if (channelprops) { // Get the referrer from the channel properties if we can (not all // channels support our internal-referrer property). // // It's possible docshell explicitly set a null referrer in the case // of typed, pasted, or bookmarked URLs and the like. In such a case // we get a success return value with null pointer. // // A null referrer is automatically whitelisted as an explicit user // action (though they'll still get the confirmation dialog). For a // missing referrer we go to our fall-back plan of using the XPI // location for whitelisting purposes. rv = channelprops->GetPropertyAsInterface(referrerProperty, NS_GET_IID(nsIURI), getter_AddRefs(referringURI)); if (NS_SUCCEEDED(rv)) useReferrer = PR_TRUE; } // Cancel the current request. nsXPInstallManager restarts the download // under its control (shared codepath with InstallTrigger) aRequest->Cancel(NS_BINDING_ABORTED); // Get the global object of the target window for StartSoftwareUpdate nsCOMPtr<nsIScriptGlobalObjectOwner> globalObjectOwner = do_QueryInterface(aWindowContext); nsIScriptGlobalObject* globalObject = globalObjectOwner ? globalObjectOwner->GetScriptGlobalObject() : nsnull; if ( !globalObject ) return NS_ERROR_INVALID_ARG; nsCOMPtr<nsIURI> checkuri; if ( useReferrer ) { // easiest and most common case: base decision on the page that // contained the link // // NOTE: the XPI itself may be from elsewhere; the user can decide if // they trust the actual source when they get the install confirmation // dialog. The decision we're making here is whether the triggering // site is one which is allowed to annoy the user with modal dialogs. checkuri = referringURI; } else { // Now we're stumbing in the dark. In the most likely case the user // simply clicked on an FTP link (no referrer) and it's perfectly // sane to use the current window. // // On the other hand the user might be opening a non-http XPI link // in an unrelated existing window (typed in location bar, bookmark, // dragged link ...) in which case the current window is irrelevant. // If we knew it was one of these explicit user actions we'd like to // allow it, but we have no way of knowing that here. // // But there's no way to distinguish the innocent cases from a clever // malicious site. If we used the target window then evil.com could // embed a presumed allowed site (e.g. mozilla.org) in a frame, then // change the location to the XPI and trigger the install. Or evil.com // could do the same thing in a new window (more work to get around // popup blocking, but possible). // // Our choices appear to be block this type of load entirely or to // trust only the install URI. The former is unacceptably restrictive, // the latter allows malicious sites to pester people with modal // dialogs. As long as the trusted sites don't host bad content that's // no worse than an endless stream of alert()s -- already possible. // If the trusted sites don't even have an ftp server then even this // level of annoyance is not possible. // // If a trusted site hosts an install with an exploitable flaw it // might be possible that a malicious site would attempt to trick // people into installing it, hoping to turn around and exploit it. // This is not entirely far-fetched (it's been done with ActiveX // controls) and will require community policing of the default // trusted sites. checkuri = uri; } nsAutoPtr<nsXPITriggerInfo> trigger(new nsXPITriggerInfo()); nsAutoPtr<nsXPITriggerItem> item(new nsXPITriggerItem(0, NS_ConvertUTF8toUTF16(urispec).get(), nsnull)); if (trigger && item) { // trigger will own the item now trigger->Add(item.forget()); nsCOMPtr<nsIDOMWindowInternal> win(do_QueryInterface(globalObject)); nsCOMPtr<nsIXPIInstallInfo> installInfo = new nsXPIInstallInfo(win, checkuri, trigger, 0); if (installInfo) { // From here trigger is owned by installInfo until passed on to nsXPInstallManager trigger.forget(); if (AllowInstall(checkuri)) { return StartInstall(installInfo, nsnull); } else { nsCOMPtr<nsIObserverService> os(do_GetService("@mozilla.org/observer-service;1")); if (os) os->NotifyObservers(installInfo, "xpinstall-install-blocked", nsnull); return NS_ERROR_ABORT; } } } return NS_ERROR_OUT_OF_MEMORY; }
nsresult nsProfileMigrator::GetDefaultBrowserMigratorKey(nsACString& aKey, nsCOMPtr<nsIBrowserProfileMigrator>& bpm) { #if XP_WIN nsCOMPtr<nsIWindowsRegKey> regKey = do_CreateInstance("@mozilla.org/windows-registry-key;1"); if (!regKey) return NS_ERROR_FAILURE; NS_NAMED_LITERAL_STRING(kCommandKey, "SOFTWARE\\Classes\\HTTP\\shell\\open\\command"); if (NS_FAILED(regKey->Open(nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE, kCommandKey, nsIWindowsRegKey::ACCESS_READ))) return NS_ERROR_FAILURE; nsAutoString value; if (NS_FAILED(regKey->ReadStringValue(EmptyString(), value))) return NS_ERROR_FAILURE; PRInt32 len = value.Find(NS_LITERAL_STRING(".exe"), CaseInsensitiveCompare); if (len == -1) return NS_ERROR_FAILURE; // Move past ".exe" len += 4; PRUint32 start = 0; // skip an opening quotation mark if present if (value.get()[1] != ':') { start = 1; --len; } const nsDependentSubstring filePath(Substring(value, start, len)); // We want to find out what the default browser is but the path in and of itself // isn't enough. Why? Because sometimes on Windows paths get truncated like so: // C:\PROGRA~1\MOZILL~2\MOZILL~1.EXE // How do we know what product that is? Mozilla or Mozilla Firebird? etc. Mozilla's // file objects do nothing to 'normalize' the path so we need to attain an actual // product descriptor from the file somehow, and in this case it means getting // the "InternalName" field of the file's VERSIONINFO resource. // // In the file's resource segment there is a VERSIONINFO section that is laid // out like this: // // VERSIONINFO // StringFileInfo // <TranslationID> // InternalName "iexplore" // VarFileInfo // Translation <TranslationID> // // By Querying the VERSIONINFO section for its Tranlations, we can find out where // the InternalName lives. (A file can have more than one translation of its // VERSIONINFO segment, but we just assume the first one). nsCOMPtr<nsILocalFile> lf; NS_NewLocalFile(filePath, PR_TRUE, getter_AddRefs(lf)); if (!lf) return NS_ERROR_FAILURE; nsCOMPtr<nsILocalFileWin> lfw = do_QueryInterface(lf); if (!lfw) return NS_ERROR_FAILURE; nsAutoString internalName; if (NS_FAILED(lfw->GetVersionInfoField("InternalName", internalName))) return NS_ERROR_FAILURE; if (internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_IEXPLORE)) { aKey = "ie"; return NS_OK; } if (internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_MOZILLA_SUITE) || internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_SEAMONKEY)) { aKey = "seamonkey"; return NS_OK; } if (internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_DOGBERT)) { aKey = "dogbert"; return NS_OK; } if (internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_OPERA)) { aKey = "opera"; return NS_OK; } // Migrate data from any existing Application Data\Phoenix\* installations. if (internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_FIREBIRD) || internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_FIREFOX) || internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_PHOENIX)) { aKey = "phoenix"; return NS_OK; } #else PRBool exists = PR_FALSE; #define CHECK_MIGRATOR(browser) do {\ bpm = do_CreateInstance(NS_BROWSERPROFILEMIGRATOR_CONTRACTID_PREFIX browser);\ if (bpm)\ bpm->GetSourceExists(&exists);\ if (exists) {\ aKey = browser;\ return NS_OK;\ }} while(0) #if defined(XP_MACOSX) CHECK_MIGRATOR("safari"); CHECK_MIGRATOR("macie"); #endif CHECK_MIGRATOR("phoenix"); CHECK_MIGRATOR("seamonkey"); CHECK_MIGRATOR("opera"); #undef CHECK_MIGRATOR #endif return NS_ERROR_FAILURE; }
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; }
bool nsMapiHook::DisplayLoginDialog(bool aLogin, PRUnichar **aUsername, PRUnichar **aPassword) { nsresult rv; bool btnResult = false; nsCOMPtr<nsIPromptService> dlgService(do_GetService(NS_PROMPTSERVICE_CONTRACTID, &rv)); if (NS_SUCCEEDED(rv) && dlgService) { nsCOMPtr<nsIStringBundleService> bundleService = mozilla::services::GetStringBundleService(); if (!bundleService) return false; nsCOMPtr<nsIStringBundle> bundle; rv = bundleService->CreateBundle(MAPI_PROPERTIES_CHROME, getter_AddRefs(bundle)); if (NS_FAILED(rv) || !bundle) return false; nsCOMPtr<nsIStringBundle> brandBundle; rv = bundleService->CreateBundle( "chrome://branding/locale/brand.properties", getter_AddRefs(brandBundle)); if (NS_FAILED(rv)) return false; nsString brandName; rv = brandBundle->GetStringFromName( NS_LITERAL_STRING("brandFullName").get(), getter_Copies(brandName)); if (NS_FAILED(rv)) return false; nsString loginTitle; const PRUnichar *brandStrings[] = { brandName.get() }; NS_NAMED_LITERAL_STRING(loginTitlePropertyTag, "loginTitle"); const PRUnichar *dTitlePropertyTag = loginTitlePropertyTag.get(); rv = bundle->FormatStringFromName(dTitlePropertyTag, brandStrings, 1, getter_Copies(loginTitle)); if (NS_FAILED(rv)) return false; if (aLogin) { nsString loginText; rv = bundle->GetStringFromName(NS_LITERAL_STRING("loginTextwithName").get(), getter_Copies(loginText)); if (NS_FAILED(rv) || loginText.IsEmpty()) return false; bool dummyValue = false; rv = dlgService->PromptUsernameAndPassword(nsnull, loginTitle.get(), loginText.get(), aUsername, aPassword, nsnull, &dummyValue, &btnResult); } else { //nsString loginString; nsString loginText; const PRUnichar *userNameStrings[] = { *aUsername }; NS_NAMED_LITERAL_STRING(loginTextPropertyTag, "loginText"); const PRUnichar *dpropertyTag = loginTextPropertyTag.get(); rv = bundle->FormatStringFromName(dpropertyTag, userNameStrings, 1, getter_Copies(loginText)); if (NS_FAILED(rv)) return false; bool dummyValue = false; rv = dlgService->PromptPassword(nsnull, loginTitle.get(), loginText.get(), aPassword, nsnull, &dummyValue, &btnResult); } } return btnResult; }
NS_IMETHODIMP XULContentSinkImpl::ReportError(const PRUnichar* aErrorText, const PRUnichar* aSourceText, nsIScriptError *aError, PRUint32 aLineNumber, PRUint32 aColNumber, bool *_retval) { NS_PRECONDITION(aError && aSourceText && aErrorText, "Check arguments!!!"); // The expat driver should report the error. *_retval = true; nsresult rv = NS_OK; // make sure to empty the context stack so that // <parsererror> could become the root element. mContextStack.Clear(); mState = eInProlog; // Clear any buffered-up text we have. It's enough to set the length to 0. // The buffer itself is allocated when we're created and deleted in our // destructor, so don't mess with it. mTextLength = 0; nsCOMPtr<nsIXULDocument> doc = do_QueryReferent(mDocument); if (doc && !doc->OnDocumentParserError()) { // The overlay was broken. Don't add a messy element to the master doc. return NS_OK; } const PRUnichar* noAtts[] = { 0, 0 }; NS_NAMED_LITERAL_STRING(errorNs, "http://www.mozilla.org/newlayout/xml/parsererror.xml"); nsAutoString parsererror(errorNs); parsererror.Append((PRUnichar)0xFFFF); parsererror.AppendLiteral("parsererror"); rv = HandleStartElement(parsererror.get(), noAtts, 0, -1, 0); NS_ENSURE_SUCCESS(rv,rv); rv = HandleCharacterData(aErrorText, nsCRT::strlen(aErrorText)); NS_ENSURE_SUCCESS(rv,rv); nsAutoString sourcetext(errorNs); sourcetext.Append((PRUnichar)0xFFFF); sourcetext.AppendLiteral("sourcetext"); rv = HandleStartElement(sourcetext.get(), noAtts, 0, -1, 0); NS_ENSURE_SUCCESS(rv,rv); rv = HandleCharacterData(aSourceText, nsCRT::strlen(aSourceText)); NS_ENSURE_SUCCESS(rv,rv); rv = HandleEndElement(sourcetext.get()); NS_ENSURE_SUCCESS(rv,rv); rv = HandleEndElement(parsererror.get()); NS_ENSURE_SUCCESS(rv,rv); return rv; }
// this is used to populate comp fields with Unicode data nsresult nsMapiHook::PopulateCompFields(lpnsMapiMessage aMessage, nsIMsgCompFields * aCompFields) { nsresult rv = NS_OK ; if (aMessage->lpOriginator) aCompFields->SetFrom (NS_ConvertASCIItoUTF16((char *) aMessage->lpOriginator->lpszAddress)); nsAutoString To ; nsAutoString Cc ; nsAutoString Bcc ; NS_NAMED_LITERAL_STRING(Comma, ","); if (aMessage->lpRecips) { for (int i=0 ; i < (int) aMessage->nRecipCount ; i++) { if (aMessage->lpRecips[i].lpszAddress || aMessage->lpRecips[i].lpszName) { const char *addressWithoutType = (aMessage->lpRecips[i].lpszAddress) ? aMessage->lpRecips[i].lpszAddress : aMessage->lpRecips[i].lpszName; if (!PL_strncasecmp(addressWithoutType, "SMTP:", 5)) addressWithoutType += 5; switch (aMessage->lpRecips[i].ulRecipClass) { case MAPI_TO : if (!To.IsEmpty()) To += Comma; To.Append(NS_ConvertASCIItoUTF16(addressWithoutType)); break; case MAPI_CC : if (!Cc.IsEmpty()) Cc += Comma; Cc.Append(NS_ConvertASCIItoUTF16(addressWithoutType)); break; case MAPI_BCC : if (!Bcc.IsEmpty()) Bcc += Comma; Bcc.Append(NS_ConvertASCIItoUTF16(addressWithoutType)); break; } } } } PR_LOG(MAPI, PR_LOG_DEBUG, ("to: %s cc: %s bcc: %s \n", NS_ConvertUTF16toUTF8(To).get(), NS_ConvertUTF16toUTF8(Cc).get(), NS_ConvertUTF16toUTF8(Bcc).get())); // set To, Cc, Bcc aCompFields->SetTo (To) ; aCompFields->SetCc (Cc) ; aCompFields->SetBcc (Bcc) ; // set subject if (aMessage->lpszSubject) aCompFields->SetSubject(NS_ConvertASCIItoUTF16(aMessage->lpszSubject)); // handle attachments as File URL rv = HandleAttachments (aCompFields, aMessage->nFileCount, aMessage->lpFiles, true) ; if (NS_FAILED(rv)) return rv ; // set body if (aMessage->lpszNoteText) { nsString Body; CopyASCIItoUTF16(aMessage->lpszNoteText, Body); if (Body.Last() != '\n') Body.AppendLiteral(CRLF); if (Body.Find("<html>") == kNotFound) aCompFields->SetForcePlainText(true); rv = aCompFields->SetBody(Body) ; } return rv ; }
/* boolean findNext (); */ NS_IMETHODIMP nsWebBrowserFind::FindNext(bool *outDidFind) { NS_ENSURE_ARG_POINTER(outDidFind); *outDidFind = false; NS_ENSURE_TRUE(CanFindNext(), NS_ERROR_NOT_INITIALIZED); nsresult rv = NS_OK; nsCOMPtr<nsIDOMWindow> searchFrame = do_QueryReferent(mCurrentSearchFrame); NS_ENSURE_TRUE(searchFrame, NS_ERROR_NOT_INITIALIZED); nsCOMPtr<nsIDOMWindow> rootFrame = do_QueryReferent(mRootSearchFrame); NS_ENSURE_TRUE(rootFrame, NS_ERROR_NOT_INITIALIZED); // first, if there's a "cmd_findagain" observer around, check to see if it // wants to perform the find again command . If it performs the find again // it will return true, in which case we exit ::FindNext() early. // Otherwise, nsWebBrowserFind needs to perform the find again command itself // this is used by nsTypeAheadFind, which controls find again when it was // the last executed find in the current window. nsCOMPtr<nsIObserverService> observerSvc = mozilla::services::GetObserverService(); if (observerSvc) { nsCOMPtr<nsISupportsInterfacePointer> windowSupportsData = do_CreateInstance(NS_SUPPORTS_INTERFACE_POINTER_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsISupports> searchWindowSupports = do_QueryInterface(rootFrame); windowSupportsData->SetData(searchWindowSupports); NS_NAMED_LITERAL_STRING(dnStr, "down"); NS_NAMED_LITERAL_STRING(upStr, "up"); observerSvc->NotifyObservers(windowSupportsData, "nsWebBrowserFind_FindAgain", mFindBackwards? upStr.get(): dnStr.get()); windowSupportsData->GetData(getter_AddRefs(searchWindowSupports)); // findnext performed if search window data cleared out *outDidFind = searchWindowSupports == nullptr; if (*outDidFind) return NS_OK; } // next, look in the current frame. If found, return. // Beware! This may flush notifications via synchronous // ScrollSelectionIntoView. rv = SearchInFrame(searchFrame, false, outDidFind); if (NS_FAILED(rv)) return rv; if (*outDidFind) return OnFind(searchFrame); // we are done // if we are not searching other frames, return if (!mSearchSubFrames && !mSearchParentFrames) return NS_OK; nsIDocShell *rootDocShell = GetDocShellFromWindow(rootFrame); if (!rootDocShell) return NS_ERROR_FAILURE; int32_t enumDirection; if (mFindBackwards) enumDirection = nsIDocShell::ENUMERATE_BACKWARDS; else enumDirection = nsIDocShell::ENUMERATE_FORWARDS; nsCOMPtr<nsISimpleEnumerator> docShellEnumerator; rv = rootDocShell->GetDocShellEnumerator(nsIDocShellTreeItem::typeAll, enumDirection, getter_AddRefs(docShellEnumerator)); if (NS_FAILED(rv)) return rv; // remember where we started nsCOMPtr<nsIDocShellTreeItem> startingItem = do_QueryInterface(GetDocShellFromWindow(searchFrame), &rv); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIDocShellTreeItem> curItem; // XXX We should avoid searching in frameset documents here. // We also need to honour mSearchSubFrames and mSearchParentFrames. bool hasMore, doFind = false; while (NS_SUCCEEDED(docShellEnumerator->HasMoreElements(&hasMore)) && hasMore) { nsCOMPtr<nsISupports> curSupports; rv = docShellEnumerator->GetNext(getter_AddRefs(curSupports)); if (NS_FAILED(rv)) break; curItem = do_QueryInterface(curSupports, &rv); if (NS_FAILED(rv)) break; if (doFind) { searchFrame = do_GetInterface(curItem, &rv); if (NS_FAILED(rv)) break; OnStartSearchFrame(searchFrame); // Beware! This may flush notifications via synchronous // ScrollSelectionIntoView. rv = SearchInFrame(searchFrame, false, outDidFind); if (NS_FAILED(rv)) return rv; if (*outDidFind) return OnFind(searchFrame); // we are done OnEndSearchFrame(searchFrame); } if (curItem.get() == startingItem.get()) doFind = true; // start looking in frames after this one }; if (!mWrapFind) { // remember where we left off SetCurrentSearchFrame(searchFrame); return NS_OK; } // From here on, we're wrapping, first through the other frames, // then finally from the beginning of the starting frame back to // the starting point. // because nsISimpleEnumerator is totally lame and isn't resettable, I // have to make a new one docShellEnumerator = nullptr; rv = rootDocShell->GetDocShellEnumerator(nsIDocShellTreeItem::typeAll, enumDirection, getter_AddRefs(docShellEnumerator)); if (NS_FAILED(rv)) return rv; while (NS_SUCCEEDED(docShellEnumerator->HasMoreElements(&hasMore)) && hasMore) { nsCOMPtr<nsISupports> curSupports; rv = docShellEnumerator->GetNext(getter_AddRefs(curSupports)); if (NS_FAILED(rv)) break; curItem = do_QueryInterface(curSupports, &rv); if (NS_FAILED(rv)) break; searchFrame = do_GetInterface(curItem, &rv); if (NS_FAILED(rv)) break; if (curItem.get() == startingItem.get()) { // Beware! This may flush notifications via synchronous // ScrollSelectionIntoView. rv = SearchInFrame(searchFrame, true, outDidFind); if (NS_FAILED(rv)) return rv; if (*outDidFind) return OnFind(searchFrame); // we are done break; } OnStartSearchFrame(searchFrame); // Beware! This may flush notifications via synchronous // ScrollSelectionIntoView. rv = SearchInFrame(searchFrame, false, outDidFind); if (NS_FAILED(rv)) return rv; if (*outDidFind) return OnFind(searchFrame); // we are done OnEndSearchFrame(searchFrame); } // remember where we left off SetCurrentSearchFrame(searchFrame); NS_ASSERTION(NS_SUCCEEDED(rv), "Something failed"); return rv; }
// this is used to convert non Unicode data and then populate comp fields nsresult nsMapiHook::PopulateCompFieldsWithConversion(lpnsMapiMessage aMessage, nsIMsgCompFields * aCompFields) { nsresult rv = NS_OK; if (aMessage->lpOriginator) { nsAutoString From; From.Append(NS_ConvertASCIItoUTF16((char *) aMessage->lpOriginator->lpszAddress)); aCompFields->SetFrom (From); } nsAutoString To; nsAutoString Cc; nsAutoString Bcc; NS_NAMED_LITERAL_STRING(Comma, ","); if (aMessage->lpRecips) { for (int i=0 ; i < (int) aMessage->nRecipCount ; i++) { if (aMessage->lpRecips[i].lpszAddress || aMessage->lpRecips[i].lpszName) { const char *addressWithoutType = (aMessage->lpRecips[i].lpszAddress) ? aMessage->lpRecips[i].lpszAddress : aMessage->lpRecips[i].lpszName; if (!PL_strncasecmp(addressWithoutType, "SMTP:", 5)) addressWithoutType += 5; switch (aMessage->lpRecips[i].ulRecipClass) { case MAPI_TO : if (!To.IsEmpty()) To += Comma ; To.Append(NS_ConvertASCIItoUTF16(addressWithoutType)); break ; case MAPI_CC : if (!Cc.IsEmpty()) Cc += Comma ; Cc.Append(NS_ConvertASCIItoUTF16(addressWithoutType)); break ; case MAPI_BCC : if (!Bcc.IsEmpty()) Bcc += Comma ; Bcc.Append(NS_ConvertASCIItoUTF16(addressWithoutType)); break ; } } } } // set To, Cc, Bcc aCompFields->SetTo (To) ; aCompFields->SetCc (Cc) ; aCompFields->SetBcc (Bcc) ; PR_LOG(MAPI, PR_LOG_DEBUG, ("to: %s cc: %s bcc: %s \n", NS_ConvertUTF16toUTF8(To).get(), NS_ConvertUTF16toUTF8(Cc).get(), NS_ConvertUTF16toUTF8(Bcc).get())); nsCAutoString platformCharSet; // set subject if (aMessage->lpszSubject) { nsAutoString Subject ; if (platformCharSet.IsEmpty()) platformCharSet.Assign(nsMsgI18NFileSystemCharset()); rv = ConvertToUnicode(platformCharSet.get(), (char *) aMessage->lpszSubject, Subject); if (NS_FAILED(rv)) return rv; aCompFields->SetSubject(Subject); } // handle attachments as File URL rv = HandleAttachments (aCompFields, aMessage->nFileCount, aMessage->lpFiles, false) ; if (NS_FAILED(rv)) return rv ; // set body if (aMessage->lpszNoteText) { nsAutoString Body ; if (platformCharSet.IsEmpty()) platformCharSet.Assign(nsMsgI18NFileSystemCharset()); rv = ConvertToUnicode(platformCharSet.get(), (char *) aMessage->lpszNoteText, Body); if (NS_FAILED(rv)) return rv ; if (Body.Last() != '\n') Body.AppendLiteral(CRLF); if (Body.Find("<html>") == kNotFound) aCompFields->SetForcePlainText(true); rv = aCompFields->SetBody(Body) ; } #ifdef RAJIV_DEBUG // testing what all was set in CompFields printf ("To : %S \n", To.get()) ; printf ("CC : %S \n", Cc.get() ) ; printf ("BCC : %S \n", Bcc.get() ) ; #endif return rv ; }
NS_IMETHODIMP nsHTMLEditor::RefreshInlineTableEditingUI() { nsCOMPtr<nsIDOMHTMLElement> htmlElement = do_QueryInterface(mInlineEditedCell); if (!htmlElement) { return NS_ERROR_NULL_POINTER; } int32_t xCell, yCell, wCell, hCell; GetElementOrigin(mInlineEditedCell, xCell, yCell); nsresult res = htmlElement->GetOffsetWidth(&wCell); NS_ENSURE_SUCCESS(res, res); res = htmlElement->GetOffsetHeight(&hCell); NS_ENSURE_SUCCESS(res, res); int32_t xHoriz = xCell + wCell/2; int32_t yVert = yCell + hCell/2; nsCOMPtr<nsIDOMNode> tableNode = GetEnclosingTable(mInlineEditedCell); nsCOMPtr<nsIDOMElement> tableElement = do_QueryInterface(tableNode); int32_t rowCount, colCount; res = GetTableSize(tableElement, &rowCount, &colCount); NS_ENSURE_SUCCESS(res, res); SetAnonymousElementPosition(xHoriz-10, yCell-7, mAddColumnBeforeButton); #ifdef DISABLE_TABLE_DELETION NS_NAMED_LITERAL_STRING(classStr, "class"); if (colCount== 1) { mRemoveColumnButton->SetAttribute(classStr, NS_LITERAL_STRING("hidden")); } else { bool hasClass = false; res = mRemoveColumnButton->HasAttribute(classStr, &hasClass); if (NS_SUCCEEDED(res) && hasClass) mRemoveColumnButton->RemoveAttribute(classStr); #endif SetAnonymousElementPosition(xHoriz-4, yCell-7, mRemoveColumnButton); #ifdef DISABLE_TABLE_DELETION } #endif SetAnonymousElementPosition(xHoriz+6, yCell-7, mAddColumnAfterButton); SetAnonymousElementPosition(xCell-7, yVert-10, mAddRowBeforeButton); #ifdef DISABLE_TABLE_DELETION if (rowCount== 1) { mRemoveRowButton->SetAttribute(classStr, NS_LITERAL_STRING("hidden")); } else { bool hasClass = false; res = mRemoveRowButton->HasAttribute(classStr, &hasClass); if (NS_SUCCEEDED(res) && hasClass) mRemoveRowButton->RemoveAttribute(classStr); #endif SetAnonymousElementPosition(xCell-7, yVert-4, mRemoveRowButton); #ifdef DISABLE_TABLE_DELETION } #endif SetAnonymousElementPosition(xCell-7, yVert+6, mAddRowAfterButton); return NS_OK; }
void nsMediaDocument::UpdateTitleAndCharset(const nsACString& aTypeStr, const char* const* aFormatNames, PRInt32 aWidth, PRInt32 aHeight, const nsAString& aStatus) { nsXPIDLString fileStr; if (mDocumentURI) { nsCAutoString fileName; nsCOMPtr<nsIURL> url = do_QueryInterface(mDocumentURI); if (url) url->GetFileName(fileName); nsCAutoString docCharset; // Now that the charset is set in |StartDocumentLoad| to the charset of // the document viewer instead of a bogus value ("ISO-8859-1" set in // |nsDocument|'s ctor), the priority is given to the current charset. // This is necessary to deal with a media document being opened in a new // window or a new tab, in which case |originCharset| of |nsIURI| is not // reliable. if (mCharacterSetSource != kCharsetUninitialized) { docCharset = mCharacterSet; } else { // resort to |originCharset| mDocumentURI->GetOriginCharset(docCharset); SetDocumentCharacterSet(docCharset); } if (!fileName.IsEmpty()) { nsresult rv; nsCOMPtr<nsITextToSubURI> textToSubURI = do_GetService(NS_ITEXTTOSUBURI_CONTRACTID, &rv); if (NS_SUCCEEDED(rv)) // UnEscapeURIForUI always succeeds textToSubURI->UnEscapeURIForUI(docCharset, fileName, fileStr); else CopyUTF8toUTF16(fileName, fileStr); } } NS_ConvertASCIItoUTF16 typeStr(aTypeStr); nsXPIDLString title; if (mStringBundle) { // if we got a valid size (not all media have a size) if (aWidth != 0 && aHeight != 0) { nsAutoString widthStr; nsAutoString heightStr; widthStr.AppendInt(aWidth); heightStr.AppendInt(aHeight); // If we got a filename, display it if (!fileStr.IsEmpty()) { const PRUnichar *formatStrings[4] = {fileStr.get(), typeStr.get(), widthStr.get(), heightStr.get()}; NS_ConvertASCIItoUTF16 fmtName(aFormatNames[eWithDimAndFile]); mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 4, getter_Copies(title)); } else { const PRUnichar *formatStrings[3] = {typeStr.get(), widthStr.get(), heightStr.get()}; NS_ConvertASCIItoUTF16 fmtName(aFormatNames[eWithDim]); mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 3, getter_Copies(title)); } } else { // If we got a filename, display it if (!fileStr.IsEmpty()) { const PRUnichar *formatStrings[2] = {fileStr.get(), typeStr.get()}; NS_ConvertASCIItoUTF16 fmtName(aFormatNames[eWithFile]); mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 2, getter_Copies(title)); } else { const PRUnichar *formatStrings[1] = {typeStr.get()}; NS_ConvertASCIItoUTF16 fmtName(aFormatNames[eWithNoInfo]); mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 1, getter_Copies(title)); } } } // set it on the document if (aStatus.IsEmpty()) { SetTitle(title); } else { nsXPIDLString titleWithStatus; const nsPromiseFlatString& status = PromiseFlatString(aStatus); const PRUnichar *formatStrings[2] = {title.get(), status.get()}; NS_NAMED_LITERAL_STRING(fmtName, "TitleWithStatus"); mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 2, getter_Copies(titleWithStatus)); SetTitle(titleWithStatus); } }