/* 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/. */

#include "mozilla/dom/CSSStyleRule.h"

#include "PseudoStyleType.h"
#include "mozilla/CSSEnabledState.h"
#include "mozilla/PseudoStyleRequest.h"
#include "mozilla/PseudoStyleType.h"
#include "mozilla/ServoBindings.h"
#include "mozilla/dom/CSSScopeRule.h"
#include "mozilla/dom/CSSStyleRuleBinding.h"
#include "mozilla/dom/ContentList.h"
#include "mozilla/dom/ShadowRoot.h"
#include "mozilla/dom/StylePropertyMap.h"
#include "nsISupports.h"

namespace mozilla::dom {

// -- CSSStyleRuleDeclaration ---------------------------------------

CSSStyleRuleDeclaration::CSSStyleRuleDeclaration(already_AddRefed<Block> aDecls)
    : mDecls(aDecls) {}

CSSStyleRuleDeclaration::~CSSStyleRuleDeclaration() = default;

// QueryInterface implementation for CSSStyleRuleDeclaration
NS_INTERFACE_MAP_BEGIN(CSSStyleRuleDeclaration)
  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
  // We forward the cycle collection interfaces to Rule(), which is
  // never null (in fact, we're part of that object!)
  if (aIID.Equals(NS_GET_IID(nsCycleCollectionISupports)) ||
      aIID.Equals(NS_GET_IID(nsXPCOMCycleCollectionParticipant))) {
    return Rule()->QueryInterface(aIID, aInstancePtr);
  }
NS_INTERFACE_MAP_END_INHERITING(nsDOMCSSDeclaration)

NS_IMPL_ADDREF_USING_AGGREGATOR(CSSStyleRuleDeclaration, Rule())
NS_IMPL_RELEASE_USING_AGGREGATOR(CSSStyleRuleDeclaration, Rule())

/* nsDOMCSSDeclaration implementation */

css::Rule* CSSStyleRuleDeclaration::GetParentRule() { return Rule(); }

nsINode* CSSStyleRuleDeclaration::GetAssociatedNode() const {
  return Rule()->GetAssociatedDocumentOrShadowRoot();
}

nsISupports* CSSStyleRuleDeclaration::GetParentObject() const {
  return Rule()->GetParentObject();
}

StyleLockedDeclarationBlock* CSSStyleRuleDeclaration::GetOrCreateCSSDeclaration(
    Operation aOperation, Block** aCreated) {
  if (aOperation != Operation::Read) {
    if (StyleSheet* sheet = Rule()->GetStyleSheet()) {
      sheet->WillDirty();
    }
  }
  return mDecls;
}

void CSSStyleRuleDeclaration::SetRawAfterClone(RefPtr<Block> aRaw) {
  mDecls = std::move(aRaw);
}

void CSSStyleRule::SetRawAfterClone(RefPtr<StyleLockedStyleRule> aRaw) {
  mRawRule = std::move(aRaw);
  mDecls.SetRawAfterClone(Servo_StyleRule_GetStyle(mRawRule).Consume());
  GroupRule::DidSetRawAfterClone();
}

already_AddRefed<StyleLockedCssRules> CSSStyleRule::GetOrCreateRawRules() {
  return Servo_StyleRule_EnsureRules(mRawRule, IsReadOnly()).Consume();
}

nsresult CSSStyleRuleDeclaration::SetCSSDeclaration(
    Block* aDecl, MutationClosureData* aClosureData) {
  CSSStyleRule* rule = Rule();
  RefPtr<Block> oldDecls;
  if (aDecl != mDecls) {
    oldDecls = std::move(mDecls);
    Servo_StyleRule_SetStyle(rule->Raw(), aDecl);
    mDecls = aDecl;
  }
  if (StyleSheet* sheet = rule->GetStyleSheet()) {
    sheet->RuleChanged(rule, {StyleRuleChangeKind::StyleRuleDeclarations,
                              oldDecls ? oldDecls.get() : aDecl, aDecl});
  }
  return NS_OK;
}

nsDOMCSSDeclaration::ParsingEnvironment
CSSStyleRuleDeclaration::GetParsingEnvironment(nsIPrincipal*) const {
  return GetParsingEnvironmentForRule(Rule(), StyleCssRuleType::Style);
}

// -- CSSStyleRule --------------------------------------------------

CSSStyleRule::CSSStyleRule(already_AddRefed<StyleLockedStyleRule> aRawRule,
                           StyleSheet* aSheet, css::Rule* aParentRule,
                           uint32_t aLine, uint32_t aColumn)
    : GroupRule(aSheet, aParentRule, aLine, aColumn),
      mRawRule(aRawRule),
      mDecls(Servo_StyleRule_GetStyle(mRawRule).Consume()) {}

NS_IMPL_ISUPPORTS_CYCLE_COLLECTION_INHERITED_0(CSSStyleRule, GroupRule)

NS_IMPL_CYCLE_COLLECTION_CLASS(CSSStyleRule)

NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(CSSStyleRule, GroupRule)
  // Keep this in sync with IsCCLeaf.

  // XXX The comment below seems to be incorrect/confusing, the TraceWrapper
  // call is needed because CSSStyleRuleDeclaration doesn't support cycle
  // collection?
  // This appears to have been done for performance reasons, but it's unclear
  // whether it's still a good idea.

  // Trace the wrapper for our declaration.  This just expands out
  // NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER which we can't use
  // directly because the wrapper is on the declaration, not on us.
  tmp->mDecls.TraceWrapper(aCallbacks, aClosure);
NS_IMPL_CYCLE_COLLECTION_TRACE_END

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(CSSStyleRule)
  // Keep this in sync with IsCCLeaf.

  NS_IMPL_CYCLE_COLLECTION_UNLINK(mStyleMap)

  // Unlink the wrapper for our declaration.
  //
  // Note that this has to happen before unlinking css::Rule.
  tmp->UnlinkDeclarationWrapper(tmp->mDecls);
  NS_IMPL_CYCLE_COLLECTION_UNLINK_WEAK_PTR
NS_IMPL_CYCLE_COLLECTION_UNLINK_END_INHERITED(GroupRule)

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(CSSStyleRule, GroupRule)
  // Keep this in sync with IsCCLeaf.

  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStyleMap)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

bool CSSStyleRule::IsCCLeaf() const {
  if (!GroupRule::IsCCLeaf()) {
    return false;
  }

  if (mStyleMap) {
    return false;
  }

  return !mDecls.PreservingWrapper();
}

size_t CSSStyleRule::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
  size_t n = aMallocSizeOf(this);

  // Measurement of the following members may be added later if DMD finds it
  // is worthwhile:
  // - mRawRule
  // - mStyleMap
  // - mDecls

  return n;
}

#ifdef DEBUG
void CSSStyleRule::List(FILE* out, int32_t aIndent) const {
  nsAutoCString str;
  for (int32_t i = 0; i < aIndent; i++) {
    str.AppendLiteral("  ");
  }
  Servo_StyleRule_Debug(mRawRule, &str);
  fprintf_stderr(out, "%s\n", str.get());
}
#endif

/* CSSRule implementation */

StyleCssRuleType CSSStyleRule::Type() const { return StyleCssRuleType::Style; }

void CSSStyleRule::GetCssText(nsACString& aCssText) const {
  Servo_StyleRule_GetCssText(mRawRule, &aCssText);
}

/* CSSStyleRule implementation */

const StyleLockedDeclarationBlock* CSSStyleRule::RawStyle() const {
  return mDecls.mDecls.get();
}

StyleLockedDeclarationBlock& CSSStyleRule::GetDeclarationBlock() const {
  return *mDecls.mDecls;
}

void CSSStyleRule::GetSelectorText(nsACString& aSelectorText) {
  Servo_StyleRule_GetSelectorText(mRawRule, &aSelectorText);
}

void CSSStyleRule::SetSelectorText(const nsACString& aSelectorText) {
  if (IsReadOnly()) {
    return;
  }

  StyleSheet* sheet = GetStyleSheet();
  if (!sheet) {
    return;
  }
  sheet->WillDirty();

  auto state = ContainingRuleState::From(mParentRule);

  // TODO(emilio): May actually be more efficient to handle this as rule
  // removal + addition, from the point of view of invalidation...
  const StyleStylesheetContents* contents = sheet->RawContents();
  if (Servo_StyleRule_SetSelectorText(
          contents, mRawRule, &aSelectorText,
          state.mParseRelativeType.ptrOr(nullptr))) {
    sheet->RuleChanged(this, StyleRuleChangeKind::Generic);
  }
}

uint32_t CSSStyleRule::SelectorCount() const {
  return Servo_StyleRule_GetSelectorCount(mRawRule);
}

static void CollectStyleRules(CSSStyleRule& aDeepestRule, bool aDesugared,
                              nsTArray<const StyleLockedStyleRule*>& aResult,
                              nsTArray<StyleScopeRuleData>* aScopes = nullptr) {
  aResult.AppendElement(aDeepestRule.Raw());
  if (aDesugared) {
    for (auto* rule = aDeepestRule.GetParentRule(); rule;
         rule = rule->GetParentRule()) {
      if (rule->Type() == StyleCssRuleType::Style) {
        aResult.AppendElement(static_cast<CSSStyleRule*>(rule)->Raw());
      } else if (aScopes && rule->Type() == StyleCssRuleType::Scope) {
        MOZ_ASSERT(aResult.Length() > 0, "Innermost rule wasn't a style rule?");
        aScopes->AppendElement(StyleScopeRuleData{
            static_cast<CSSScopeRule*>(rule)->Raw(),
            rule->GetStyleSheet(),
            aResult.Length() - 1,
        });
      }
    }
  }
}

void CSSStyleRule::GetSelectorDataAtIndex(uint32_t aSelectorIndex,
                                          bool aDesugared, nsACString* aText,
                                          uint64_t* aSpecificity) {
  AutoTArray<const StyleLockedStyleRule*, 8> rules;
  CollectStyleRules(*this, aDesugared, rules);
  Servo_StyleRule_GetSelectorDataAtIndex(&rules, aSelectorIndex, aText,
                                         aSpecificity);
}

void CSSStyleRule::SelectorTextAt(uint32_t aSelectorIndex, bool aDesugared,
                                  nsACString& aText) {
  GetSelectorDataAtIndex(aSelectorIndex, aDesugared, &aText, nullptr);
}

uint64_t CSSStyleRule::SelectorSpecificityAt(uint32_t aSelectorIndex,
                                             bool aDesugared) {
  uint64_t s = 0;
  GetSelectorDataAtIndex(aSelectorIndex, aDesugared, nullptr, &s);
  return s;
}

static void GetHosts(StyleSheet* aSheet, const Element& aElement,
                     nsTArray<Element*>& aHosts) {
  if (!aSheet) {
    return;
  }

  if (auto* owner = aSheet->GetAssociatedDocumentOrShadowRoot()) {
    if (auto* shadow = ShadowRoot::FromNode(owner->AsNode())) {
      aHosts.AppendElement(shadow->Host());
    }
  }

  for (auto* adopter : aSheet->SelfOrAncestorAdopters()) {
    auto* shadow = ShadowRoot::FromNode(adopter->AsNode());
    if (!shadow) {
      continue;
    }
    if (shadow->Host() == &aElement ||
        shadow == aElement.GetContainingShadow()) {
      aHosts.AppendElement(shadow->Host());
    }
  }
}

Element* GetHost(StyleSheet* aSheet, const Element& aElement) {
  nsTArray<Element*> hosts;
  GetHosts(aSheet, aElement, hosts);
  return hosts.SafeElementAt(0, nullptr);
}

bool CSSStyleRule::SelectorMatchesElement(uint32_t aSelectorIndex,
                                          Element& aElement,
                                          const nsAString& aPseudo,
                                          bool aRelevantLinkVisited) {
  const auto pseudo = PseudoStyleRequest::Parse(
      aPseudo, aElement.OwnerDoc()->DefaultStyleAttrURLData(),
      /* aIgnoreEnabledState = */ true);
  if (!pseudo) {
    return false;
  }

  AutoTArray<StyleScopeRuleData, 1> scopes;
  AutoTArray<const StyleLockedStyleRule*, 8> rules;
  CollectStyleRules(*this, /* aDesugared = */ true, rules, &scopes);

  AutoTArray<Element*, 4> hosts;
  GetHosts(GetStyleSheet(), aElement, hosts);
  if (hosts.IsEmpty()) {
    hosts.AppendElement(nullptr);
  }

  for (auto* host : hosts) {
    if (Servo_StyleRule_SelectorMatchesElement(
            &rules, &scopes, &aElement, aSelectorIndex, host, pseudo->mType,
            pseudo->mIdentifier, aRelevantLinkVisited)) {
      return true;
    }
  }

  return false;
}

Element* CSSStyleRule::GetScopeRootFor(uint32_t aSelectorIndex,
                                       dom::Element& aElement,
                                       const nsAString& aPseudo,
                                       bool aRelevantLinkVisited) {
  const auto pseudo = PseudoStyleRequest::Parse(
      aPseudo, aElement.OwnerDoc()->DefaultStyleAttrURLData(),
      /* aIgnoreEnabledState = */ true);
  if (!pseudo) {
    return nullptr;
  }

  auto* host = GetHost(GetStyleSheet(), aElement);
  AutoTArray<const StyleLockedStyleRule*, 8> rules;
  AutoTArray<StyleScopeRuleData, 1> scopes;
  CollectStyleRules(*this, /* aDesugared = */ true, rules, &scopes);
  return const_cast<Element*>(Servo_StyleRule_GetScopeRootFor(
      &rules, &scopes, &aElement, aSelectorIndex, host, pseudo->mType,
      pseudo->mIdentifier, aRelevantLinkVisited));
}

SelectorWarningKind ToWebIDLSelectorWarningKind(
    StyleSelectorWarningKind aKind) {
  // Whenever an entry is modified here, file a DevTools follow-up bug to make
  // use of the warning, e.g. Like it is done in
  // `css-selector-warnings-tooltip-helper.js`.
  switch (aKind) {
    case StyleSelectorWarningKind::UnconstraintedRelativeSelector:
      return SelectorWarningKind::UnconstrainedHas;
    case StyleSelectorWarningKind::SiblingCombinatorAfterScopeSelector:
      return SelectorWarningKind::SiblingCombinatorAfterScope;
  }
  MOZ_ASSERT_UNREACHABLE("Unhandled selector warning kind");
  // Return something for assert-disabled builds.
  return SelectorWarningKind::UnconstrainedHas;
}

void CSSStyleRule::GetSelectorWarnings(
    nsTArray<SelectorWarning>& aResult) const {
  nsTArray<StyleSelectorWarningData> result;
  Servo_GetSelectorWarnings(mRawRule, &result);
  for (const auto& warning : result) {
    auto& entry = *aResult.AppendElement();
    entry.mIndex = warning.index;
    entry.mKind = ToWebIDLSelectorWarningKind(warning.kind);
  }
}

already_AddRefed<NodeList> CSSStyleRule::QuerySelectorAll(nsINode& aRoot) {
  AutoTArray<const StyleLockedStyleRule*, 8> rules;
  AutoTArray<StyleScopeRuleData, 1> scopes;
  CollectStyleRules(*this, /* aDesugared = */ true, rules, &scopes);
  auto contentList = MakeRefPtr<SimpleContentList>(&aRoot);
  if (scopes.IsEmpty()) {
    StyleSelectorList* list = Servo_StyleRule_GetSelectorList(&rules);
    Servo_SelectorList_QueryAll(&aRoot, list, contentList.get(),
                                /* useInvalidation */ false);
    Servo_SelectorList_Drop(list);
  } else {
    // TODO(dshin): This division is annoying, but `querySelectorAll` path has
    // fast-path options that we can take advantage of.
    Servo_SelectorList_QueryAllWithScope(&aRoot, &rules, &scopes,
                                         contentList.get());
  }

  return contentList.forget();
}

StylePropertyMap* CSSStyleRule::StyleMap() {
  if (!mStyleMap) {
    mStyleMap = MakeRefPtr<StylePropertyMap>(this);
  }

  return mStyleMap;
}

/* virtual */
JSObject* CSSStyleRule::WrapObject(JSContext* aCx,
                                   JS::Handle<JSObject*> aGivenProto) {
  return CSSStyleRule_Binding::Wrap(aCx, this, aGivenProto);
}

}  // namespace mozilla::dom
