Files
palemoon27/dom/base/nsXHTMLContentSerializer.cpp
T
roytam1 e39f9f88f7 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1152171 part 2 - Rename AnimationTimeline to DocumentTimeline; r=smaug (26c118319)
- Bug 1152171 part 3 - Update web-platform-tests expectations; r=jgraham (b7b4032aa)
- Bug 1153734 part 1 - Remove AnimationEffect; r=smaug (9cf67a02e)
- Bug 1153734 part 2 - Rename Animation to KeyframeEffectReadonly; r=smaug (b69556ee6)
- Bug 1153734 part 3 - Rename AnimationPlayer.source to AnimationPlayer.effect; r=smaug (50d3130ee)
- Bug 1153734 part 4 - Rename other uses of 'source' and 'source content'; r=jwatt (b02c4ba36)
- Bug 1153734 part 5 - Add AnimationEffectReadonly as a superinterface of KeyframeEffectReadonly; r=smaug (c3395d3f5)
- Bug 1149990 - Support replaying of finished CSS transitions by supporting setting of currentTime/startTime. r=birtles (3fb2cb401)
- Bug 1154615 part 1 - Rename AnimationPlayer to Animation in WebIDL; r=smaug (6c2125b49)
- Bug 1154615 part 2 - Rename PendingPlayerTracker to PendingAnimationTracker; r=jwatt (8d6804def)
- Bug 1154615 part 3 - Rename internal members of PendingAnimationTracker; r=jwatt (f348f6355)
- Bug 1154615 part 4 - Rename references to players in dom/animation; r=jwatt (0250572e8)
- Bug 1117603 part 1 - Don't assume style rules have been refreshed in GetAnimationRule; r=dbaron (a5d340d0f)
- remove kungFuDeathGrip (49df758e6)
- Bug 1117603 part 2 - Don't unregister from the refresh driver unless we are also queueing events; r=dbaron (715c9caa1)
- Bug 1154615 part 5 - Rename AnimationPlayerCollection to AnimationCollection; r=jwatt (4c596f089)
- Bug 1154615 part 6 - Rename references to players within layout/; r=jwatt (42405f3fc)
- Bug 1154615 part 7 - Rename CSSAnimationPlayer and CSSTransitionPlayer; r=jwatt (49ab272ed)
- Bug 1154615 part 8 - Rename references to players in animation observers; r=jwatt (c3fa26d7a)
- Bug 1154615 part 9 - Rename test files; r=jwatt (9d9f03e7b)
- Bug 1145439 (Part 1) - Throttle requestAnimationFrame for non-visible iframes. r=mstange,mchang (be7d183d6)
- Bug 1145439 (Part 2) - Make test_scroll_event_ordering.html wait for rAF to unthrottle. r=roc (9ac8317c9)
- Bug 1144324 - Try to register for, and handle, touch events when APZ is enabled. r=dvander,jimm (fb75d1665)
- Bug 1144324 - Remove the codepaths that conditionally enable touch events based on touch the presence of touch listeners. r=smaug,jimm (710617e6b)
- Bug 1003991 - Disable https:// only load for ServiceWorkers when Developer Tools are open. r=nsm, r=miker (9d6669814)
- Bug 1153267 - part 1 - use smart-pointer .forget() instead of NS_ADDREF+assign; r=ehsan (e4555c90c)
- Bug 1153267 - part 2 - use smart pointers instead of manual NS_ADDREF'ing outparams; r=ehsan (ae8b60d5a)
- Bug 1153267 - fix typo that broke OS X builds on a CLOSED TREE; r=bustage (08fdb3c4f)
- Bug 1146843 - Revert part of cset 33c30e283fa8 because the code is used in Fennec. r=snorp (407248257)
- Bug 1151940 part 1. Make some readonly properties defined on Window by CSSOM-view replaceable. r=smaug (5cb9b91f0)
- Bug 1151940 part 2. Add a convenience function in nsGlobalWindow for replacing a property on the window with a new value. r=smaug (2ba39331c)
- Bug 1151940 part 3. Make some writable cssom-view attributes that we only allow setting from chrome act the way readonly replaceables would when called from content. r=smaug (b485e1b44)
- Goanna -> Gecko (2c539d7be)
- Goanna -> Gecko (25d34e213)
- Bug 1148962 - Use TakeOwnershipOfErrorReporting in CPOW code (r=bholley) (96c997639)
- pointer style (a07fbffaa)
- Bug 1152577: Add 'aReason' argument to AutoEntryScript constructor, and provide plausible names for its instantiations. r=bholley (512fa27e2)
- bug 1155691 - Expose WindowRoot to chrome from window in webidl. r=smaug (235281924)
- Bug 404828 - No need to assert that the top window isn't reachable. r=smaug (d73154fa0)
- Bug 404828 - Followup: remove assertion expectations on a CLOSED TREE. a=tomcat (a5dabe1b7)
- Bug 1156102 - Mark nsGlobalWindowObserver::mWindow as MOZ_NON_OWNING_REF; r=baku (c0d4208b7)
- Bug 1107801 - Improve gamepad support on MacOS. r=ted (c591bd5ac)
- Goanna -> Gecko (d9b81bc9e)
- Bug 852944 - Gamepad API IPC; r=ted, r=baku (521892538)
- Bug 1143529 part 1. Stop manually calling WrapObject in DataStoreService::GetDataStoresResolve. r=baku (056ad6bfe)
- Bug 1143529 part 2. Tighten up the assert in binding Wrap methods. r=peterv (765a13325)
- Bug 1152169 - DataStoreService should check if the first revision exists, r=bent (ee371cc5d)
- Bug 1152169 followup: Mark FirstRevisionIdCallback methods Run() and HandleEvent() as 'override'. rs=ehsan (8186c4168)
- Bug 1143651 - don't use CallQueryInterface when the compiler can do the cast for us; r=ehsan (a50f0a54b)
- Bug 1144322 - Handle tabindex in overridden IsInteractiveHTMLContent methods. r=smaug (fd4b9beed)
- Bug 1086684 - Stash the full path for file inputs to avoid doing IPC at inopportune times. r=ehsan/bent/gps (b843b1efc)
- Bug 1143934 - Disallow mozSetFileNameArray in content processes. r=ehsan (42e5c8c6d)
- Bug 1143934 - Fix assorted forms mochitests for e10s-compatibility. r=smaug (7a3babfed)
- Bug 1143934 - Work around SessionStore dependency on current brokenness. r=ttaubert (5b0fcb5ce)
- Bug 956530 - Clear the delayed caret data when clicking on a selected part of a text control if the focus event handler selects the control; r=roc (2859f07b4)
- Bug 956530 follow-up: Fix the test failure on Windows 8 caused by the text box having a glowing outline as a result of being clicked on (d34e8da1a)
- Bug 1157898 part 1. Make code of the form "return rv.ErrorCode();" where rv is an ErrorResult use StealNSResult instead. r=peterv (800da50e2)
- Bug 1157898 part 2. Make code of the form "NS_ENSURE_SUCCESS(rv.ErrorCode(), rv.ErrorCode());" use Failed and StealNSResult instead. r=peterv (472432a83)
- Bug 1157898 part 3. Fix the remaining consumers of rv.ErrorCode() in NS_ENSURE_* expressions to not do that. r=peterv (d452807e7)
- Bug 1122238 part 1. Switch to using the new stackframe APIs in JSStackFrame. r=bholley (9d87b261a)
- Bug 1122238 part 2. Stop caching things in JSStackFrame when we're called over Xrays. r=bholley (83eda7275)
- Bug 1122238 part 3. Drop all the DOMException-cloning and sanitization gunk we added in bug 1107592 and bug 1107953 and bug 1117242 . r=bholley (f237aa948)
- add support for NetBSD/SPARC64 (065783b70)
- Bug 1153484 - Fetch should ignore invalid headers, but still process later headers. r=nsm (8925ddd77)
- Bug 1157754 part 2. Convert consumers of ErrorResult::ClearMessage() to the new better APIs we have for suppressing exceptions on ErrorResult. r=bkelly (6519fbd5e)
- Bug 1157754 part 3. Make ClearMessage private on ErrorResult. r=peterv (3fb218692)
- Bug 1157898 part 4. Add ErrorResult::ErrorCodeIs() and use it in various places to get rid of ErrorCode(). r=peterv (bed7bfb4c)
- Bug 1130686 - Refactor PromiseHolder in the service worker clients code. r=nsm (b3dbdcbfe)
- Bug 1130686 - Implement client.focus. r=baku (5dee6d850)
- Bug 1149163 part 1 - Clean up nsHTMLEditRules::GetInnerContent; r=froydnj (cc8f65b54)
- Bug 1149163 part 2 - Make nsDOMIterator infallible; r=froydnj (d975f6c62)
- Bug 1149163 part 3 - Clean up nsHTMLEditRules::BustUpInlinesAtBRs; r=froydnj (58155adad)
- Bug 1149163 part 4 - Allow use of temporary nsBoolDomIterFunctor; r=froydnj (dbafec00f)
- Bug 1149163 part 5 - Clean up nsHTMLEditRules::GetNodesForOperation; r=froydnj (41179d810)
- Bug 1149163 part 6 - Clean up nsHTMLEditRules::LookInsideDivBQandList; r=froydnj (0b757bf14)
- Bug 1149163 part 7 - Clean up nsHTMLEditRules::PromoteRange; r=froydnj (c49c714b1)
- Bug 1149163 part 8 - Clean up nsHTMLEditRules::GetPromotedRanges; r=froydnj (5163a0026)
- Bug 1148228 - Stop checking ul twice (43a22088c)
- Bug 1141017 - resurrect serif and monospace. r=ehsan (95a1b6fcf)
- Bug 1147412 part 1 - Make methods take nsINode*, not just nsIContent*; r=ehsan (7f762cdbe)
- Bug 1147412 part 2 - Clean up nsHTMLEditor::SetInlinePropertyOnTextNode; r=ehsan (faf805587)
- Bug 1147412 part 3 - Fix completely broken nsHTMLCSSUtils::IsCSSEquivalentToHTMLInlineStyleSet implementation; r=ehsan (73fea67c1)
- Bug 1147412 part 4 - Clean up nsHTMLEditor::GetInlinePropertyBase; r=ehsan (3265bfbce)
- Bug 1147412 part 5 - Clean up nsHTMLEditor::RemoveInlinePropertyImpl; r=ehsan (0f402bd7e)
- Bug 1147412 part 6 - Remove nsHTMLCSSUtils::IsCSSEditableProperty(nsIDOMNode*,...); r=ehsan (100e4038a)
- Bug 1147412 part 7 - Remove nsHTMLCSSUtils::GetComputedStyle(nsIDOMElement*); r=ehsan (6c51103bc)
- Bug 1147412 part 8 - Clean up nsHTMLCSSUtils::IsCSSInvertible; r=ehsan (01e60c446)
- Bug 1147412 part 9 - Convert some nsHTMLEditor members to Element; r=ehsan (e7efb1ac4)
- Bug 1147412 part 10 - Clean up nsHTMLCSSUtils::Get*Property, GetCSSInlinePropertyBase; r=ehsan (54154143d)
- Bug 1149163 part 9 - Clean up nsHTMLEditRules::GetNodesFromSelection; r=froydnj (5186308b9)
- Bug 1154701 part 1 - Clean up nsHTMLEditor::CreateListOfNodesToPaste; r=ehsan (ea95238d5)
- Bug 1153629 part 1 - Clean up nsHTMLEditRules::GetListActionNodes; r=ehsan (51f3b3e95)
- Bug 1153629 part 2 - Clean up nsHTMLEditRules::GetParagraphFormatNodes; r=ehsan (a27bd7751)
- Bug 1153629 part 3 - Clean up nsHTMLEditRules::GetNodesFromPoint; r=ehsan (edc7e4561)
- Bug 1153629 part 4 - Clean up nsHTMLEditRules::ListIsEmptyLine; r=ehsan (ce3289bc7)
- Bug 1153629 part 5 - Clean up nsHTMLEditRules::GetChildNodesForOperation; r=ehsan (b3a509dbf)
- Bug 1153629 part 6 - Clean up nsHTMLEditRules::MakeBlockquote; r=ehsan (cb3808182)
- Bug 1153629 part 7 - Clean up nsHTMLEditRules::RemoveBlockStyle, RemovePartOfBlock; r=ehsan (660b9f76e)
- Bug 1153629 part 8 - Clean up nsHTMLEditRules::ApplyBlockStyle; r=ehsan (f54f9538c)
- Bug 1153629 part 9 - Clean up nsHTMLEditRules::MakeTransitionList; r=ehsan (fb63cf6d8)
- Bug 1153629 part 10 - Clean up nsHTMLEditRules::AlignInnerBlocks; r=ehsan (752d2df7a)
- Bug 1153629 part 11 - Clean up nsHTMLEditRules::AdjustSpecialBreaks; r=ehsan (16ef0416b)
- Bug 1153629 part 12 - Clean up nsHTMLEditRules::RemoveEmptyNodes; r=ehsan (d528e70e6)
- Bug 1154701 part 2 - Use more OwningNonNull in editor; r=ehsan (85b1929e6)
- Bug 1154701 part 3 - Clean up nsHTMLEditor::GetListAndTableParents, DiscoverPartialListsAndTables, ScanForListAndTableStructure, ReplaceOrphanedStructure; r=ehsan (7fe31f058)
- Bug 1154701 part 4 - Switch nsHTMLEditor::mContentFilters to nsTArray; r=ehsan (64e6dd160)
- Bug 1154701 part 5 - Switch nsHTMLEditor::objectResizeEventListeners to nsTArray; r=ehsan (036bc65fe)
- Bug 1154701 part 6 - Clean up nsHTMLEditor::SetInlinePropertyOnNodeImpl; r=ehsan (2d619ca16)
- Bug 1154701 part 7 - Clean up nsHTMLEditor::SetInlineProperty; r=ehsan (7a367d31b)
- Bug 1154701 part 8 - Clean up nsHTMLEditor::SetInlinePropertyOnNode; r=ehsan (707c07d93)
- Bug 1154701 part 9 - Clean up nsHTMLEditor::RelativeFontChange; r=ehsan (273ae9c64)
- Bug 1154701 part 10 - Switch nsEditor::mActionListeners to nsTArray; r=ehsan (d2b5732fe)
- Bug 1154701 part 11 - Switch nsEditor::mEditorObservers to nsTArray; r=ehsan (25a5af12e)
- Bug 1154701 part 12 - Switch nsEditor::mDocStateListeners to nsTArray; r=ehsan (665af0792)
- Bug 1154701 part 13 - Clean up nsHTMLEditor::SetCSSBackgroundColor; r=ehsan (ba424ade8)
- Bug 1154701 part 14 - Remove unused nsCOMArray cruft; r=ehsan (3a8679a67)
- Bug 1101651 - Part 1: xpcomrt version of dom media library need for standalone webrtcs. r=jesup (ae37b5464)
- Bug 1137447 - New app update telemetry for patch type (complete or partial), extended error codes, and general cleanup. r=bbondy (c736ae502)
2020-06-12 21:48:57 +08:00

1012 lines
31 KiB
C++

/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 sw=2 et tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* nsIContentSerializer implementation that can be used with an
* nsIDocumentEncoder to convert an XHTML (not HTML!) DOM to an XHTML
* string that could be parsed into more or less the original DOM.
*/
#include "nsXHTMLContentSerializer.h"
#include "nsIDOMElement.h"
#include "nsIContent.h"
#include "nsIDocument.h"
#include "nsNameSpaceManager.h"
#include "nsString.h"
#include "nsUnicharUtils.h"
#include "nsXPIDLString.h"
#include "nsIServiceManager.h"
#include "nsIDocumentEncoder.h"
#include "nsGkAtoms.h"
#include "nsIURI.h"
#include "nsNetUtil.h"
#include "nsEscape.h"
#include "nsITextToSubURI.h"
#include "nsCRT.h"
#include "nsIParserService.h"
#include "nsContentUtils.h"
#include "nsLWBrkCIID.h"
#include "nsIScriptElement.h"
#include "nsAttrName.h"
#include "nsParserConstants.h"
#include "nsComputedDOMStyle.h"
#include "mozilla/dom/Element.h"
static const int32_t kLongLineLen = 128;
#define kXMLNS "xmlns"
nsresult
NS_NewXHTMLContentSerializer(nsIContentSerializer** aSerializer)
{
nsRefPtr<nsXHTMLContentSerializer> it = new nsXHTMLContentSerializer();
it.forget(aSerializer);
return NS_OK;
}
nsXHTMLContentSerializer::nsXHTMLContentSerializer()
: mIsHTMLSerializer(false)
{
}
nsXHTMLContentSerializer::~nsXHTMLContentSerializer()
{
NS_ASSERTION(mOLStateStack.IsEmpty(), "Expected OL State stack to be empty");
}
NS_IMETHODIMP
nsXHTMLContentSerializer::Init(uint32_t aFlags, uint32_t aWrapColumn,
const char* aCharSet, bool aIsCopying,
bool aRewriteEncodingDeclaration)
{
// The previous version of the HTML serializer did implicit wrapping
// when there is no flags, so we keep wrapping in order to keep
// compatibility with the existing calling code
// XXXLJ perhaps should we remove this default settings later ?
if (aFlags & nsIDocumentEncoder::OutputFormatted ) {
aFlags = aFlags | nsIDocumentEncoder::OutputWrap;
}
nsresult rv;
rv = nsXMLContentSerializer::Init(aFlags, aWrapColumn, aCharSet, aIsCopying, aRewriteEncodingDeclaration);
NS_ENSURE_SUCCESS(rv, rv);
mRewriteEncodingDeclaration = aRewriteEncodingDeclaration;
mIsCopying = aIsCopying;
mIsFirstChildOfOL = false;
mInBody = 0;
mDisableEntityEncoding = 0;
mBodyOnly = (mFlags & nsIDocumentEncoder::OutputBodyOnly) ? true
: false;
// set up entity converter if we are going to need it
if (mFlags & nsIDocumentEncoder::OutputEncodeW3CEntities) {
mEntityConverter = do_CreateInstance(NS_ENTITYCONVERTER_CONTRACTID);
}
return NS_OK;
}
// See if the string has any lines longer than longLineLen:
// if so, we presume formatting is wonky (e.g. the node has been edited)
// and we'd better rewrap the whole text node.
bool
nsXHTMLContentSerializer::HasLongLines(const nsString& text, int32_t& aLastNewlineOffset)
{
uint32_t start=0;
uint32_t theLen = text.Length();
bool rv = false;
aLastNewlineOffset = kNotFound;
for (start = 0; start < theLen; ) {
int32_t eol = text.FindChar('\n', start);
if (eol < 0) {
eol = text.Length();
}
else {
aLastNewlineOffset = eol;
}
if (int32_t(eol - start) > kLongLineLen)
rv = true;
start = eol + 1;
}
return rv;
}
NS_IMETHODIMP
nsXHTMLContentSerializer::AppendText(nsIContent* aText,
int32_t aStartOffset,
int32_t aEndOffset,
nsAString& aStr)
{
NS_ENSURE_ARG(aText);
nsAutoString data;
nsresult rv;
rv = AppendTextData(aText, aStartOffset, aEndOffset, data, true);
if (NS_FAILED(rv))
return NS_ERROR_FAILURE;
if (mDoRaw || PreLevel() > 0) {
NS_ENSURE_TRUE(AppendToStringConvertLF(data, aStr), NS_ERROR_OUT_OF_MEMORY);
}
else if (mDoFormat) {
NS_ENSURE_TRUE(AppendToStringFormatedWrapped(data, aStr), NS_ERROR_OUT_OF_MEMORY);
}
else if (mDoWrap) {
NS_ENSURE_TRUE(AppendToStringWrapped(data, aStr), NS_ERROR_OUT_OF_MEMORY);
}
else {
int32_t lastNewlineOffset = kNotFound;
if (HasLongLines(data, lastNewlineOffset)) {
// We have long lines, rewrap
mDoWrap = true;
bool result = AppendToStringWrapped(data, aStr);
mDoWrap = false;
NS_ENSURE_TRUE(result, NS_ERROR_OUT_OF_MEMORY);
}
else {
NS_ENSURE_TRUE(AppendToStringConvertLF(data, aStr), NS_ERROR_OUT_OF_MEMORY);
}
}
return NS_OK;
}
nsresult
nsXHTMLContentSerializer::EscapeURI(nsIContent* aContent, const nsAString& aURI, nsAString& aEscapedURI)
{
// URL escape %xx cannot be used in JS.
// No escaping if the scheme is 'javascript'.
if (IsJavaScript(aContent, nsGkAtoms::href, kNameSpaceID_None, aURI)) {
aEscapedURI = aURI;
return NS_OK;
}
// nsITextToSubURI does charset convert plus uri escape
// This is needed to convert to a document charset which is needed to support existing browsers.
// But we eventually want to use UTF-8 instead of a document charset, then the code would be much simpler.
// See HTML 4.01 spec, "Appendix B.2.1 Non-ASCII characters in URI attribute values"
nsCOMPtr<nsITextToSubURI> textToSubURI;
nsAutoString uri(aURI); // in order to use FindCharInSet()
nsresult rv = NS_OK;
if (!mCharset.IsEmpty() && !IsASCII(uri)) {
textToSubURI = do_GetService(NS_ITEXTTOSUBURI_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
}
int32_t start = 0;
int32_t end;
nsAutoString part;
nsXPIDLCString escapedURI;
aEscapedURI.Truncate(0);
// Loop and escape parts by avoiding escaping reserved characters
// (and '%', '#', as well as '[' and ']' for IPv6 address literals).
while ((end = uri.FindCharInSet("%#;/?:@&=+$,[]", start)) != -1) {
part = Substring(aURI, start, (end-start));
if (textToSubURI && !IsASCII(part)) {
rv = textToSubURI->ConvertAndEscape(mCharset.get(), part.get(), getter_Copies(escapedURI));
NS_ENSURE_SUCCESS(rv, rv);
}
else {
escapedURI.Adopt(nsEscape(NS_ConvertUTF16toUTF8(part).get(), url_Path));
}
AppendASCIItoUTF16(escapedURI, aEscapedURI);
// Append a reserved character without escaping.
part = Substring(aURI, end, 1);
aEscapedURI.Append(part);
start = end + 1;
}
if (start < (int32_t) aURI.Length()) {
// Escape the remaining part.
part = Substring(aURI, start, aURI.Length()-start);
if (textToSubURI) {
rv = textToSubURI->ConvertAndEscape(mCharset.get(), part.get(), getter_Copies(escapedURI));
NS_ENSURE_SUCCESS(rv, rv);
}
else {
escapedURI.Adopt(nsEscape(NS_ConvertUTF16toUTF8(part).get(), url_Path));
}
AppendASCIItoUTF16(escapedURI, aEscapedURI);
}
return rv;
}
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;
}
const nsAttrName* name = aContent->GetAttrNameAt(index);
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);
}
aContent->GetAttr(namespaceID, attrName, 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 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);
}
}
// 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;
}
bool
nsXHTMLContentSerializer::AppendEndOfElementStart(nsIContent *aOriginalElement,
nsIAtom * aName,
int32_t aNamespaceID,
nsAString& aStr)
{
// this method is not called by nsHTMLContentSerializer
// so we don't have to check HTML element, just XHTML
NS_ASSERTION(!mIsHTMLSerializer, "nsHTMLContentSerializer shouldn't call this method !");
if (kNameSpaceID_XHTML != aNamespaceID) {
return nsXMLContentSerializer::AppendEndOfElementStart(aOriginalElement, aName,
aNamespaceID, aStr);
}
nsIContent* content = aOriginalElement;
// for non empty elements, even if they are not a container, we always
// serialize their content, because the XHTML element could contain non XHTML
// nodes useful in some context, like in an XSLT stylesheet
if (HasNoChildren(content)) {
nsIParserService* parserService = nsContentUtils::GetParserService();
if (parserService) {
bool isContainer;
parserService->
IsContainer(parserService->HTMLCaseSensitiveAtomTagToId(aName),
isContainer);
if (!isContainer) {
// for backward compatibility with HTML 4 user agents
// only non-container HTML elements can be closed immediatly,
// and a space is added before />
return AppendToString(NS_LITERAL_STRING(" />"), aStr);
}
}
}
return AppendToString(kGreaterThan, aStr);
}
bool
nsXHTMLContentSerializer::AfterElementStart(nsIContent* aContent,
nsIContent* aOriginalElement,
nsAString& aStr)
{
if (mRewriteEncodingDeclaration &&
aContent->IsHTMLElement(nsGkAtoms::head)) {
// Check if there already are any content-type meta children.
// If there are, they will be modified to use the correct charset.
// If there aren't, we'll insert one here.
bool hasMeta = false;
for (nsIContent* child = aContent->GetFirstChild();
child;
child = child->GetNextSibling()) {
if (child->IsHTMLElement(nsGkAtoms::meta) &&
child->HasAttr(kNameSpaceID_None, nsGkAtoms::content)) {
nsAutoString header;
child->GetAttr(kNameSpaceID_None, nsGkAtoms::httpEquiv, header);
if (header.LowerCaseEqualsLiteral("content-type")) {
hasMeta = true;
break;
}
}
}
if (!hasMeta) {
NS_ENSURE_TRUE(AppendNewLineToString(aStr), false);
if (mDoFormat) {
NS_ENSURE_TRUE(AppendIndentation(aStr), false);
}
NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING("<meta http-equiv=\"content-type\""), aStr), false);
NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING(" content=\"text/html; charset="), aStr), false);
NS_ENSURE_TRUE(AppendToString(NS_ConvertASCIItoUTF16(mCharset), aStr), false);
if (mIsHTMLSerializer) {
NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING("\">"), aStr), false);
} else {
NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING("\" />"), aStr), false);
}
}
}
return true;
}
void
nsXHTMLContentSerializer::AfterElementEnd(nsIContent * aContent,
nsAString& aStr)
{
NS_ASSERTION(!mIsHTMLSerializer, "nsHTMLContentSerializer shouldn't call this method !");
// this method is not called by nsHTMLContentSerializer
// so we don't have to check HTML element, just XHTML
if (aContent->IsHTMLElement(nsGkAtoms::body)) {
--mInBody;
}
}
NS_IMETHODIMP
nsXHTMLContentSerializer::AppendDocumentStart(nsIDocument *aDocument,
nsAString& aStr)
{
if (!mBodyOnly)
return nsXMLContentSerializer::AppendDocumentStart(aDocument, aStr);
return NS_OK;
}
bool
nsXHTMLContentSerializer::CheckElementStart(nsIContent * aContent,
bool & aForceFormat,
nsAString& aStr,
nsresult& aResult)
{
aResult = NS_OK;
// The _moz_dirty attribute is emitted by the editor to
// indicate that this element should be pretty printed
// even if we're not in pretty printing mode
aForceFormat = !(mFlags & nsIDocumentEncoder::OutputIgnoreMozDirty) &&
aContent->HasAttr(kNameSpaceID_None, nsGkAtoms::mozdirty);
if (aContent->IsHTMLElement(nsGkAtoms::br) &&
(mFlags & nsIDocumentEncoder::OutputNoFormattingInPre) &&
PreLevel() > 0) {
AppendNewLineToString(aStr);
return false;
}
if (aContent->IsHTMLElement(nsGkAtoms::body)) {
++mInBody;
}
return true;
}
bool
nsXHTMLContentSerializer::CheckElementEnd(nsIContent * aContent,
bool & aForceFormat,
nsAString& aStr)
{
NS_ASSERTION(!mIsHTMLSerializer, "nsHTMLContentSerializer shouldn't call this method !");
aForceFormat = !(mFlags & nsIDocumentEncoder::OutputIgnoreMozDirty) &&
aContent->HasAttr(kNameSpaceID_None, nsGkAtoms::mozdirty);
// this method is not called by nsHTMLContentSerializer
// so we don't have to check HTML element, just XHTML
if (aContent->IsHTMLElement()) {
if (mIsCopying && aContent->IsHTMLElement(nsGkAtoms::ol)) {
NS_ASSERTION((!mOLStateStack.IsEmpty()), "Cannot have an empty OL Stack");
/* Though at this point we must always have an state to be deleted as all
the OL opening tags are supposed to push an olState object to the stack*/
if (!mOLStateStack.IsEmpty()) {
mOLStateStack.RemoveElementAt(mOLStateStack.Length() -1);
}
}
if (HasNoChildren(aContent)) {
nsIParserService* parserService = nsContentUtils::GetParserService();
if (parserService) {
bool isContainer;
parserService->
IsContainer(parserService->HTMLCaseSensitiveAtomTagToId(
aContent->NodeInfo()->NameAtom()),
isContainer);
if (!isContainer) {
// non-container HTML elements are already closed,
// see AppendEndOfElementStart
return false;
}
}
}
// for backward compatibility with old HTML user agents,
// empty elements should have an ending tag, so we mustn't call
// nsXMLContentSerializer::CheckElementEnd
return true;
}
bool dummyFormat;
return nsXMLContentSerializer::CheckElementEnd(aContent, dummyFormat, aStr);
}
bool
nsXHTMLContentSerializer::AppendAndTranslateEntities(const nsAString& aStr,
nsAString& aOutputStr)
{
if (mBodyOnly && !mInBody) {
return true;
}
if (mDisableEntityEncoding) {
return aOutputStr.Append(aStr, mozilla::fallible);
}
return nsXMLContentSerializer::AppendAndTranslateEntities(aStr, aOutputStr);
}
bool
nsXHTMLContentSerializer::IsShorthandAttr(const nsIAtom* aAttrName,
const nsIAtom* aElementName)
{
// checked
if ((aAttrName == nsGkAtoms::checked) &&
(aElementName == nsGkAtoms::input)) {
return true;
}
// compact
if ((aAttrName == nsGkAtoms::compact) &&
(aElementName == nsGkAtoms::dir ||
aElementName == nsGkAtoms::dl ||
aElementName == nsGkAtoms::menu ||
aElementName == nsGkAtoms::ol ||
aElementName == nsGkAtoms::ul)) {
return true;
}
// declare
if ((aAttrName == nsGkAtoms::declare) &&
(aElementName == nsGkAtoms::object)) {
return true;
}
// defer
if ((aAttrName == nsGkAtoms::defer) &&
(aElementName == nsGkAtoms::script)) {
return true;
}
// disabled
if ((aAttrName == nsGkAtoms::disabled) &&
(aElementName == nsGkAtoms::button ||
aElementName == nsGkAtoms::input ||
aElementName == nsGkAtoms::optgroup ||
aElementName == nsGkAtoms::option ||
aElementName == nsGkAtoms::select ||
aElementName == nsGkAtoms::textarea)) {
return true;
}
// ismap
if ((aAttrName == nsGkAtoms::ismap) &&
(aElementName == nsGkAtoms::img ||
aElementName == nsGkAtoms::input)) {
return true;
}
// multiple
if ((aAttrName == nsGkAtoms::multiple) &&
(aElementName == nsGkAtoms::select)) {
return true;
}
// noresize
if ((aAttrName == nsGkAtoms::noresize) &&
(aElementName == nsGkAtoms::frame)) {
return true;
}
// noshade
if ((aAttrName == nsGkAtoms::noshade) &&
(aElementName == nsGkAtoms::hr)) {
return true;
}
// nowrap
if ((aAttrName == nsGkAtoms::nowrap) &&
(aElementName == nsGkAtoms::td ||
aElementName == nsGkAtoms::th)) {
return true;
}
// readonly
if ((aAttrName == nsGkAtoms::readonly) &&
(aElementName == nsGkAtoms::input ||
aElementName == nsGkAtoms::textarea)) {
return true;
}
// selected
if ((aAttrName == nsGkAtoms::selected) &&
(aElementName == nsGkAtoms::option)) {
return true;
}
// autoplay and controls
if ((aElementName == nsGkAtoms::video || aElementName == nsGkAtoms::audio) &&
(aAttrName == nsGkAtoms::autoplay || aAttrName == nsGkAtoms::muted ||
aAttrName == nsGkAtoms::controls)) {
return true;
}
return false;
}
bool
nsXHTMLContentSerializer::LineBreakBeforeOpen(int32_t aNamespaceID, nsIAtom* aName)
{
if (aNamespaceID != kNameSpaceID_XHTML) {
return mAddSpace;
}
if (aName == nsGkAtoms::title ||
aName == nsGkAtoms::meta ||
aName == nsGkAtoms::link ||
aName == nsGkAtoms::style ||
aName == nsGkAtoms::select ||
aName == nsGkAtoms::option ||
aName == nsGkAtoms::script ||
aName == nsGkAtoms::html) {
return true;
}
else {
nsIParserService* parserService = nsContentUtils::GetParserService();
if (parserService) {
bool res;
parserService->
IsBlock(parserService->HTMLCaseSensitiveAtomTagToId(aName), res);
return res;
}
}
return mAddSpace;
}
bool
nsXHTMLContentSerializer::LineBreakAfterOpen(int32_t aNamespaceID, nsIAtom* aName)
{
if (aNamespaceID != kNameSpaceID_XHTML) {
return false;
}
if ((aName == nsGkAtoms::html) ||
(aName == nsGkAtoms::head) ||
(aName == nsGkAtoms::body) ||
(aName == nsGkAtoms::ul) ||
(aName == nsGkAtoms::ol) ||
(aName == nsGkAtoms::dl) ||
(aName == nsGkAtoms::table) ||
(aName == nsGkAtoms::tbody) ||
(aName == nsGkAtoms::tr) ||
(aName == nsGkAtoms::br) ||
(aName == nsGkAtoms::meta) ||
(aName == nsGkAtoms::link) ||
(aName == nsGkAtoms::script) ||
(aName == nsGkAtoms::select) ||
(aName == nsGkAtoms::map) ||
(aName == nsGkAtoms::area) ||
(aName == nsGkAtoms::style)) {
return true;
}
return false;
}
bool
nsXHTMLContentSerializer::LineBreakBeforeClose(int32_t aNamespaceID, nsIAtom* aName)
{
if (aNamespaceID != kNameSpaceID_XHTML) {
return false;
}
if ((aName == nsGkAtoms::html) ||
(aName == nsGkAtoms::head) ||
(aName == nsGkAtoms::body) ||
(aName == nsGkAtoms::ul) ||
(aName == nsGkAtoms::ol) ||
(aName == nsGkAtoms::dl) ||
(aName == nsGkAtoms::select) ||
(aName == nsGkAtoms::table) ||
(aName == nsGkAtoms::tbody)) {
return true;
}
return false;
}
bool
nsXHTMLContentSerializer::LineBreakAfterClose(int32_t aNamespaceID, nsIAtom* aName)
{
if (aNamespaceID != kNameSpaceID_XHTML) {
return false;
}
if ((aName == nsGkAtoms::html) ||
(aName == nsGkAtoms::head) ||
(aName == nsGkAtoms::body) ||
(aName == nsGkAtoms::tr) ||
(aName == nsGkAtoms::th) ||
(aName == nsGkAtoms::td) ||
(aName == nsGkAtoms::pre) ||
(aName == nsGkAtoms::title) ||
(aName == nsGkAtoms::li) ||
(aName == nsGkAtoms::dt) ||
(aName == nsGkAtoms::dd) ||
(aName == nsGkAtoms::blockquote) ||
(aName == nsGkAtoms::select) ||
(aName == nsGkAtoms::option) ||
(aName == nsGkAtoms::p) ||
(aName == nsGkAtoms::map) ||
(aName == nsGkAtoms::div)) {
return true;
}
else {
nsIParserService* parserService = nsContentUtils::GetParserService();
if (parserService) {
bool res;
parserService->
IsBlock(parserService->HTMLCaseSensitiveAtomTagToId(aName), res);
return res;
}
}
return false;
}
void
nsXHTMLContentSerializer::MaybeEnterInPreContent(nsIContent* aNode)
{
if (!ShouldMaintainPreLevel() ||
!aNode->IsHTMLElement()) {
return;
}
if (IsElementPreformatted(aNode) ||
aNode->IsAnyOfHTMLElements(nsGkAtoms::script,
nsGkAtoms::style,
nsGkAtoms::noscript,
nsGkAtoms::noframes)) {
PreLevel()++;
}
}
void
nsXHTMLContentSerializer::MaybeLeaveFromPreContent(nsIContent* aNode)
{
if (!ShouldMaintainPreLevel() ||
!aNode->IsHTMLElement()) {
return;
}
if (IsElementPreformatted(aNode) ||
aNode->IsAnyOfHTMLElements(nsGkAtoms::script,
nsGkAtoms::style,
nsGkAtoms::noscript,
nsGkAtoms::noframes)) {
--PreLevel();
}
}
bool
nsXHTMLContentSerializer::IsElementPreformatted(nsIContent* aNode)
{
MOZ_ASSERT(ShouldMaintainPreLevel(), "We should not be calling this needlessly");
if (!aNode->IsElement()) {
return false;
}
nsRefPtr<nsStyleContext> styleContext =
nsComputedDOMStyle::GetStyleContextForElementNoFlush(aNode->AsElement(),
nullptr, nullptr);
if (styleContext) {
const nsStyleText* textStyle = styleContext->StyleText();
return textStyle->WhiteSpaceOrNewlineIsSignificant();
}
return false;
}
bool
nsXHTMLContentSerializer::SerializeLIValueAttribute(nsIContent* aElement,
nsAString& aStr)
{
// We are copying and we are at the "first" LI node of OL in selected range.
// It may not be the first LI child of OL but it's first in the selected range.
// Note that we get into this condition only once per a OL.
bool found = false;
nsCOMPtr<nsIDOMNode> currNode = do_QueryInterface(aElement);
nsAutoString valueStr;
olState state (0, false);
if (!mOLStateStack.IsEmpty()) {
state = mOLStateStack[mOLStateStack.Length()-1];
// isFirstListItem should be true only before the serialization of the
// first item in the list.
state.isFirstListItem = false;
mOLStateStack[mOLStateStack.Length()-1] = state;
}
int32_t startVal = state.startVal;
int32_t offset = 0;
// Traverse previous siblings until we find one with "value" attribute.
// offset keeps track of how many previous siblings we had tocurrNode traverse.
while (currNode && !found) {
nsCOMPtr<nsIDOMElement> currElement = do_QueryInterface(currNode);
// currElement may be null if it were a text node.
if (currElement) {
nsAutoString tagName;
currElement->GetTagName(tagName);
if (tagName.LowerCaseEqualsLiteral("li")) {
currElement->GetAttribute(NS_LITERAL_STRING("value"), valueStr);
if (valueStr.IsEmpty())
offset++;
else {
found = true;
nsresult rv = NS_OK;
startVal = valueStr.ToInteger(&rv);
}
}
}
nsCOMPtr<nsIDOMNode> tmp;
currNode->GetPreviousSibling(getter_AddRefs(tmp));
currNode.swap(tmp);
}
// If LI was not having "value", Set the "value" attribute for it.
// Note that We are at the first LI in the selected range of OL.
if (offset == 0 && found) {
// offset = 0 => LI itself has the value attribute and we did not need to traverse back.
// Just serialize value attribute like other tags.
NS_ENSURE_TRUE(SerializeAttr(EmptyString(), NS_LITERAL_STRING("value"),
valueStr, aStr, false), false);
}
else if (offset == 1 && !found) {
/*(offset = 1 && !found) means either LI is the first child node of OL
and LI is not having "value" attribute.
In that case we would not like to set "value" attribute to reduce the changes.
*/
//do nothing...
}
else if (offset > 0) {
// Set value attribute.
nsAutoString valueStr;
//As serializer needs to use this valueAttr we are creating here,
valueStr.AppendInt(startVal + offset);
NS_ENSURE_TRUE(SerializeAttr(EmptyString(), NS_LITERAL_STRING("value"),
valueStr, aStr, false), false);
}
return true;
}
bool
nsXHTMLContentSerializer::IsFirstChildOfOL(nsIContent* aElement)
{
nsCOMPtr<nsIDOMNode> node = do_QueryInterface(aElement);
nsAutoString parentName;
nsCOMPtr<nsIDOMNode> parentNode;
node->GetParentNode(getter_AddRefs(parentNode));
if (parentNode)
parentNode->GetNodeName(parentName);
else
return false;
if (parentName.LowerCaseEqualsLiteral("ol")) {
if (!mOLStateStack.IsEmpty()) {
olState state = mOLStateStack[mOLStateStack.Length()-1];
if (state.isFirstListItem)
return true;
}
return false;
}
else
return false;
}
bool
nsXHTMLContentSerializer::HasNoChildren(nsIContent * aContent) {
for (nsIContent* child = aContent->GetFirstChild();
child;
child = child->GetNextSibling()) {
if (!child->IsNodeOfType(nsINode::eTEXT))
return false;
if (child->TextLength())
return false;
}
return true;
}