CSSStyleSheet.cpp 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036
  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. // vim:cindent:tabstop=2:expandtab:shiftwidth=2:
  3. /* This Source Code Form is subject to the terms of the Mozilla Public
  4. * License, v. 2.0. If a copy of the MPL was not distributed with this
  5. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6. /* representation of a CSS style sheet */
  7. #include "mozilla/CSSStyleSheet.h"
  8. #include "nsIAtom.h"
  9. #include "nsCSSRuleProcessor.h"
  10. #include "mozilla/MemoryReporting.h"
  11. #include "mozilla/dom/Element.h"
  12. #include "mozilla/dom/MediaListBinding.h"
  13. #include "mozilla/css/NameSpaceRule.h"
  14. #include "mozilla/css/GroupRule.h"
  15. #include "mozilla/css/ImportRule.h"
  16. #include "nsCSSRules.h"
  17. #include "nsIMediaList.h"
  18. #include "nsIDocument.h"
  19. #include "nsPresContext.h"
  20. #include "nsGkAtoms.h"
  21. #include "nsQueryObject.h"
  22. #include "nsString.h"
  23. #include "nsTArray.h"
  24. #include "nsIDOMCSSStyleSheet.h"
  25. #include "mozilla/dom/CSSRuleList.h"
  26. #include "nsIDOMMediaList.h"
  27. #include "nsIDOMNode.h"
  28. #include "nsError.h"
  29. #include "nsCSSParser.h"
  30. #include "mozilla/css/Loader.h"
  31. #include "nsICSSLoaderObserver.h"
  32. #include "nsNameSpaceManager.h"
  33. #include "nsXMLNameSpaceMap.h"
  34. #include "nsCOMPtr.h"
  35. #include "nsContentUtils.h"
  36. #include "nsIScriptSecurityManager.h"
  37. #include "mozAutoDocUpdate.h"
  38. #include "nsRuleNode.h"
  39. #include "nsMediaFeatures.h"
  40. #include "nsDOMClassInfoID.h"
  41. #include "mozilla/Likely.h"
  42. #include "nsComponentManagerUtils.h"
  43. #include "nsNullPrincipal.h"
  44. #include "mozilla/RuleProcessorCache.h"
  45. #include "nsIStyleSheetLinkingElement.h"
  46. #include "nsDOMWindowUtils.h"
  47. #include "nsStyleSet.h"
  48. using namespace mozilla;
  49. using namespace mozilla::dom;
  50. // -------------------------------
  51. // Style Rule List for the DOM
  52. //
  53. class CSSRuleListImpl final : public CSSRuleList
  54. {
  55. public:
  56. explicit CSSRuleListImpl(CSSStyleSheet *aStyleSheet);
  57. virtual CSSStyleSheet* GetParentObject() override;
  58. virtual nsIDOMCSSRule*
  59. IndexedGetter(uint32_t aIndex, bool& aFound) override;
  60. virtual uint32_t
  61. Length() override;
  62. void DropReference() { mStyleSheet = nullptr; }
  63. protected:
  64. virtual ~CSSRuleListImpl();
  65. CSSStyleSheet* mStyleSheet;
  66. };
  67. CSSRuleListImpl::CSSRuleListImpl(CSSStyleSheet *aStyleSheet)
  68. {
  69. // Not reference counted to avoid circular references.
  70. // The style sheet will tell us when its going away.
  71. mStyleSheet = aStyleSheet;
  72. }
  73. CSSRuleListImpl::~CSSRuleListImpl()
  74. {
  75. }
  76. CSSStyleSheet*
  77. CSSRuleListImpl::GetParentObject()
  78. {
  79. return mStyleSheet;
  80. }
  81. uint32_t
  82. CSSRuleListImpl::Length()
  83. {
  84. if (!mStyleSheet) {
  85. return 0;
  86. }
  87. return AssertedCast<uint32_t>(mStyleSheet->StyleRuleCount());
  88. }
  89. nsIDOMCSSRule*
  90. CSSRuleListImpl::IndexedGetter(uint32_t aIndex, bool& aFound)
  91. {
  92. aFound = false;
  93. if (mStyleSheet) {
  94. // ensure rules have correct parent
  95. mStyleSheet->EnsureUniqueInner();
  96. css::Rule* rule = mStyleSheet->GetStyleRuleAt(aIndex);
  97. if (rule) {
  98. aFound = true;
  99. return rule->GetDOMRule();
  100. }
  101. }
  102. // Per spec: "Return Value ... null if ... not a valid index."
  103. return nullptr;
  104. }
  105. template <class Numeric>
  106. int32_t DoCompare(Numeric a, Numeric b)
  107. {
  108. if (a == b)
  109. return 0;
  110. if (a < b)
  111. return -1;
  112. return 1;
  113. }
  114. bool
  115. nsMediaExpression::Matches(nsPresContext *aPresContext,
  116. const nsCSSValue& aActualValue) const
  117. {
  118. const nsCSSValue& actual = aActualValue;
  119. const nsCSSValue& required = mValue;
  120. // If we don't have the feature, the match fails.
  121. if (actual.GetUnit() == eCSSUnit_Null) {
  122. return false;
  123. }
  124. // If the expression had no value to match, the match succeeds,
  125. // unless the value is an integer 0 or a zero length.
  126. if (required.GetUnit() == eCSSUnit_Null) {
  127. if (actual.GetUnit() == eCSSUnit_Integer)
  128. return actual.GetIntValue() != 0;
  129. if (actual.IsLengthUnit())
  130. return actual.GetFloatValue() != 0;
  131. return true;
  132. }
  133. NS_ASSERTION(mFeature->mRangeType == nsMediaFeature::eMinMaxAllowed ||
  134. mRange == nsMediaExpression::eEqual, "yikes");
  135. int32_t cmp; // -1 (actual < required)
  136. // 0 (actual == required)
  137. // 1 (actual > required)
  138. switch (mFeature->mValueType) {
  139. case nsMediaFeature::eLength:
  140. {
  141. NS_ASSERTION(actual.IsLengthUnit(), "bad actual value");
  142. NS_ASSERTION(required.IsLengthUnit(), "bad required value");
  143. nscoord actualCoord = nsRuleNode::CalcLengthWithInitialFont(
  144. aPresContext, actual);
  145. nscoord requiredCoord = nsRuleNode::CalcLengthWithInitialFont(
  146. aPresContext, required);
  147. cmp = DoCompare(actualCoord, requiredCoord);
  148. }
  149. break;
  150. case nsMediaFeature::eInteger:
  151. case nsMediaFeature::eBoolInteger:
  152. {
  153. NS_ASSERTION(actual.GetUnit() == eCSSUnit_Integer,
  154. "bad actual value");
  155. NS_ASSERTION(required.GetUnit() == eCSSUnit_Integer,
  156. "bad required value");
  157. NS_ASSERTION(mFeature->mValueType != nsMediaFeature::eBoolInteger ||
  158. actual.GetIntValue() == 0 || actual.GetIntValue() == 1,
  159. "bad actual bool integer value");
  160. NS_ASSERTION(mFeature->mValueType != nsMediaFeature::eBoolInteger ||
  161. required.GetIntValue() == 0 || required.GetIntValue() == 1,
  162. "bad required bool integer value");
  163. cmp = DoCompare(actual.GetIntValue(), required.GetIntValue());
  164. }
  165. break;
  166. case nsMediaFeature::eFloat:
  167. {
  168. NS_ASSERTION(actual.GetUnit() == eCSSUnit_Number,
  169. "bad actual value");
  170. NS_ASSERTION(required.GetUnit() == eCSSUnit_Number,
  171. "bad required value");
  172. cmp = DoCompare(actual.GetFloatValue(), required.GetFloatValue());
  173. }
  174. break;
  175. case nsMediaFeature::eIntRatio:
  176. {
  177. NS_ASSERTION(actual.GetUnit() == eCSSUnit_Array &&
  178. actual.GetArrayValue()->Count() == 2 &&
  179. actual.GetArrayValue()->Item(0).GetUnit() ==
  180. eCSSUnit_Integer &&
  181. actual.GetArrayValue()->Item(1).GetUnit() ==
  182. eCSSUnit_Integer,
  183. "bad actual value");
  184. NS_ASSERTION(required.GetUnit() == eCSSUnit_Array &&
  185. required.GetArrayValue()->Count() == 2 &&
  186. required.GetArrayValue()->Item(0).GetUnit() ==
  187. eCSSUnit_Integer &&
  188. required.GetArrayValue()->Item(1).GetUnit() ==
  189. eCSSUnit_Integer,
  190. "bad required value");
  191. // Convert to int64_t so we can multiply without worry. Note
  192. // that while the spec requires that both halves of |required|
  193. // be positive, the numerator or denominator of |actual| might
  194. // be zero (e.g., when testing 'aspect-ratio' on a 0-width or
  195. // 0-height iframe).
  196. int64_t actualNum = actual.GetArrayValue()->Item(0).GetIntValue(),
  197. actualDen = actual.GetArrayValue()->Item(1).GetIntValue(),
  198. requiredNum = required.GetArrayValue()->Item(0).GetIntValue(),
  199. requiredDen = required.GetArrayValue()->Item(1).GetIntValue();
  200. cmp = DoCompare(actualNum * requiredDen, requiredNum * actualDen);
  201. }
  202. break;
  203. case nsMediaFeature::eResolution:
  204. {
  205. NS_ASSERTION(actual.GetUnit() == eCSSUnit_Inch ||
  206. actual.GetUnit() == eCSSUnit_Pixel ||
  207. actual.GetUnit() == eCSSUnit_Centimeter,
  208. "bad actual value");
  209. NS_ASSERTION(required.GetUnit() == eCSSUnit_Inch ||
  210. required.GetUnit() == eCSSUnit_Pixel ||
  211. required.GetUnit() == eCSSUnit_Centimeter,
  212. "bad required value");
  213. float actualDPI = actual.GetFloatValue();
  214. float overrideDPPX = aPresContext->GetOverrideDPPX();
  215. if (overrideDPPX > 0) {
  216. actualDPI = overrideDPPX * 96.0f;
  217. } else if (actual.GetUnit() == eCSSUnit_Centimeter) {
  218. actualDPI = actualDPI * 2.54f;
  219. } else if (actual.GetUnit() == eCSSUnit_Pixel) {
  220. actualDPI = actualDPI * 96.0f;
  221. }
  222. float requiredDPI = required.GetFloatValue();
  223. if (required.GetUnit() == eCSSUnit_Centimeter) {
  224. requiredDPI = requiredDPI * 2.54f;
  225. } else if (required.GetUnit() == eCSSUnit_Pixel) {
  226. requiredDPI = requiredDPI * 96.0f;
  227. }
  228. cmp = DoCompare(actualDPI, requiredDPI);
  229. }
  230. break;
  231. case nsMediaFeature::eEnumerated:
  232. {
  233. NS_ASSERTION(actual.GetUnit() == eCSSUnit_Enumerated,
  234. "bad actual value");
  235. NS_ASSERTION(required.GetUnit() == eCSSUnit_Enumerated,
  236. "bad required value");
  237. NS_ASSERTION(mFeature->mRangeType == nsMediaFeature::eMinMaxNotAllowed,
  238. "bad range"); // we asserted above about mRange
  239. // We don't really need DoCompare, but it doesn't hurt (and
  240. // maybe the compiler will condense this case with eInteger).
  241. cmp = DoCompare(actual.GetIntValue(), required.GetIntValue());
  242. }
  243. break;
  244. case nsMediaFeature::eIdent:
  245. {
  246. NS_ASSERTION(actual.GetUnit() == eCSSUnit_Ident,
  247. "bad actual value");
  248. NS_ASSERTION(required.GetUnit() == eCSSUnit_Ident,
  249. "bad required value");
  250. NS_ASSERTION(mFeature->mRangeType == nsMediaFeature::eMinMaxNotAllowed,
  251. "bad range");
  252. cmp = !(actual == required); // string comparison
  253. }
  254. break;
  255. }
  256. switch (mRange) {
  257. case nsMediaExpression::eMin:
  258. return cmp != -1;
  259. case nsMediaExpression::eMax:
  260. return cmp != 1;
  261. case nsMediaExpression::eEqual:
  262. return cmp == 0;
  263. }
  264. NS_NOTREACHED("unexpected mRange");
  265. return false;
  266. }
  267. void
  268. nsMediaQueryResultCacheKey::AddExpression(const nsMediaExpression* aExpression,
  269. bool aExpressionMatches)
  270. {
  271. const nsMediaFeature *feature = aExpression->mFeature;
  272. FeatureEntry *entry = nullptr;
  273. for (uint32_t i = 0; i < mFeatureCache.Length(); ++i) {
  274. if (mFeatureCache[i].mFeature == feature) {
  275. entry = &mFeatureCache[i];
  276. break;
  277. }
  278. }
  279. if (!entry) {
  280. entry = mFeatureCache.AppendElement();
  281. if (!entry) {
  282. return; /* out of memory */
  283. }
  284. entry->mFeature = feature;
  285. }
  286. ExpressionEntry eentry = { *aExpression, aExpressionMatches };
  287. entry->mExpressions.AppendElement(eentry);
  288. }
  289. bool
  290. nsMediaQueryResultCacheKey::Matches(nsPresContext* aPresContext) const
  291. {
  292. if (aPresContext->Medium() != mMedium) {
  293. return false;
  294. }
  295. for (uint32_t i = 0; i < mFeatureCache.Length(); ++i) {
  296. const FeatureEntry *entry = &mFeatureCache[i];
  297. nsCSSValue actual;
  298. nsresult rv =
  299. (entry->mFeature->mGetter)(aPresContext, entry->mFeature, actual);
  300. NS_ENSURE_SUCCESS(rv, false); // any better ideas?
  301. for (uint32_t j = 0; j < entry->mExpressions.Length(); ++j) {
  302. const ExpressionEntry &eentry = entry->mExpressions[j];
  303. if (eentry.mExpression.Matches(aPresContext, actual) !=
  304. eentry.mExpressionMatches) {
  305. return false;
  306. }
  307. }
  308. }
  309. return true;
  310. }
  311. bool
  312. nsDocumentRuleResultCacheKey::AddMatchingRule(css::DocumentRule* aRule)
  313. {
  314. MOZ_ASSERT(!mFinalized);
  315. return mMatchingRules.AppendElement(aRule);
  316. }
  317. void
  318. nsDocumentRuleResultCacheKey::Finalize()
  319. {
  320. mMatchingRules.Sort();
  321. #ifdef DEBUG
  322. mFinalized = true;
  323. #endif
  324. }
  325. #ifdef DEBUG
  326. static bool
  327. ArrayIsSorted(const nsTArray<css::DocumentRule*>& aRules)
  328. {
  329. for (size_t i = 1; i < aRules.Length(); i++) {
  330. if (aRules[i - 1] > aRules[i]) {
  331. return false;
  332. }
  333. }
  334. return true;
  335. }
  336. #endif
  337. bool
  338. nsDocumentRuleResultCacheKey::Matches(
  339. nsPresContext* aPresContext,
  340. const nsTArray<css::DocumentRule*>& aRules) const
  341. {
  342. MOZ_ASSERT(mFinalized);
  343. MOZ_ASSERT(ArrayIsSorted(mMatchingRules));
  344. MOZ_ASSERT(ArrayIsSorted(aRules));
  345. #ifdef DEBUG
  346. for (css::DocumentRule* rule : mMatchingRules) {
  347. MOZ_ASSERT(aRules.BinaryIndexOf(rule) != aRules.NoIndex,
  348. "aRules must contain all rules in mMatchingRules");
  349. }
  350. #endif
  351. // First check that aPresContext matches all the rules listed in
  352. // mMatchingRules.
  353. for (css::DocumentRule* rule : mMatchingRules) {
  354. if (!rule->UseForPresentation(aPresContext)) {
  355. return false;
  356. }
  357. }
  358. // Then check that all the rules in aRules that aren't also in
  359. // mMatchingRules do not match.
  360. // pointer to matching rules
  361. auto pm = mMatchingRules.begin();
  362. auto pm_end = mMatchingRules.end();
  363. // pointer to all rules
  364. auto pr = aRules.begin();
  365. auto pr_end = aRules.end();
  366. // mMatchingRules and aRules are both sorted by their pointer values,
  367. // so we can iterate over the two lists simultaneously.
  368. while (pr < pr_end) {
  369. while (pm < pm_end && *pm < *pr) {
  370. ++pm;
  371. }
  372. if (pm >= pm_end || *pm != *pr) {
  373. if ((*pr)->UseForPresentation(aPresContext)) {
  374. return false;
  375. }
  376. }
  377. ++pr;
  378. }
  379. return true;
  380. }
  381. #ifdef DEBUG
  382. void
  383. nsDocumentRuleResultCacheKey::List(FILE* aOut, int32_t aIndent) const
  384. {
  385. for (css::DocumentRule* rule : mMatchingRules) {
  386. nsCString str;
  387. for (int32_t i = 0; i < aIndent; i++) {
  388. str.AppendLiteral(" ");
  389. }
  390. str.AppendLiteral("{ ");
  391. nsString condition;
  392. rule->GetConditionText(condition);
  393. AppendUTF16toUTF8(condition, str);
  394. str.AppendLiteral(" }\n");
  395. fprintf_stderr(aOut, "%s", str.get());
  396. }
  397. }
  398. #endif
  399. size_t
  400. nsDocumentRuleResultCacheKey::SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
  401. {
  402. size_t n = 0;
  403. n += mMatchingRules.ShallowSizeOfExcludingThis(aMallocSizeOf);
  404. return n;
  405. }
  406. void
  407. nsMediaQuery::AppendToString(nsAString& aString) const
  408. {
  409. if (mHadUnknownExpression) {
  410. aString.AppendLiteral("not all");
  411. return;
  412. }
  413. NS_ASSERTION(!mNegated || !mHasOnly, "can't have not and only");
  414. NS_ASSERTION(!mTypeOmitted || (!mNegated && !mHasOnly),
  415. "can't have not or only when type is omitted");
  416. if (!mTypeOmitted) {
  417. if (mNegated) {
  418. aString.AppendLiteral("not ");
  419. } else if (mHasOnly) {
  420. aString.AppendLiteral("only ");
  421. }
  422. aString.Append(nsDependentAtomString(mMediaType));
  423. }
  424. for (uint32_t i = 0, i_end = mExpressions.Length(); i < i_end; ++i) {
  425. if (i > 0 || !mTypeOmitted)
  426. aString.AppendLiteral(" and ");
  427. aString.Append('(');
  428. const nsMediaExpression &expr = mExpressions[i];
  429. const nsMediaFeature *feature = expr.mFeature;
  430. if (feature->mReqFlags & nsMediaFeature::eHasWebkitPrefix) {
  431. aString.AppendLiteral("-webkit-");
  432. }
  433. if (expr.mRange == nsMediaExpression::eMin) {
  434. aString.AppendLiteral("min-");
  435. } else if (expr.mRange == nsMediaExpression::eMax) {
  436. aString.AppendLiteral("max-");
  437. }
  438. aString.Append(nsDependentAtomString(*feature->mName));
  439. if (expr.mValue.GetUnit() != eCSSUnit_Null) {
  440. aString.AppendLiteral(": ");
  441. switch (feature->mValueType) {
  442. case nsMediaFeature::eLength:
  443. NS_ASSERTION(expr.mValue.IsLengthUnit(), "bad unit");
  444. // Use 'width' as a property that takes length values
  445. // written in the normal way.
  446. expr.mValue.AppendToString(eCSSProperty_width, aString,
  447. nsCSSValue::eNormalized);
  448. break;
  449. case nsMediaFeature::eInteger:
  450. case nsMediaFeature::eBoolInteger:
  451. NS_ASSERTION(expr.mValue.GetUnit() == eCSSUnit_Integer,
  452. "bad unit");
  453. // Use 'z-index' as a property that takes integer values
  454. // written without anything extra.
  455. expr.mValue.AppendToString(eCSSProperty_z_index, aString,
  456. nsCSSValue::eNormalized);
  457. break;
  458. case nsMediaFeature::eFloat:
  459. {
  460. NS_ASSERTION(expr.mValue.GetUnit() == eCSSUnit_Number,
  461. "bad unit");
  462. // Use 'line-height' as a property that takes float values
  463. // written in the normal way.
  464. expr.mValue.AppendToString(eCSSProperty_line_height, aString,
  465. nsCSSValue::eNormalized);
  466. }
  467. break;
  468. case nsMediaFeature::eIntRatio:
  469. {
  470. NS_ASSERTION(expr.mValue.GetUnit() == eCSSUnit_Array,
  471. "bad unit");
  472. nsCSSValue::Array *array = expr.mValue.GetArrayValue();
  473. NS_ASSERTION(array->Count() == 2, "unexpected length");
  474. NS_ASSERTION(array->Item(0).GetUnit() == eCSSUnit_Integer,
  475. "bad unit");
  476. NS_ASSERTION(array->Item(1).GetUnit() == eCSSUnit_Integer,
  477. "bad unit");
  478. array->Item(0).AppendToString(eCSSProperty_z_index, aString,
  479. nsCSSValue::eNormalized);
  480. aString.Append('/');
  481. array->Item(1).AppendToString(eCSSProperty_z_index, aString,
  482. nsCSSValue::eNormalized);
  483. }
  484. break;
  485. case nsMediaFeature::eResolution:
  486. {
  487. aString.AppendFloat(expr.mValue.GetFloatValue());
  488. if (expr.mValue.GetUnit() == eCSSUnit_Inch) {
  489. aString.AppendLiteral("dpi");
  490. } else if (expr.mValue.GetUnit() == eCSSUnit_Pixel) {
  491. aString.AppendLiteral("dppx");
  492. } else {
  493. NS_ASSERTION(expr.mValue.GetUnit() == eCSSUnit_Centimeter,
  494. "bad unit");
  495. aString.AppendLiteral("dpcm");
  496. }
  497. }
  498. break;
  499. case nsMediaFeature::eEnumerated:
  500. NS_ASSERTION(expr.mValue.GetUnit() == eCSSUnit_Enumerated,
  501. "bad unit");
  502. AppendASCIItoUTF16(
  503. nsCSSProps::ValueToKeyword(expr.mValue.GetIntValue(),
  504. feature->mData.mKeywordTable),
  505. aString);
  506. break;
  507. case nsMediaFeature::eIdent:
  508. NS_ASSERTION(expr.mValue.GetUnit() == eCSSUnit_Ident,
  509. "bad unit");
  510. aString.Append(expr.mValue.GetStringBufferValue());
  511. break;
  512. }
  513. }
  514. aString.Append(')');
  515. }
  516. }
  517. nsMediaQuery*
  518. nsMediaQuery::Clone() const
  519. {
  520. return new nsMediaQuery(*this);
  521. }
  522. bool
  523. nsMediaQuery::Matches(nsPresContext* aPresContext,
  524. nsMediaQueryResultCacheKey* aKey) const
  525. {
  526. if (mHadUnknownExpression)
  527. return false;
  528. bool match =
  529. mMediaType == aPresContext->Medium() || mMediaType == nsGkAtoms::all;
  530. for (uint32_t i = 0, i_end = mExpressions.Length(); match && i < i_end; ++i) {
  531. const nsMediaExpression &expr = mExpressions[i];
  532. nsCSSValue actual;
  533. nsresult rv =
  534. (expr.mFeature->mGetter)(aPresContext, expr.mFeature, actual);
  535. NS_ENSURE_SUCCESS(rv, false); // any better ideas?
  536. match = expr.Matches(aPresContext, actual);
  537. if (aKey) {
  538. aKey->AddExpression(&expr, match);
  539. }
  540. }
  541. return match == !mNegated;
  542. }
  543. NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsMediaList)
  544. NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
  545. NS_INTERFACE_MAP_ENTRY(nsIDOMMediaList)
  546. NS_INTERFACE_MAP_ENTRY(nsISupports)
  547. NS_INTERFACE_MAP_END
  548. NS_IMPL_CYCLE_COLLECTING_ADDREF(nsMediaList)
  549. NS_IMPL_CYCLE_COLLECTING_RELEASE(nsMediaList)
  550. NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_0(nsMediaList)
  551. nsMediaList::nsMediaList()
  552. : mStyleSheet(nullptr)
  553. {
  554. }
  555. nsMediaList::~nsMediaList()
  556. {
  557. }
  558. /* virtual */ JSObject*
  559. nsMediaList::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
  560. {
  561. return MediaListBinding::Wrap(aCx, this, aGivenProto);
  562. }
  563. void
  564. nsMediaList::GetText(nsAString& aMediaText)
  565. {
  566. aMediaText.Truncate();
  567. for (int32_t i = 0, i_end = mArray.Length(); i < i_end; ++i) {
  568. nsMediaQuery* query = mArray[i];
  569. query->AppendToString(aMediaText);
  570. if (i + 1 < i_end) {
  571. aMediaText.AppendLiteral(", ");
  572. }
  573. }
  574. }
  575. // XXXbz this is so ill-defined in the spec, it's not clear quite what
  576. // it should be doing....
  577. void
  578. nsMediaList::SetText(const nsAString& aMediaText)
  579. {
  580. nsCSSParser parser;
  581. bool htmlMode = mStyleSheet && mStyleSheet->GetOwnerNode();
  582. parser.ParseMediaList(aMediaText, nullptr, 0, this, htmlMode);
  583. }
  584. bool
  585. nsMediaList::Matches(nsPresContext* aPresContext,
  586. nsMediaQueryResultCacheKey* aKey)
  587. {
  588. for (int32_t i = 0, i_end = mArray.Length(); i < i_end; ++i) {
  589. if (mArray[i]->Matches(aPresContext, aKey)) {
  590. return true;
  591. }
  592. }
  593. return mArray.IsEmpty();
  594. }
  595. void
  596. nsMediaList::SetStyleSheet(CSSStyleSheet* aSheet)
  597. {
  598. NS_ASSERTION(aSheet == mStyleSheet || !aSheet || !mStyleSheet,
  599. "multiple style sheets competing for one media list");
  600. mStyleSheet = aSheet;
  601. }
  602. already_AddRefed<nsMediaList>
  603. nsMediaList::Clone()
  604. {
  605. RefPtr<nsMediaList> result = new nsMediaList();
  606. result->mArray.AppendElements(mArray.Length());
  607. for (uint32_t i = 0, i_end = mArray.Length(); i < i_end; ++i) {
  608. result->mArray[i] = mArray[i]->Clone();
  609. MOZ_ASSERT(result->mArray[i]);
  610. }
  611. return result.forget();
  612. }
  613. NS_IMETHODIMP
  614. nsMediaList::GetMediaText(nsAString& aMediaText)
  615. {
  616. GetText(aMediaText);
  617. return NS_OK;
  618. }
  619. // "sheet" should be a CSSStyleSheet and "doc" should be an
  620. // nsCOMPtr<nsIDocument>
  621. #define BEGIN_MEDIA_CHANGE(sheet, doc) \
  622. if (sheet) { \
  623. doc = sheet->GetAssociatedDocument(); \
  624. } \
  625. mozAutoDocUpdate updateBatch(doc, UPDATE_STYLE, true); \
  626. if (sheet) { \
  627. sheet->WillDirty(); \
  628. }
  629. #define END_MEDIA_CHANGE(sheet, doc) \
  630. if (sheet) { \
  631. sheet->DidDirty(); \
  632. } \
  633. /* XXXldb Pass something meaningful? */ \
  634. if (doc) { \
  635. doc->StyleRuleChanged(sheet, nullptr); \
  636. }
  637. NS_IMETHODIMP
  638. nsMediaList::SetMediaText(const nsAString& aMediaText)
  639. {
  640. nsCOMPtr<nsIDocument> doc;
  641. BEGIN_MEDIA_CHANGE(mStyleSheet, doc)
  642. SetText(aMediaText);
  643. END_MEDIA_CHANGE(mStyleSheet, doc)
  644. return NS_OK;
  645. }
  646. NS_IMETHODIMP
  647. nsMediaList::GetLength(uint32_t* aLength)
  648. {
  649. NS_ENSURE_ARG_POINTER(aLength);
  650. *aLength = Length();
  651. return NS_OK;
  652. }
  653. NS_IMETHODIMP
  654. nsMediaList::Item(uint32_t aIndex, nsAString& aReturn)
  655. {
  656. bool dummy;
  657. IndexedGetter(aIndex, dummy, aReturn);
  658. return NS_OK;
  659. }
  660. void
  661. nsMediaList::IndexedGetter(uint32_t aIndex, bool& aFound, nsAString& aReturn)
  662. {
  663. if (aIndex < Length()) {
  664. aFound = true;
  665. aReturn.Truncate();
  666. mArray[aIndex]->AppendToString(aReturn);
  667. } else {
  668. aFound = false;
  669. SetDOMStringToNull(aReturn);
  670. }
  671. }
  672. NS_IMETHODIMP
  673. nsMediaList::DeleteMedium(const nsAString& aOldMedium)
  674. {
  675. nsresult rv = NS_OK;
  676. nsCOMPtr<nsIDocument> doc;
  677. BEGIN_MEDIA_CHANGE(mStyleSheet, doc)
  678. rv = Delete(aOldMedium);
  679. if (NS_FAILED(rv))
  680. return rv;
  681. END_MEDIA_CHANGE(mStyleSheet, doc)
  682. return rv;
  683. }
  684. NS_IMETHODIMP
  685. nsMediaList::AppendMedium(const nsAString& aNewMedium)
  686. {
  687. nsresult rv = NS_OK;
  688. nsCOMPtr<nsIDocument> doc;
  689. BEGIN_MEDIA_CHANGE(mStyleSheet, doc)
  690. rv = Append(aNewMedium);
  691. if (NS_FAILED(rv))
  692. return rv;
  693. END_MEDIA_CHANGE(mStyleSheet, doc)
  694. return rv;
  695. }
  696. nsresult
  697. nsMediaList::Delete(const nsAString& aOldMedium)
  698. {
  699. if (aOldMedium.IsEmpty())
  700. return NS_ERROR_DOM_NOT_FOUND_ERR;
  701. for (int32_t i = 0, i_end = mArray.Length(); i < i_end; ++i) {
  702. nsMediaQuery* query = mArray[i];
  703. nsAutoString buf;
  704. query->AppendToString(buf);
  705. if (buf == aOldMedium) {
  706. mArray.RemoveElementAt(i);
  707. return NS_OK;
  708. }
  709. }
  710. return NS_ERROR_DOM_NOT_FOUND_ERR;
  711. }
  712. nsresult
  713. nsMediaList::Append(const nsAString& aNewMedium)
  714. {
  715. if (aNewMedium.IsEmpty())
  716. return NS_ERROR_DOM_NOT_FOUND_ERR;
  717. Delete(aNewMedium);
  718. nsresult rv = NS_OK;
  719. nsTArray<nsAutoPtr<nsMediaQuery> > buf;
  720. mArray.SwapElements(buf);
  721. SetText(aNewMedium);
  722. if (mArray.Length() == 1) {
  723. nsMediaQuery *query = mArray[0].forget();
  724. if (!buf.AppendElement(query)) {
  725. delete query;
  726. rv = NS_ERROR_OUT_OF_MEMORY;
  727. }
  728. }
  729. mArray.SwapElements(buf);
  730. return rv;
  731. }
  732. namespace mozilla {
  733. // -------------------------------
  734. // CSS Style Sheet Inner Data Container
  735. //
  736. CSSStyleSheetInner::CSSStyleSheetInner(CSSStyleSheet* aPrimarySheet,
  737. CORSMode aCORSMode,
  738. ReferrerPolicy aReferrerPolicy,
  739. const SRIMetadata& aIntegrity)
  740. : StyleSheetInfo(aCORSMode, aReferrerPolicy, aIntegrity)
  741. {
  742. MOZ_COUNT_CTOR(CSSStyleSheetInner);
  743. mSheets.AppendElement(aPrimarySheet);
  744. }
  745. static bool SetStyleSheetReference(css::Rule* aRule, void* aSheet)
  746. {
  747. if (aRule) {
  748. aRule->SetStyleSheet(static_cast<CSSStyleSheet*>(aSheet));
  749. }
  750. return true;
  751. }
  752. struct ChildSheetListBuilder {
  753. RefPtr<CSSStyleSheet>* sheetSlot;
  754. CSSStyleSheet* parent;
  755. void SetParentLinks(CSSStyleSheet* aSheet) {
  756. aSheet->mParent = parent;
  757. aSheet->SetAssociatedDocument(parent->mDocument,
  758. parent->mDocumentAssociationMode);
  759. }
  760. static void ReparentChildList(CSSStyleSheet* aPrimarySheet,
  761. CSSStyleSheet* aFirstChild)
  762. {
  763. for (CSSStyleSheet *child = aFirstChild; child; child = child->mNext) {
  764. child->mParent = aPrimarySheet;
  765. child->SetAssociatedDocument(aPrimarySheet->mDocument,
  766. aPrimarySheet->mDocumentAssociationMode);
  767. }
  768. }
  769. };
  770. bool
  771. CSSStyleSheet::RebuildChildList(css::Rule* aRule, void* aBuilder)
  772. {
  773. int32_t type = aRule->GetType();
  774. if (type < css::Rule::IMPORT_RULE) {
  775. // Keep going till we get to the import rules.
  776. return true;
  777. }
  778. if (type != css::Rule::IMPORT_RULE) {
  779. // We're past all the import rules; stop the enumeration.
  780. return false;
  781. }
  782. ChildSheetListBuilder* builder =
  783. static_cast<ChildSheetListBuilder*>(aBuilder);
  784. // XXXbz We really need to decomtaminate all this stuff. Is there a reason
  785. // that I can't just QI to ImportRule and get a CSSStyleSheet
  786. // directly from it?
  787. nsCOMPtr<nsIDOMCSSImportRule> importRule(do_QueryInterface(aRule));
  788. NS_ASSERTION(importRule, "GetType lied");
  789. nsCOMPtr<nsIDOMCSSStyleSheet> childSheet;
  790. importRule->GetStyleSheet(getter_AddRefs(childSheet));
  791. // Have to do this QI to be safe, since XPConnect can fake
  792. // nsIDOMCSSStyleSheets
  793. RefPtr<CSSStyleSheet> cssSheet = do_QueryObject(childSheet);
  794. if (!cssSheet) {
  795. return true;
  796. }
  797. (*builder->sheetSlot) = cssSheet;
  798. builder->SetParentLinks(*builder->sheetSlot);
  799. builder->sheetSlot = &(*builder->sheetSlot)->mNext;
  800. return true;
  801. }
  802. size_t
  803. CSSStyleSheet::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const
  804. {
  805. size_t n = 0;
  806. const CSSStyleSheet* s = this;
  807. while (s) {
  808. n += aMallocSizeOf(s);
  809. // Each inner can be shared by multiple sheets. So we only count the inner
  810. // if this sheet is the last one in the list of those sharing it. As a
  811. // result, the last such sheet takes all the blame for the memory
  812. // consumption of the inner, which isn't ideal but it's better than
  813. // double-counting the inner. We use last instead of first since the first
  814. // sheet may be held in the nsXULPrototypeCache and not used in a window at
  815. // all.
  816. if (s->mInner->mSheets.LastElement() == s) {
  817. n += s->mInner->SizeOfIncludingThis(aMallocSizeOf);
  818. }
  819. // Measurement of the following members may be added later if DMD finds it
  820. // is worthwhile:
  821. // - s->mTitle
  822. // - s->mMedia
  823. // - s->mRuleCollection
  824. // - s->mRuleProcessors
  825. //
  826. // The following members are not measured:
  827. // - s->mOwnerRule, because it's non-owning
  828. s = s->mNext;
  829. }
  830. return n;
  831. }
  832. CSSStyleSheetInner::CSSStyleSheetInner(CSSStyleSheetInner& aCopy,
  833. CSSStyleSheet* aPrimarySheet)
  834. : StyleSheetInfo(aCopy)
  835. {
  836. MOZ_COUNT_CTOR(CSSStyleSheetInner);
  837. AddSheet(aPrimarySheet);
  838. aCopy.mOrderedRules.EnumerateForwards(css::GroupRule::CloneRuleInto, &mOrderedRules);
  839. mOrderedRules.EnumerateForwards(SetStyleSheetReference, aPrimarySheet);
  840. ChildSheetListBuilder builder = { &mFirstChild, aPrimarySheet };
  841. mOrderedRules.EnumerateForwards(CSSStyleSheet::RebuildChildList, &builder);
  842. RebuildNameSpaces();
  843. }
  844. CSSStyleSheetInner::~CSSStyleSheetInner()
  845. {
  846. MOZ_COUNT_DTOR(CSSStyleSheetInner);
  847. mOrderedRules.EnumerateForwards(SetStyleSheetReference, nullptr);
  848. }
  849. CSSStyleSheetInner*
  850. CSSStyleSheetInner::CloneFor(CSSStyleSheet* aPrimarySheet)
  851. {
  852. return new CSSStyleSheetInner(*this, aPrimarySheet);
  853. }
  854. void
  855. CSSStyleSheetInner::AddSheet(CSSStyleSheet* aSheet)
  856. {
  857. mSheets.AppendElement(aSheet);
  858. }
  859. void
  860. CSSStyleSheetInner::RemoveSheet(CSSStyleSheet* aSheet)
  861. {
  862. if (1 == mSheets.Length()) {
  863. NS_ASSERTION(aSheet == mSheets.ElementAt(0), "bad parent");
  864. delete this;
  865. return;
  866. }
  867. if (aSheet == mSheets.ElementAt(0)) {
  868. mSheets.RemoveElementAt(0);
  869. NS_ASSERTION(mSheets.Length(), "no parents");
  870. mOrderedRules.EnumerateForwards(SetStyleSheetReference,
  871. mSheets.ElementAt(0));
  872. ChildSheetListBuilder::ReparentChildList(mSheets[0], mFirstChild);
  873. }
  874. else {
  875. mSheets.RemoveElement(aSheet);
  876. }
  877. }
  878. static void
  879. AddNamespaceRuleToMap(css::Rule* aRule, nsXMLNameSpaceMap* aMap)
  880. {
  881. NS_ASSERTION(aRule->GetType() == css::Rule::NAMESPACE_RULE, "Bogus rule type");
  882. RefPtr<css::NameSpaceRule> nameSpaceRule = do_QueryObject(aRule);
  883. nsAutoString urlSpec;
  884. nameSpaceRule->GetURLSpec(urlSpec);
  885. aMap->AddPrefix(nameSpaceRule->GetPrefix(), urlSpec);
  886. }
  887. static bool
  888. CreateNameSpace(css::Rule* aRule, void* aNameSpacePtr)
  889. {
  890. int32_t type = aRule->GetType();
  891. if (css::Rule::NAMESPACE_RULE == type) {
  892. AddNamespaceRuleToMap(aRule,
  893. static_cast<nsXMLNameSpaceMap*>(aNameSpacePtr));
  894. return true;
  895. }
  896. // stop if not namespace, import or charset because namespace can't follow
  897. // anything else
  898. return (css::Rule::CHARSET_RULE == type || css::Rule::IMPORT_RULE == type);
  899. }
  900. void
  901. CSSStyleSheetInner::RebuildNameSpaces()
  902. {
  903. // Just nuke our existing namespace map, if any
  904. if (NS_SUCCEEDED(CreateNamespaceMap())) {
  905. mOrderedRules.EnumerateForwards(CreateNameSpace, mNameSpaceMap);
  906. }
  907. }
  908. nsresult
  909. CSSStyleSheetInner::CreateNamespaceMap()
  910. {
  911. mNameSpaceMap = nsXMLNameSpaceMap::Create(false);
  912. NS_ENSURE_TRUE(mNameSpaceMap, NS_ERROR_OUT_OF_MEMORY);
  913. // Override the default namespace map behavior for the null prefix to
  914. // return the wildcard namespace instead of the null namespace.
  915. mNameSpaceMap->AddPrefix(nullptr, kNameSpaceID_Unknown);
  916. return NS_OK;
  917. }
  918. size_t
  919. CSSStyleSheetInner::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const
  920. {
  921. size_t n = aMallocSizeOf(this);
  922. n += mOrderedRules.ShallowSizeOfExcludingThis(aMallocSizeOf);
  923. for (size_t i = 0; i < mOrderedRules.Length(); i++) {
  924. n += mOrderedRules[i]->SizeOfIncludingThis(aMallocSizeOf);
  925. }
  926. n += mFirstChild ? mFirstChild->SizeOfIncludingThis(aMallocSizeOf) : 0;
  927. // Measurement of the following members may be added later if DMD finds it is
  928. // worthwhile:
  929. // - mSheetURI
  930. // - mOriginalSheetURI
  931. // - mBaseURI
  932. // - mPrincipal
  933. // - mNameSpaceMap
  934. //
  935. // The following members are not measured:
  936. // - mSheets, because it's non-owning
  937. return n;
  938. }
  939. // -------------------------------
  940. // CSS Style Sheet
  941. //
  942. CSSStyleSheet::CSSStyleSheet(css::SheetParsingMode aParsingMode,
  943. CORSMode aCORSMode, ReferrerPolicy aReferrerPolicy)
  944. : StyleSheet(StyleBackendType::Gecko, aParsingMode),
  945. mParent(nullptr),
  946. mOwnerRule(nullptr),
  947. mDirty(false),
  948. mInRuleProcessorCache(false),
  949. mScopeElement(nullptr),
  950. mRuleProcessors(nullptr)
  951. {
  952. mInner = new CSSStyleSheetInner(this, aCORSMode, aReferrerPolicy,
  953. SRIMetadata());
  954. }
  955. CSSStyleSheet::CSSStyleSheet(css::SheetParsingMode aParsingMode,
  956. CORSMode aCORSMode,
  957. ReferrerPolicy aReferrerPolicy,
  958. const SRIMetadata& aIntegrity)
  959. : StyleSheet(StyleBackendType::Gecko, aParsingMode),
  960. mParent(nullptr),
  961. mOwnerRule(nullptr),
  962. mDirty(false),
  963. mInRuleProcessorCache(false),
  964. mScopeElement(nullptr),
  965. mRuleProcessors(nullptr)
  966. {
  967. mInner = new CSSStyleSheetInner(this, aCORSMode, aReferrerPolicy,
  968. aIntegrity);
  969. }
  970. CSSStyleSheet::CSSStyleSheet(const CSSStyleSheet& aCopy,
  971. CSSStyleSheet* aParentToUse,
  972. css::ImportRule* aOwnerRuleToUse,
  973. nsIDocument* aDocumentToUse,
  974. nsINode* aOwningNodeToUse)
  975. : StyleSheet(aCopy, aDocumentToUse, aOwningNodeToUse),
  976. mParent(aParentToUse),
  977. mOwnerRule(aOwnerRuleToUse),
  978. mDirty(aCopy.mDirty),
  979. mInRuleProcessorCache(false),
  980. mScopeElement(nullptr),
  981. mInner(aCopy.mInner),
  982. mRuleProcessors(nullptr)
  983. {
  984. mInner->AddSheet(this);
  985. if (mDirty) { // CSSOM's been there, force full copy now
  986. NS_ASSERTION(mInner->mComplete, "Why have rules been accessed on an incomplete sheet?");
  987. // FIXME: handle failure?
  988. EnsureUniqueInner();
  989. }
  990. if (aCopy.mMedia) {
  991. // XXX This is wrong; we should be keeping @import rules and
  992. // sheets in sync!
  993. mMedia = aCopy.mMedia->Clone();
  994. }
  995. }
  996. CSSStyleSheet::~CSSStyleSheet()
  997. {
  998. for (CSSStyleSheet* child = mInner->mFirstChild;
  999. child;
  1000. child = child->mNext) {
  1001. // XXXbz this is a little bogus; see the XXX comment where we
  1002. // declare mFirstChild.
  1003. if (child->mParent == this) {
  1004. child->mParent = nullptr;
  1005. child->mDocument = nullptr;
  1006. }
  1007. }
  1008. DropRuleCollection();
  1009. DropMedia();
  1010. mInner->RemoveSheet(this);
  1011. // XXX The document reference is not reference counted and should
  1012. // not be released. The document will let us know when it is going
  1013. // away.
  1014. if (mRuleProcessors) {
  1015. NS_ASSERTION(mRuleProcessors->Length() == 0, "destructing sheet with rule processor reference");
  1016. delete mRuleProcessors; // weak refs, should be empty here anyway
  1017. }
  1018. if (mInRuleProcessorCache) {
  1019. RuleProcessorCache::RemoveSheet(this);
  1020. }
  1021. }
  1022. void
  1023. CSSStyleSheet::DropRuleCollection()
  1024. {
  1025. if (mRuleCollection) {
  1026. mRuleCollection->DropReference();
  1027. mRuleCollection = nullptr;
  1028. }
  1029. }
  1030. void
  1031. CSSStyleSheet::DropMedia()
  1032. {
  1033. if (mMedia) {
  1034. mMedia->SetStyleSheet(nullptr);
  1035. mMedia = nullptr;
  1036. }
  1037. }
  1038. void
  1039. CSSStyleSheet::UnlinkInner()
  1040. {
  1041. // We can only have a cycle through our inner if we have a unique inner,
  1042. // because otherwise there are no JS wrappers for anything in the inner.
  1043. if (mInner->mSheets.Length() != 1) {
  1044. return;
  1045. }
  1046. mInner->mOrderedRules.EnumerateForwards(SetStyleSheetReference, nullptr);
  1047. mInner->mOrderedRules.Clear();
  1048. // Have to be a bit careful with child sheets, because we want to
  1049. // drop their mNext pointers and null out their mParent and
  1050. // mDocument, but don't want to work with deleted objects. And we
  1051. // don't want to do any addrefing in the process, just to make sure
  1052. // we don't confuse the cycle collector (though on the face of it,
  1053. // addref/release pairs during unlink should probably be ok).
  1054. RefPtr<CSSStyleSheet> child;
  1055. child.swap(mInner->mFirstChild);
  1056. while (child) {
  1057. MOZ_ASSERT(child->mParent == this, "We have a unique inner!");
  1058. child->mParent = nullptr;
  1059. child->mDocument = nullptr;
  1060. RefPtr<CSSStyleSheet> next;
  1061. // Null out child->mNext, but don't let it die yet
  1062. next.swap(child->mNext);
  1063. // Switch to looking at the old value of child->mNext next iteration
  1064. child.swap(next);
  1065. // "next" is now our previous value of child; it'll get released
  1066. // as we loop around.
  1067. }
  1068. }
  1069. void
  1070. CSSStyleSheet::TraverseInner(nsCycleCollectionTraversalCallback &cb)
  1071. {
  1072. // We can only have a cycle through our inner if we have a unique inner,
  1073. // because otherwise there are no JS wrappers for anything in the inner.
  1074. if (mInner->mSheets.Length() != 1) {
  1075. return;
  1076. }
  1077. RefPtr<CSSStyleSheet>* childSheetSlot = &mInner->mFirstChild;
  1078. while (*childSheetSlot) {
  1079. NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "child sheet");
  1080. cb.NoteXPCOMChild(NS_ISUPPORTS_CAST(nsIDOMCSSStyleSheet*, childSheetSlot->get()));
  1081. childSheetSlot = &(*childSheetSlot)->mNext;
  1082. }
  1083. const nsCOMArray<css::Rule>& rules = mInner->mOrderedRules;
  1084. for (int32_t i = 0, count = rules.Count(); i < count; ++i) {
  1085. NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mOrderedRules[i]");
  1086. cb.NoteXPCOMChild(rules[i]->GetExistingDOMRule());
  1087. }
  1088. }
  1089. // QueryInterface implementation for CSSStyleSheet
  1090. NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(CSSStyleSheet)
  1091. NS_INTERFACE_MAP_ENTRY(nsICSSLoaderObserver)
  1092. NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, StyleSheet)
  1093. if (aIID.Equals(NS_GET_IID(CSSStyleSheet)))
  1094. foundInterface = reinterpret_cast<nsISupports*>(this);
  1095. else
  1096. NS_INTERFACE_MAP_END_INHERITING(StyleSheet)
  1097. NS_IMPL_ADDREF_INHERITED(CSSStyleSheet, StyleSheet)
  1098. NS_IMPL_RELEASE_INHERITED(CSSStyleSheet, StyleSheet)
  1099. NS_IMPL_CYCLE_COLLECTION_CLASS(CSSStyleSheet)
  1100. NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(CSSStyleSheet)
  1101. tmp->DropMedia();
  1102. // We do not unlink mNext; our parent will handle that. If we
  1103. // unlinked it here, our parent would not be able to walk its list
  1104. // of child sheets and null out the back-references to it, if we got
  1105. // unlinked before it does.
  1106. tmp->DropRuleCollection();
  1107. tmp->UnlinkInner();
  1108. tmp->mScopeElement = nullptr;
  1109. NS_IMPL_CYCLE_COLLECTION_UNLINK_END_INHERITED(StyleSheet)
  1110. NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(CSSStyleSheet, StyleSheet)
  1111. NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mMedia)
  1112. // We do not traverse mNext; our parent will handle that. See
  1113. // comments in Unlink for why.
  1114. NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRuleCollection)
  1115. NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mScopeElement)
  1116. tmp->TraverseInner(cb);
  1117. NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
  1118. nsresult
  1119. CSSStyleSheet::AddRuleProcessor(nsCSSRuleProcessor* aProcessor)
  1120. {
  1121. if (! mRuleProcessors) {
  1122. mRuleProcessors = new AutoTArray<nsCSSRuleProcessor*, 8>();
  1123. if (!mRuleProcessors)
  1124. return NS_ERROR_OUT_OF_MEMORY;
  1125. }
  1126. NS_ASSERTION(mRuleProcessors->NoIndex == mRuleProcessors->IndexOf(aProcessor),
  1127. "processor already registered");
  1128. mRuleProcessors->AppendElement(aProcessor); // weak ref
  1129. return NS_OK;
  1130. }
  1131. nsresult
  1132. CSSStyleSheet::DropRuleProcessor(nsCSSRuleProcessor* aProcessor)
  1133. {
  1134. if (!mRuleProcessors)
  1135. return NS_ERROR_FAILURE;
  1136. return mRuleProcessors->RemoveElement(aProcessor)
  1137. ? NS_OK
  1138. : NS_ERROR_FAILURE;
  1139. }
  1140. void
  1141. CSSStyleSheet::AddStyleSet(nsStyleSet* aStyleSet)
  1142. {
  1143. NS_ASSERTION(!mStyleSets.Contains(aStyleSet),
  1144. "style set already registered");
  1145. mStyleSets.AppendElement(aStyleSet);
  1146. }
  1147. void
  1148. CSSStyleSheet::DropStyleSet(nsStyleSet* aStyleSet)
  1149. {
  1150. DebugOnly<bool> found = mStyleSets.RemoveElement(aStyleSet);
  1151. NS_ASSERTION(found, "didn't find style set");
  1152. }
  1153. bool
  1154. CSSStyleSheet::UseForPresentation(nsPresContext* aPresContext,
  1155. nsMediaQueryResultCacheKey& aKey) const
  1156. {
  1157. if (mMedia) {
  1158. return mMedia->Matches(aPresContext, &aKey);
  1159. }
  1160. return true;
  1161. }
  1162. void
  1163. CSSStyleSheet::SetMedia(nsMediaList* aMedia)
  1164. {
  1165. mMedia = aMedia;
  1166. }
  1167. bool
  1168. CSSStyleSheet::HasRules() const
  1169. {
  1170. return StyleRuleCount() != 0;
  1171. }
  1172. void
  1173. CSSStyleSheet::SetEnabled(bool aEnabled)
  1174. {
  1175. // Internal method, so callers must handle BeginUpdate/EndUpdate
  1176. bool oldDisabled = mDisabled;
  1177. mDisabled = !aEnabled;
  1178. if (mInner->mComplete && oldDisabled != mDisabled) {
  1179. ClearRuleCascades();
  1180. if (mDocument) {
  1181. mDocument->SetStyleSheetApplicableState(this, !mDisabled);
  1182. }
  1183. }
  1184. }
  1185. CSSStyleSheet*
  1186. CSSStyleSheet::GetParentSheet() const
  1187. {
  1188. return mParent;
  1189. }
  1190. void
  1191. CSSStyleSheet::SetAssociatedDocument(nsIDocument* aDocument,
  1192. DocumentAssociationMode aAssociationMode)
  1193. {
  1194. MOZ_ASSERT_IF(!aDocument, aAssociationMode == NotOwnedByDocument);
  1195. // not ref counted
  1196. mDocument = aDocument;
  1197. mDocumentAssociationMode = aAssociationMode;
  1198. // Now set the same document on all our child sheets....
  1199. // XXXbz this is a little bogus; see the XXX comment where we
  1200. // declare mFirstChild.
  1201. for (CSSStyleSheet* child = mInner->mFirstChild;
  1202. child; child = child->mNext) {
  1203. if (child->mParent == this) {
  1204. child->SetAssociatedDocument(aDocument, aAssociationMode);
  1205. }
  1206. }
  1207. }
  1208. uint64_t
  1209. CSSStyleSheet::FindOwningWindowInnerID() const
  1210. {
  1211. uint64_t windowID = 0;
  1212. if (mDocument) {
  1213. windowID = mDocument->InnerWindowID();
  1214. }
  1215. if (windowID == 0 && mOwningNode) {
  1216. windowID = mOwningNode->OwnerDoc()->InnerWindowID();
  1217. }
  1218. if (windowID == 0 && mOwnerRule) {
  1219. RefPtr<CSSStyleSheet> sheet = static_cast<css::Rule*>(mOwnerRule)->GetStyleSheet();
  1220. if (sheet) {
  1221. windowID = sheet->FindOwningWindowInnerID();
  1222. }
  1223. }
  1224. if (windowID == 0 && mParent) {
  1225. windowID = mParent->FindOwningWindowInnerID();
  1226. }
  1227. return windowID;
  1228. }
  1229. void
  1230. CSSStyleSheet::AppendStyleSheet(CSSStyleSheet* aSheet)
  1231. {
  1232. NS_PRECONDITION(nullptr != aSheet, "null arg");
  1233. WillDirty();
  1234. RefPtr<CSSStyleSheet>* tail = &mInner->mFirstChild;
  1235. while (*tail) {
  1236. tail = &(*tail)->mNext;
  1237. }
  1238. *tail = aSheet;
  1239. // This is not reference counted. Our parent tells us when
  1240. // it's going away.
  1241. aSheet->mParent = this;
  1242. aSheet->mDocument = mDocument;
  1243. DidDirty();
  1244. }
  1245. void
  1246. CSSStyleSheet::AppendStyleRule(css::Rule* aRule)
  1247. {
  1248. NS_PRECONDITION(nullptr != aRule, "null arg");
  1249. WillDirty();
  1250. mInner->mOrderedRules.AppendObject(aRule);
  1251. aRule->SetStyleSheet(this);
  1252. DidDirty();
  1253. if (css::Rule::NAMESPACE_RULE == aRule->GetType()) {
  1254. #ifdef DEBUG
  1255. nsresult rv =
  1256. #endif
  1257. RegisterNamespaceRule(aRule);
  1258. NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
  1259. "RegisterNamespaceRule returned error");
  1260. }
  1261. }
  1262. int32_t
  1263. CSSStyleSheet::StyleRuleCount() const
  1264. {
  1265. return mInner->mOrderedRules.Count();
  1266. }
  1267. css::Rule*
  1268. CSSStyleSheet::GetStyleRuleAt(int32_t aIndex) const
  1269. {
  1270. // Important: If this function is ever made scriptable, we must add
  1271. // a security check here. See GetCssRules below for an example.
  1272. return mInner->mOrderedRules.SafeObjectAt(aIndex);
  1273. }
  1274. void
  1275. CSSStyleSheet::EnsureUniqueInner()
  1276. {
  1277. mDirty = true;
  1278. MOZ_ASSERT(mInner->mSheets.Length() != 0,
  1279. "unexpected number of outers");
  1280. if (mInner->mSheets.Length() == 1) {
  1281. // already unique
  1282. return;
  1283. }
  1284. CSSStyleSheetInner* clone = mInner->CloneFor(this);
  1285. MOZ_ASSERT(clone);
  1286. mInner->RemoveSheet(this);
  1287. mInner = clone;
  1288. // otherwise the rule processor has pointers to the old rules
  1289. ClearRuleCascades();
  1290. // let our containing style sets know that if we call
  1291. // nsPresContext::EnsureSafeToHandOutCSSRules we will need to restyle the
  1292. // document
  1293. for (nsStyleSet* styleSet : mStyleSets) {
  1294. styleSet->SetNeedsRestyleAfterEnsureUniqueInner();
  1295. }
  1296. }
  1297. void
  1298. CSSStyleSheet::AppendAllChildSheets(nsTArray<CSSStyleSheet*>& aArray)
  1299. {
  1300. for (CSSStyleSheet* child = mInner->mFirstChild; child;
  1301. child = child->mNext) {
  1302. aArray.AppendElement(child);
  1303. }
  1304. }
  1305. already_AddRefed<CSSStyleSheet>
  1306. CSSStyleSheet::Clone(CSSStyleSheet* aCloneParent,
  1307. css::ImportRule* aCloneOwnerRule,
  1308. nsIDocument* aCloneDocument,
  1309. nsINode* aCloneOwningNode) const
  1310. {
  1311. RefPtr<CSSStyleSheet> clone = new CSSStyleSheet(*this,
  1312. aCloneParent,
  1313. aCloneOwnerRule,
  1314. aCloneDocument,
  1315. aCloneOwningNode);
  1316. return clone.forget();
  1317. }
  1318. #ifdef DEBUG
  1319. static void
  1320. ListRules(const nsCOMArray<css::Rule>& aRules, FILE* aOut, int32_t aIndent)
  1321. {
  1322. for (int32_t index = aRules.Count() - 1; index >= 0; --index) {
  1323. aRules.ObjectAt(index)->List(aOut, aIndent);
  1324. }
  1325. }
  1326. struct ListEnumData {
  1327. ListEnumData(FILE* aOut, int32_t aIndent)
  1328. : mOut(aOut),
  1329. mIndent(aIndent)
  1330. {
  1331. }
  1332. FILE* mOut;
  1333. int32_t mIndent;
  1334. };
  1335. void
  1336. CSSStyleSheet::List(FILE* out, int32_t aIndent) const
  1337. {
  1338. int32_t index;
  1339. // Indent
  1340. nsAutoCString str;
  1341. for (index = aIndent; --index >= 0; ) {
  1342. str.AppendLiteral(" ");
  1343. }
  1344. str.AppendLiteral("CSS Style Sheet: ");
  1345. nsAutoCString urlSpec;
  1346. nsresult rv = mInner->mSheetURI->GetSpec(urlSpec);
  1347. if (NS_SUCCEEDED(rv) && !urlSpec.IsEmpty()) {
  1348. str.Append(urlSpec);
  1349. }
  1350. if (mMedia) {
  1351. str.AppendLiteral(" media: ");
  1352. nsAutoString buffer;
  1353. mMedia->GetText(buffer);
  1354. AppendUTF16toUTF8(buffer, str);
  1355. }
  1356. str.Append('\n');
  1357. fprintf_stderr(out, "%s", str.get());
  1358. for (const CSSStyleSheet* child = mInner->mFirstChild;
  1359. child;
  1360. child = child->mNext) {
  1361. child->List(out, aIndent + 1);
  1362. }
  1363. fprintf_stderr(out, "%s", "Rules in source order:\n");
  1364. ListRules(mInner->mOrderedRules, out, aIndent);
  1365. }
  1366. #endif
  1367. void
  1368. CSSStyleSheet::ClearRuleCascades()
  1369. {
  1370. // We might be in ClearRuleCascades because we had a modification
  1371. // to the sheet that resulted in an nsCSSSelector being destroyed.
  1372. // Tell the RestyleManager for each document we're used in
  1373. // so that they can drop any nsCSSSelector pointers (used for
  1374. // eRestyle_SomeDescendants) in their mPendingRestyles.
  1375. for (nsStyleSet* styleSet : mStyleSets) {
  1376. styleSet->ClearSelectors();
  1377. }
  1378. bool removedSheetFromRuleProcessorCache = false;
  1379. if (mRuleProcessors) {
  1380. nsCSSRuleProcessor **iter = mRuleProcessors->Elements(),
  1381. **end = iter + mRuleProcessors->Length();
  1382. for(; iter != end; ++iter) {
  1383. if (!removedSheetFromRuleProcessorCache && (*iter)->IsShared()) {
  1384. // Since the sheet has been modified, we need to remove all
  1385. // RuleProcessorCache entries that contain this sheet, as the
  1386. // list of @-moz-document rules might have changed.
  1387. RuleProcessorCache::RemoveSheet(this);
  1388. removedSheetFromRuleProcessorCache = true;
  1389. }
  1390. (*iter)->ClearRuleCascades();
  1391. }
  1392. }
  1393. if (mParent) {
  1394. CSSStyleSheet* parent = (CSSStyleSheet*)mParent;
  1395. parent->ClearRuleCascades();
  1396. }
  1397. }
  1398. void
  1399. CSSStyleSheet::WillDirty()
  1400. {
  1401. if (mInner->mComplete) {
  1402. EnsureUniqueInner();
  1403. }
  1404. }
  1405. void
  1406. CSSStyleSheet::DidDirty()
  1407. {
  1408. MOZ_ASSERT(!mInner->mComplete || mDirty,
  1409. "caller must have called WillDirty()");
  1410. ClearRuleCascades();
  1411. }
  1412. nsresult
  1413. CSSStyleSheet::RegisterNamespaceRule(css::Rule* aRule)
  1414. {
  1415. if (!mInner->mNameSpaceMap) {
  1416. nsresult rv = mInner->CreateNamespaceMap();
  1417. NS_ENSURE_SUCCESS(rv, rv);
  1418. }
  1419. AddNamespaceRuleToMap(aRule, mInner->mNameSpaceMap);
  1420. return NS_OK;
  1421. }
  1422. nsMediaList*
  1423. CSSStyleSheet::Media()
  1424. {
  1425. if (!mMedia) {
  1426. mMedia = new nsMediaList();
  1427. mMedia->SetStyleSheet(this);
  1428. }
  1429. return mMedia;
  1430. }
  1431. nsIDOMCSSRule*
  1432. CSSStyleSheet::GetDOMOwnerRule() const
  1433. {
  1434. return mOwnerRule ? mOwnerRule->GetDOMRule() : nullptr;
  1435. }
  1436. CSSRuleList*
  1437. CSSStyleSheet::GetCssRulesInternal(ErrorResult& aRv)
  1438. {
  1439. if (!mRuleCollection) {
  1440. mRuleCollection = new CSSRuleListImpl(this);
  1441. }
  1442. return mRuleCollection;
  1443. }
  1444. static bool
  1445. RuleHasPendingChildSheet(css::Rule *cssRule)
  1446. {
  1447. nsCOMPtr<nsIDOMCSSImportRule> importRule(do_QueryInterface(cssRule));
  1448. NS_ASSERTION(importRule, "Rule which has type IMPORT_RULE and does not implement nsIDOMCSSImportRule!");
  1449. nsCOMPtr<nsIDOMCSSStyleSheet> childSheet;
  1450. importRule->GetStyleSheet(getter_AddRefs(childSheet));
  1451. RefPtr<CSSStyleSheet> cssSheet = do_QueryObject(childSheet);
  1452. return cssSheet != nullptr && !cssSheet->IsComplete();
  1453. }
  1454. uint32_t
  1455. CSSStyleSheet::InsertRuleInternal(const nsAString& aRule,
  1456. uint32_t aIndex,
  1457. ErrorResult& aRv)
  1458. {
  1459. MOZ_ASSERT(mInner->mComplete);
  1460. WillDirty();
  1461. if (aIndex > uint32_t(mInner->mOrderedRules.Count())) {
  1462. aRv.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
  1463. return 0;
  1464. }
  1465. NS_ASSERTION(uint32_t(mInner->mOrderedRules.Count()) <= INT32_MAX,
  1466. "Too many style rules!");
  1467. // Hold strong ref to the CSSLoader in case the document update
  1468. // kills the document
  1469. RefPtr<css::Loader> loader;
  1470. if (mDocument) {
  1471. loader = mDocument->CSSLoader();
  1472. NS_ASSERTION(loader, "Document with no CSS loader!");
  1473. }
  1474. nsCSSParser css(loader, this);
  1475. mozAutoDocUpdate updateBatch(mDocument, UPDATE_STYLE, true);
  1476. RefPtr<css::Rule> rule;
  1477. aRv = css.ParseRule(aRule, mInner->mSheetURI, mInner->mBaseURI,
  1478. mInner->mPrincipal, getter_AddRefs(rule));
  1479. if (NS_WARN_IF(aRv.Failed())) {
  1480. return 0;
  1481. }
  1482. // Hierarchy checking.
  1483. int32_t newType = rule->GetType();
  1484. // check that we're not inserting before a charset rule
  1485. css::Rule* nextRule = mInner->mOrderedRules.SafeObjectAt(aIndex);
  1486. if (nextRule) {
  1487. int32_t nextType = nextRule->GetType();
  1488. if (nextType == css::Rule::CHARSET_RULE) {
  1489. aRv.Throw(NS_ERROR_DOM_HIERARCHY_REQUEST_ERR);
  1490. return 0;
  1491. }
  1492. if (nextType == css::Rule::IMPORT_RULE &&
  1493. newType != css::Rule::CHARSET_RULE &&
  1494. newType != css::Rule::IMPORT_RULE) {
  1495. aRv.Throw(NS_ERROR_DOM_HIERARCHY_REQUEST_ERR);
  1496. return 0;
  1497. }
  1498. if (nextType == css::Rule::NAMESPACE_RULE &&
  1499. newType != css::Rule::CHARSET_RULE &&
  1500. newType != css::Rule::IMPORT_RULE &&
  1501. newType != css::Rule::NAMESPACE_RULE) {
  1502. aRv.Throw(NS_ERROR_DOM_HIERARCHY_REQUEST_ERR);
  1503. return 0;
  1504. }
  1505. }
  1506. if (aIndex != 0) {
  1507. // no inserting charset at nonzero position
  1508. if (newType == css::Rule::CHARSET_RULE) {
  1509. aRv.Throw(NS_ERROR_DOM_HIERARCHY_REQUEST_ERR);
  1510. return 0;
  1511. }
  1512. css::Rule* prevRule = mInner->mOrderedRules.SafeObjectAt(aIndex - 1);
  1513. int32_t prevType = prevRule->GetType();
  1514. if (newType == css::Rule::IMPORT_RULE &&
  1515. prevType != css::Rule::CHARSET_RULE &&
  1516. prevType != css::Rule::IMPORT_RULE) {
  1517. aRv.Throw(NS_ERROR_DOM_HIERARCHY_REQUEST_ERR);
  1518. return 0;
  1519. }
  1520. if (newType == css::Rule::NAMESPACE_RULE &&
  1521. prevType != css::Rule::CHARSET_RULE &&
  1522. prevType != css::Rule::IMPORT_RULE &&
  1523. prevType != css::Rule::NAMESPACE_RULE) {
  1524. aRv.Throw(NS_ERROR_DOM_HIERARCHY_REQUEST_ERR);
  1525. return 0;
  1526. }
  1527. }
  1528. if (!mInner->mOrderedRules.InsertObjectAt(rule, aIndex)) {
  1529. aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
  1530. return 0;
  1531. }
  1532. DidDirty();
  1533. rule->SetStyleSheet(this);
  1534. int32_t type = rule->GetType();
  1535. if (type == css::Rule::NAMESPACE_RULE) {
  1536. // XXXbz does this screw up when inserting a namespace rule before
  1537. // another namespace rule that binds the same prefix to a different
  1538. // namespace?
  1539. aRv = RegisterNamespaceRule(rule);
  1540. if (NS_WARN_IF(aRv.Failed())) {
  1541. return 0;
  1542. }
  1543. }
  1544. // We don't notify immediately for @import rules, but rather when
  1545. // the sheet the rule is importing is loaded (see StyleSheetLoaded)
  1546. if ((type != css::Rule::IMPORT_RULE || !RuleHasPendingChildSheet(rule)) &&
  1547. mDocument) {
  1548. mDocument->StyleRuleAdded(this, rule);
  1549. }
  1550. return aIndex;
  1551. }
  1552. void
  1553. CSSStyleSheet::DeleteRuleInternal(uint32_t aIndex, ErrorResult& aRv)
  1554. {
  1555. // XXX TBI: handle @rule types
  1556. mozAutoDocUpdate updateBatch(mDocument, UPDATE_STYLE, true);
  1557. WillDirty();
  1558. if (aIndex >= uint32_t(mInner->mOrderedRules.Count())) {
  1559. aRv.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
  1560. return;
  1561. }
  1562. NS_ASSERTION(uint32_t(mInner->mOrderedRules.Count()) <= INT32_MAX,
  1563. "Too many style rules!");
  1564. // Hold a strong ref to the rule so it doesn't die when we RemoveObjectAt
  1565. RefPtr<css::Rule> rule = mInner->mOrderedRules.ObjectAt(aIndex);
  1566. if (rule) {
  1567. mInner->mOrderedRules.RemoveObjectAt(aIndex);
  1568. if (mDocument && mDocument->StyleSheetChangeEventsEnabled()) {
  1569. // Force creation of the DOM rule, so that it can be put on the
  1570. // StyleRuleRemoved event object.
  1571. rule->GetDOMRule();
  1572. }
  1573. rule->SetStyleSheet(nullptr);
  1574. DidDirty();
  1575. if (mDocument) {
  1576. mDocument->StyleRuleRemoved(this, rule);
  1577. }
  1578. }
  1579. }
  1580. nsresult
  1581. CSSStyleSheet::DeleteRuleFromGroup(css::GroupRule* aGroup, uint32_t aIndex)
  1582. {
  1583. NS_ENSURE_ARG_POINTER(aGroup);
  1584. NS_ASSERTION(mInner->mComplete, "No deleting from an incomplete sheet!");
  1585. RefPtr<css::Rule> rule = aGroup->GetStyleRuleAt(aIndex);
  1586. NS_ENSURE_TRUE(rule, NS_ERROR_ILLEGAL_VALUE);
  1587. // check that the rule actually belongs to this sheet!
  1588. if (this != rule->GetStyleSheet()) {
  1589. return NS_ERROR_INVALID_ARG;
  1590. }
  1591. mozAutoDocUpdate updateBatch(mDocument, UPDATE_STYLE, true);
  1592. WillDirty();
  1593. nsresult result = aGroup->DeleteStyleRuleAt(aIndex);
  1594. NS_ENSURE_SUCCESS(result, result);
  1595. rule->SetStyleSheet(nullptr);
  1596. DidDirty();
  1597. if (mDocument) {
  1598. mDocument->StyleRuleRemoved(this, rule);
  1599. }
  1600. return NS_OK;
  1601. }
  1602. nsresult
  1603. CSSStyleSheet::InsertRuleIntoGroup(const nsAString & aRule,
  1604. css::GroupRule* aGroup,
  1605. uint32_t aIndex,
  1606. uint32_t* _retval)
  1607. {
  1608. NS_ASSERTION(mInner->mComplete, "No inserting into an incomplete sheet!");
  1609. // check that the group actually belongs to this sheet!
  1610. if (this != aGroup->GetStyleSheet()) {
  1611. return NS_ERROR_INVALID_ARG;
  1612. }
  1613. // Hold strong ref to the CSSLoader in case the document update
  1614. // kills the document
  1615. RefPtr<css::Loader> loader;
  1616. if (mDocument) {
  1617. loader = mDocument->CSSLoader();
  1618. NS_ASSERTION(loader, "Document with no CSS loader!");
  1619. }
  1620. nsCSSParser css(loader, this);
  1621. // parse and grab the rule
  1622. mozAutoDocUpdate updateBatch(mDocument, UPDATE_STYLE, true);
  1623. WillDirty();
  1624. RefPtr<css::Rule> rule;
  1625. nsresult result = css.ParseRule(aRule, mInner->mSheetURI, mInner->mBaseURI,
  1626. mInner->mPrincipal, getter_AddRefs(rule));
  1627. if (NS_FAILED(result))
  1628. return result;
  1629. switch (rule->GetType()) {
  1630. case css::Rule::STYLE_RULE:
  1631. case css::Rule::MEDIA_RULE:
  1632. case css::Rule::FONT_FACE_RULE:
  1633. case css::Rule::PAGE_RULE:
  1634. case css::Rule::KEYFRAMES_RULE:
  1635. case css::Rule::COUNTER_STYLE_RULE:
  1636. case css::Rule::DOCUMENT_RULE:
  1637. case css::Rule::SUPPORTS_RULE:
  1638. // these types are OK to insert into a group
  1639. break;
  1640. case css::Rule::CHARSET_RULE:
  1641. case css::Rule::IMPORT_RULE:
  1642. case css::Rule::NAMESPACE_RULE:
  1643. // these aren't
  1644. return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
  1645. default:
  1646. NS_NOTREACHED("unexpected rule type");
  1647. return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
  1648. }
  1649. result = aGroup->InsertStyleRuleAt(aIndex, rule);
  1650. NS_ENSURE_SUCCESS(result, result);
  1651. DidDirty();
  1652. if (mDocument) {
  1653. mDocument->StyleRuleAdded(this, rule);
  1654. }
  1655. *_retval = aIndex;
  1656. return NS_OK;
  1657. }
  1658. // nsICSSLoaderObserver implementation
  1659. NS_IMETHODIMP
  1660. CSSStyleSheet::StyleSheetLoaded(StyleSheet* aSheet,
  1661. bool aWasAlternate,
  1662. nsresult aStatus)
  1663. {
  1664. MOZ_ASSERT(aSheet->IsGecko(),
  1665. "why we were called back with a ServoStyleSheet?");
  1666. CSSStyleSheet* sheet = aSheet->AsGecko();
  1667. if (sheet->GetParentSheet() == nullptr) {
  1668. return NS_OK; // ignore if sheet has been detached already (see parseSheet)
  1669. }
  1670. NS_ASSERTION(this == sheet->GetParentSheet(),
  1671. "We are being notified of a sheet load for a sheet that is not our child!");
  1672. if (mDocument && NS_SUCCEEDED(aStatus)) {
  1673. mozAutoDocUpdate updateBatch(mDocument, UPDATE_STYLE, true);
  1674. // XXXldb @import rules shouldn't even implement nsIStyleRule (but
  1675. // they do)!
  1676. mDocument->StyleRuleAdded(this, sheet->GetOwnerRule());
  1677. }
  1678. return NS_OK;
  1679. }
  1680. nsresult
  1681. CSSStyleSheet::ReparseSheet(const nsAString& aInput)
  1682. {
  1683. // Not doing this if the sheet is not complete!
  1684. if (!mInner->mComplete) {
  1685. return NS_ERROR_DOM_INVALID_ACCESS_ERR;
  1686. }
  1687. // Hold strong ref to the CSSLoader in case the document update
  1688. // kills the document
  1689. RefPtr<css::Loader> loader;
  1690. if (mDocument) {
  1691. loader = mDocument->CSSLoader();
  1692. NS_ASSERTION(loader, "Document with no CSS loader!");
  1693. } else {
  1694. loader = new css::Loader(StyleBackendType::Gecko);
  1695. }
  1696. mozAutoDocUpdate updateBatch(mDocument, UPDATE_STYLE, true);
  1697. WillDirty();
  1698. // detach existing rules (including child sheets via import rules)
  1699. css::LoaderReusableStyleSheets reusableSheets;
  1700. int ruleCount;
  1701. while ((ruleCount = mInner->mOrderedRules.Count()) != 0) {
  1702. RefPtr<css::Rule> rule = mInner->mOrderedRules.ObjectAt(ruleCount - 1);
  1703. mInner->mOrderedRules.RemoveObjectAt(ruleCount - 1);
  1704. rule->SetStyleSheet(nullptr);
  1705. if (rule->GetType() == css::Rule::IMPORT_RULE) {
  1706. nsCOMPtr<nsIDOMCSSImportRule> importRule(do_QueryInterface(rule));
  1707. NS_ASSERTION(importRule, "GetType lied");
  1708. nsCOMPtr<nsIDOMCSSStyleSheet> childSheet;
  1709. importRule->GetStyleSheet(getter_AddRefs(childSheet));
  1710. RefPtr<CSSStyleSheet> cssSheet = do_QueryObject(childSheet);
  1711. if (cssSheet && cssSheet->GetOriginalURI()) {
  1712. reusableSheets.AddReusableSheet(cssSheet);
  1713. }
  1714. }
  1715. if (mDocument) {
  1716. mDocument->StyleRuleRemoved(this, rule);
  1717. }
  1718. }
  1719. // nuke child sheets list and current namespace map
  1720. for (CSSStyleSheet* child = mInner->mFirstChild; child; ) {
  1721. NS_ASSERTION(child->mParent == this, "Child sheet is not parented to this!");
  1722. CSSStyleSheet* next = child->mNext;
  1723. child->mParent = nullptr;
  1724. child->mDocument = nullptr;
  1725. child->mNext = nullptr;
  1726. child = next;
  1727. }
  1728. mInner->mFirstChild = nullptr;
  1729. mInner->mNameSpaceMap = nullptr;
  1730. uint32_t lineNumber = 1;
  1731. if (mOwningNode) {
  1732. nsCOMPtr<nsIStyleSheetLinkingElement> link = do_QueryInterface(mOwningNode);
  1733. if (link) {
  1734. lineNumber = link->GetLineNumber();
  1735. }
  1736. }
  1737. nsCSSParser parser(loader, this);
  1738. nsresult rv = parser.ParseSheet(aInput, mInner->mSheetURI, mInner->mBaseURI,
  1739. mInner->mPrincipal, lineNumber, &reusableSheets);
  1740. DidDirty(); // we are always 'dirty' here since we always remove rules first
  1741. NS_ENSURE_SUCCESS(rv, rv);
  1742. // notify document of all new rules
  1743. if (mDocument) {
  1744. for (int32_t index = 0; index < mInner->mOrderedRules.Count(); ++index) {
  1745. RefPtr<css::Rule> rule = mInner->mOrderedRules.ObjectAt(index);
  1746. if (rule->GetType() == css::Rule::IMPORT_RULE &&
  1747. RuleHasPendingChildSheet(rule)) {
  1748. continue; // notify when loaded (see StyleSheetLoaded)
  1749. }
  1750. mDocument->StyleRuleAdded(this, rule);
  1751. }
  1752. }
  1753. return NS_OK;
  1754. }
  1755. } // namespace mozilla