Bug 1698238 return default dictionary from GetUserMediaRequest#getConstraints() if...
[gecko.git] / dom / base / nsContentUtils.h
blob496113cd60a51761141863d44a8e3174c1149f57
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
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/. */
7 /* A namespace class for static content utilities. */
9 #ifndef nsContentUtils_h___
10 #define nsContentUtils_h___
12 #if defined(XP_WIN)
13 # include <float.h>
14 #endif
16 #if defined(SOLARIS)
17 # include <ieeefp.h>
18 #endif
20 #include <cstddef>
21 #include <cstdint>
22 #include <functional>
23 #include <tuple>
24 #include <utility>
25 #include "ErrorList.h"
26 #include "Units.h"
27 #include "js/Id.h"
28 #include "js/RootingAPI.h"
29 #include "mozilla/AlreadyAddRefed.h"
30 #include "mozilla/Assertions.h"
31 #include "mozilla/Attributes.h"
32 #include "mozilla/BasicEvents.h"
33 #include "mozilla/CORSMode.h"
34 #include "mozilla/CallState.h"
35 #include "mozilla/Maybe.h"
36 #include "mozilla/RefPtr.h"
37 #include "mozilla/TaskCategory.h"
38 #include "mozilla/TimeStamp.h"
39 #include "mozilla/UniquePtr.h"
40 #include "mozilla/dom/BindingDeclarations.h"
41 #include "mozilla/dom/FromParser.h"
42 #include "mozilla/fallible.h"
43 #include "mozilla/gfx/Point.h"
44 #include "nsCOMPtr.h"
45 #include "nsHashtablesFwd.h"
46 #include "nsIContentPolicy.h"
47 #include "nsID.h"
48 #include "nsINode.h"
49 #include "nsIScriptError.h"
50 #include "nsIThread.h"
51 #include "nsLiteralString.h"
52 #include "nsMargin.h"
53 #include "nsPIDOMWindow.h"
54 #include "nsStringFwd.h"
55 #include "nsTArray.h"
56 #include "nsTLiteralString.h"
57 #include "prtime.h"
59 #if defined(XP_WIN)
60 // Undefine LoadImage to prevent naming conflict with Windows.
61 # undef LoadImage
62 #endif
64 class JSObject;
65 class imgICache;
66 class imgIContainer;
67 class imgINotificationObserver;
68 class imgIRequest;
69 class imgLoader;
70 class imgRequestProxy;
71 class nsAtom;
72 class nsAttrValue;
73 class nsAutoScriptBlockerSuppressNodeRemoved;
74 class nsContentList;
75 class nsCycleCollectionTraversalCallback;
76 class nsDocShell;
77 class nsGlobalWindowInner;
78 class nsHtml5StringParser;
79 class nsIArray;
80 class nsIBidiKeyboard;
81 class nsIChannel;
82 class nsIConsoleService;
83 class nsIContent;
84 class nsIDocShell;
85 class nsIDocShellTreeItem;
86 class nsIDocumentLoaderFactory;
87 class nsIDragSession;
88 class nsIFile;
89 class nsIFragmentContentSink;
90 class nsIFrame;
91 class nsIHttpChannel;
92 class nsIIOService;
93 class nsIImageLoadingContent;
94 class nsIInterfaceRequestor;
95 class nsILoadGroup;
96 class nsILoadInfo;
97 class nsIObserver;
98 class nsIParser;
99 class nsIPluginTag;
100 class nsIPrincipal;
101 class nsIReferrerInfo;
102 class nsIRequest;
103 class nsIRunnable;
104 class nsIScreen;
105 class nsIScriptContext;
106 class nsIScriptSecurityManager;
107 class nsISerialEventTarget;
108 class nsIStringBundle;
109 class nsIStringBundleService;
110 class nsISupports;
111 class nsITransferable;
112 class nsIURI;
113 class nsIUUIDGenerator;
114 class nsIWidget;
115 class nsIXPConnect;
116 class nsNameSpaceManager;
117 class nsNodeInfoManager;
118 class nsPIWindowRoot;
119 class nsPresContext;
120 class nsStringBuffer;
121 class nsStringHashKey;
122 class nsTextFragment;
123 class nsView;
124 class nsWrapperCache;
126 struct JSContext;
127 struct nsPoint;
129 template <class T>
130 class nsRefPtrHashKey;
132 namespace IPC {
133 class Message;
136 namespace JS {
137 class Value;
139 struct PropertyDescriptor;
140 } // namespace JS
142 namespace mozilla {
143 class Dispatcher;
144 class ErrorResult;
145 class EventListenerManager;
146 class HTMLEditor;
147 class LazyLogModule;
148 class LogModule;
149 class PresShell;
150 class TextEditor;
151 class WidgetDragEvent;
152 class WidgetKeyboardEvent;
154 struct InputEventOptions;
156 template <typename ParentType, typename RefType>
157 class RangeBoundaryBase;
159 template <typename T>
160 class NotNull;
161 template <class T>
162 class StaticRefPtr;
164 namespace dom {
165 struct AutocompleteInfo;
166 class BrowserChild;
167 class BrowserParent;
168 class BrowsingContext;
169 class BrowsingContextGroup;
170 class ContentChild;
171 class ContentFrameMessageManager;
172 class ContentParent;
173 struct CustomElementDefinition;
174 class CustomElementRegistry;
175 class DataTransfer;
176 class Document;
177 class DocumentFragment;
178 class DOMArena;
179 class Element;
180 class Event;
181 class EventTarget;
182 class HTMLInputElement;
183 class IPCDataTransfer;
184 class IPCDataTransferItem;
185 struct LifecycleCallbackArgs;
186 struct LifecycleAdoptedCallbackArgs;
187 class MessageBroadcaster;
188 class NodeInfo;
189 class Selection;
190 class WorkerPrivate;
191 enum class ElementCallbackType;
192 enum class ReferrerPolicy : uint8_t;
193 } // namespace dom
195 namespace intl {
196 class LineBreaker;
197 class WordBreaker;
198 } // namespace intl
200 namespace ipc {
201 class Shmem;
202 class IShmemAllocator;
203 } // namespace ipc
205 namespace gfx {
206 class DataSourceSurface;
207 enum class SurfaceFormat : int8_t;
208 } // namespace gfx
210 namespace layers {
211 class LayerManager;
212 } // namespace layers
214 } // namespace mozilla
216 extern const char kLoadAsData[];
218 // Stolen from nsReadableUtils, but that's OK, since we can declare the same
219 // name multiple times.
220 const nsString& EmptyString();
221 const nsCString& EmptyCString();
223 enum EventNameType {
224 EventNameType_None = 0x0000,
225 EventNameType_HTML = 0x0001,
226 EventNameType_XUL = 0x0002,
227 EventNameType_SVGGraphic = 0x0004, // svg graphic elements
228 EventNameType_SVGSVG = 0x0008, // the svg element
229 EventNameType_SMIL = 0x0010, // smil elements
230 EventNameType_HTMLBodyOrFramesetOnly = 0x0020,
231 EventNameType_HTMLMarqueeOnly = 0x0040,
233 EventNameType_HTMLXUL = 0x0003,
234 EventNameType_All = 0xFFFF
237 struct EventNameMapping {
238 // This holds pointers to nsGkAtoms members, and is therefore safe as a
239 // non-owning reference.
240 nsAtom* MOZ_NON_OWNING_REF mAtom;
241 int32_t mType;
242 mozilla::EventMessage mMessage;
243 mozilla::EventClassID mEventClassID;
244 // True if mAtom is possibly used by special SVG/SMIL events, but
245 // mMessage is eUnidentifiedEvent. See EventNameList.h
246 bool mMaybeSpecialSVGorSMILEvent;
249 class nsContentUtils {
250 friend class nsAutoScriptBlockerSuppressNodeRemoved;
251 typedef mozilla::dom::Element Element;
252 typedef mozilla::dom::Document Document;
253 typedef mozilla::Cancelable Cancelable;
254 typedef mozilla::CanBubble CanBubble;
255 typedef mozilla::Composed Composed;
256 typedef mozilla::ChromeOnlyDispatch ChromeOnlyDispatch;
257 typedef mozilla::EventMessage EventMessage;
258 typedef mozilla::TimeDuration TimeDuration;
259 typedef mozilla::Trusted Trusted;
261 public:
262 static nsresult Init();
264 static bool IsCallerChrome();
265 static bool ThreadsafeIsCallerChrome();
266 static bool IsCallerUAWidget();
267 static bool IsFuzzingEnabled()
268 #ifndef FUZZING
270 return false;
272 #else
274 #endif
275 static bool IsErrorPage(nsIURI* aURI);
277 static bool IsCallerChromeOrFuzzingEnabled(JSContext* aCx, JSObject*) {
278 return ThreadsafeIsSystemCaller(aCx) || IsFuzzingEnabled();
281 static bool IsCallerChromeOrElementTransformGettersEnabled(JSContext* aCx,
282 JSObject*);
284 // The APIs for checking whether the caller is system (in the sense of system
285 // principal) should only be used when the JSContext is known to accurately
286 // represent the caller. In practice, that means you should only use them in
287 // two situations at the moment:
289 // 1) Functions used in WebIDL Func annotations.
290 // 2) Bindings code or other code called directly from the JS engine.
292 // Use pretty much anywhere else is almost certainly wrong and should be
293 // replaced with [NeedsCallerType] annotations in bindings.
295 // Check whether the caller is system if you know you're on the main thread.
296 static bool IsSystemCaller(JSContext* aCx);
298 // Check whether the caller is system if you might be on a worker or worklet
299 // thread.
300 static bool ThreadsafeIsSystemCaller(JSContext* aCx);
302 // In the traditional Gecko architecture, both C++ code and untrusted JS code
303 // needed to rely on the same XPCOM method/getter/setter to get work done.
304 // This required lots of security checks in the various exposed methods, which
305 // in turn created difficulty in determining whether the caller was script
306 // (whose access needed to be checked) and internal C++ platform code (whose
307 // access did not need to be checked). To address this problem, Gecko had a
308 // convention whereby the absence of script on the stack was interpretted as
309 // "System Caller" and always granted unfettered access.
311 // Unfortunately, this created a bunch of footguns. For example, when the
312 // implementation of a DOM method wanted to perform a privileged
313 // sub-operation, it needed to "hide" the presence of script on the stack in
314 // order for that sub-operation to be allowed. Additionally, if script could
315 // trigger an API entry point to be invoked in some asynchronous way without
316 // script on the stack, it could potentially perform privilege escalation.
318 // In the modern world, untrusted script should interact with the platform
319 // exclusively over WebIDL APIs, and platform code has a lot more flexibility
320 // in deciding whether or not to use XPCOM. This gives us the flexibility to
321 // do something better.
323 // Going forward, APIs should be designed such that any security checks that
324 // ask the question "is my caller allowed to do this?" should live in WebIDL
325 // API entry points, with a separate method provided for internal callers
326 // that just want to get the job done.
328 // To enforce this and catch bugs, nsContentUtils::SubjectPrincipal will crash
329 // if it is invoked without script on the stack. To land that transition, it
330 // was necessary to go through and whitelist a bunch of callers that were
331 // depending on the old behavior. Those callers should be fixed up, and these
332 // methods should not be used by new code without review from bholley or bz.
333 static bool LegacyIsCallerNativeCode() { return !GetCurrentJSContext(); }
334 static bool LegacyIsCallerChromeOrNativeCode() {
335 return LegacyIsCallerNativeCode() || IsCallerChrome();
337 static nsIPrincipal* SubjectPrincipalOrSystemIfNativeCaller() {
338 if (!GetCurrentJSContext()) {
339 return GetSystemPrincipal();
341 return SubjectPrincipal();
344 static bool LookupBindingMember(
345 JSContext* aCx, nsIContent* aContent, JS::Handle<jsid> aId,
346 JS::MutableHandle<JS::PropertyDescriptor> aDesc);
348 // Check whether we should avoid leaking distinguishing information to JS/CSS.
349 // This function can be called both in the main thread and worker threads.
350 static bool ShouldResistFingerprinting();
351 static bool ShouldResistFingerprinting(nsIDocShell* aDocShell);
352 static bool ShouldResistFingerprinting(nsIPrincipal* aPrincipal);
353 static bool ShouldResistFingerprinting(
354 mozilla::dom::WorkerPrivate* aWorkerPrivate);
355 static bool ShouldResistFingerprinting(const Document* aDoc);
357 // Prevent system colors from being exposed to CSS or canvas.
358 static bool UseStandinsForNativeColors();
360 // A helper function to calculate the rounded window size for fingerprinting
361 // resistance. The rounded size is based on the chrome UI size and available
362 // screen size. If the inputWidth/Height is greater than the available content
363 // size, this will report the available content size. Otherwise, it will
364 // round the size to the nearest upper 200x100.
365 static void CalcRoundedWindowSizeForResistingFingerprinting(
366 int32_t aChromeWidth, int32_t aChromeHeight, int32_t aScreenWidth,
367 int32_t aScreenHeight, int32_t aInputWidth, int32_t aInputHeight,
368 bool aSetOuterWidth, bool aSetOuterHeight, int32_t* aOutputWidth,
369 int32_t* aOutputHeight);
372 * Returns the parent node of aChild crossing document boundaries, but skips
373 * any cross-process parent frames and continues with the nearest in-process
374 * frame in the hierarchy.
376 * Uses the parent node in the composed document.
378 static nsINode* GetNearestInProcessCrossDocParentNode(nsINode* aChild);
381 * Similar to nsINode::IsInclusiveDescendantOf, except will treat an
382 * HTMLTemplateElement or ShadowRoot as an ancestor of things in the
383 * corresponding DocumentFragment. See the concept of "host-including
384 * inclusive ancestor" in the DOM specification.
386 static bool ContentIsHostIncludingDescendantOf(
387 const nsINode* aPossibleDescendant, const nsINode* aPossibleAncestor);
390 * Similar to nsINode::IsInclusiveDescendantOf except it crosses document
391 * boundaries, this function uses ancestor/descendant relations in the
392 * composed document (see shadow DOM spec).
394 static bool ContentIsCrossDocDescendantOf(nsINode* aPossibleDescendant,
395 nsINode* aPossibleAncestor);
398 * As with ContentIsCrossDocDescendantOf but crosses shadow boundaries but not
399 * cross document boundaries.
401 * @see nsINode::GetFlattenedTreeParentNode()
403 static bool ContentIsFlattenedTreeDescendantOf(
404 const nsINode* aPossibleDescendant, const nsINode* aPossibleAncestor);
407 * Same as `ContentIsFlattenedTreeDescendantOf`, but from the flattened tree
408 * point of view of the style system
410 * @see nsINode::GetFlattenedTreeParentNodeForStyle()
412 static bool ContentIsFlattenedTreeDescendantOfForStyle(
413 const nsINode* aPossibleDescendant, const nsINode* aPossibleAncestor);
416 * Retarget an object A against an object B
417 * @see https://dom.spec.whatwg.org/#retarget
419 static nsINode* Retarget(nsINode* aTargetA, nsINode* aTargetB);
422 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor.
424 * This method fills the |aArray| with all ancestor nodes of |aNode|
425 * including |aNode| at the zero index.
428 static nsresult GetInclusiveAncestors(nsINode* aNode,
429 nsTArray<nsINode*>& aArray);
432 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor.
434 * This method fills |aAncestorNodes| with all ancestor nodes of |aNode|
435 * including |aNode| (QI'd to nsIContent) at the zero index.
436 * For each ancestor, there is a corresponding element in |aAncestorOffsets|
437 * which is the IndexOf the child in relation to its parent.
439 * This method just sucks.
441 static nsresult GetInclusiveAncestorsAndOffsets(
442 nsINode* aNode, int32_t aOffset, nsTArray<nsIContent*>* aAncestorNodes,
443 nsTArray<int32_t>* aAncestorOffsets);
446 * Returns the closest common inclusive ancestor
447 * (https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor) , if any,
448 * for two nodes.
450 * Returns null if the nodes are disconnected.
452 static nsINode* GetClosestCommonInclusiveAncestor(nsINode* aNode1,
453 nsINode* aNode2) {
454 if (aNode1 == aNode2) {
455 return aNode1;
458 return GetCommonAncestorHelper(aNode1, aNode2);
462 * Returns the common flattened tree ancestor, if any, for two given content
463 * nodes.
465 static nsIContent* GetCommonFlattenedTreeAncestor(nsIContent* aContent1,
466 nsIContent* aContent2) {
467 if (aContent1 == aContent2) {
468 return aContent1;
471 return GetCommonFlattenedTreeAncestorHelper(aContent1, aContent2);
475 * Returns the common flattened tree ancestor from the point of view of the
476 * style system, if any, for two given content nodes.
478 static Element* GetCommonFlattenedTreeAncestorForStyle(Element* aElement1,
479 Element* aElement2);
482 * Returns the common ancestor under interactive content, if any.
483 * If neither one has interactive content as ancestor, common ancestor will be
484 * returned. If only one has interactive content as ancestor, null will be
485 * returned. If the nodes are the same, that node is returned.
487 static nsINode* GetCommonAncestorUnderInteractiveContent(nsINode* aNode1,
488 nsINode* aNode2);
491 * Returns the common BrowserParent ancestor, if any, for two given
492 * BrowserParent.
494 static mozilla::dom::BrowserParent* GetCommonBrowserParentAncestor(
495 mozilla::dom::BrowserParent* aBrowserParent1,
496 mozilla::dom::BrowserParent* aBrowserParent2);
499 * Returns true if aNode1 is before aNode2 in the same connected
500 * tree.
501 * aNode1Index and aNode2Index are in/out arguments. If non-null, and value is
502 * not -1, that value is used instead of calling slow ComputeIndexOf on the
503 * parent node. If value is -1, the value will be set to the return value of
504 * ComputeIndexOf.
506 static bool PositionIsBefore(nsINode* aNode1, nsINode* aNode2,
507 int32_t* aNode1Index = nullptr,
508 int32_t* aNode2Index = nullptr);
510 struct ComparePointsCache {
511 int32_t ComputeIndexOf(const nsINode* aParent, const nsINode* aChild) {
512 if (aParent == mParent && aChild == mChild) {
513 return mIndex;
516 mIndex = aParent->ComputeIndexOf(aChild);
517 mParent = aParent;
518 mChild = aChild;
519 return mIndex;
522 private:
523 const nsINode* mParent = nullptr;
524 const nsINode* mChild = nullptr;
525 int32_t mIndex = 0;
529 * Utility routine to compare two "points", where a point is a node/offset
530 * pair.
531 * Pass a cache object as aParent1Cache if you expect to repeatedly
532 * call this function with the same value as aParent1.
534 * XXX aOffset1 and aOffset2 should be uint32_t since valid offset value is
535 * between 0 - UINT32_MAX. However, these methods work even with
536 * negative offset values! E.g., when aOffset1 is -1 and aOffset is 0,
537 * these methods return -1. Some root callers depend on this behavior.
539 * @return -1 if point1 < point2,
540 * 1 if point1 > point2,
541 * 0 if point1 == point2.
542 * `Nothing` if the two nodes aren't in the same connected subtree.
544 static mozilla::Maybe<int32_t> ComparePoints(
545 const nsINode* aParent1, int32_t aOffset1, const nsINode* aParent2,
546 int32_t aOffset2, ComparePointsCache* aParent1Cache = nullptr);
547 template <typename FPT, typename FRT, typename SPT, typename SRT>
548 static mozilla::Maybe<int32_t> ComparePoints(
549 const mozilla::RangeBoundaryBase<FPT, FRT>& aFirstBoundary,
550 const mozilla::RangeBoundaryBase<SPT, SRT>& aSecondBoundary);
553 * Utility routine to compare two "points", where a point is a
554 * node/offset pair
555 * Returns -1 if point1 < point2, 1, if point1 > point2,
556 * 0 if error or if point1 == point2.
557 * NOTE! If the two nodes aren't in the same connected subtree,
558 * the result is 1, and the optional aDisconnected parameter
559 * is set to true.
561 * Pass a cache object as aParent1Cache if you expect to repeatedly
562 * call this function with the same value as aParent1.
564 * XXX aOffset1 and aOffset2 should be uint32_t since valid offset value is
565 * between 0 - UINT32_MAX. However, these methods work even with
566 * negative offset values! E.g., when aOffset1 is -1 and aOffset is 0,
567 * these methods return -1. Some root callers depend on this behavior.
568 * On the other hand, nsINode can have ATTRCHILD_ARRAY_MAX_CHILD_COUN
569 * (0x3FFFFF) at most. Therefore, they can be int32_t for now.
571 static int32_t ComparePoints_Deprecated(
572 const nsINode* aParent1, int32_t aOffset1, const nsINode* aParent2,
573 int32_t aOffset2, bool* aDisconnected = nullptr,
574 ComparePointsCache* aParent1Cache = nullptr);
575 template <typename FPT, typename FRT, typename SPT, typename SRT>
576 static int32_t ComparePoints_Deprecated(
577 const mozilla::RangeBoundaryBase<FPT, FRT>& aFirstBoundary,
578 const mozilla::RangeBoundaryBase<SPT, SRT>& aSecondBoundary,
579 bool* aDisconnected = nullptr);
582 * Brute-force search of the element subtree rooted at aContent for
583 * an element with the given id. aId must be nonempty, otherwise
584 * this method may return nodes even if they have no id!
586 static Element* MatchElementId(nsIContent* aContent, const nsAString& aId);
589 * Similar to above, but to be used if one already has an atom for the ID
591 static Element* MatchElementId(nsIContent* aContent, const nsAtom* aId);
594 * Reverses the document position flags passed in.
596 * @param aDocumentPosition The document position flags to be reversed.
598 * @return The reversed document position flags.
600 * @see Node
602 static uint16_t ReverseDocumentPosition(uint16_t aDocumentPosition);
604 static const nsDependentSubstring TrimCharsInSet(const char* aSet,
605 const nsAString& aValue);
607 template <bool IsWhitespace(char16_t)>
608 static const nsDependentSubstring TrimWhitespace(const nsAString& aStr,
609 bool aTrimTrailing = true);
612 * Returns true if aChar is of class Ps, Pi, Po, Pf, or Pe.
614 static bool IsFirstLetterPunctuation(uint32_t aChar);
617 * Returns true if aChar is of class Lu, Ll, Lt, Lm, Lo, Nd, Nl or No
619 static bool IsAlphanumeric(uint32_t aChar);
620 static bool IsAlphanumericAt(const nsTextFragment* aFrag, uint32_t aOffset);
623 * Is the character an HTML whitespace character?
625 * We define whitespace using the list in HTML5 and css3-selectors:
626 * U+0009, U+000A, U+000C, U+000D, U+0020
628 * HTML 4.01 also lists U+200B (zero-width space).
630 static bool IsHTMLWhitespace(char16_t aChar);
633 * Returns whether the character is an HTML whitespace (see IsHTMLWhitespace)
634 * or a nbsp character (U+00A0).
636 static bool IsHTMLWhitespaceOrNBSP(char16_t aChar);
639 * https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements
641 static bool IsHTMLBlockLevelElement(nsIContent* aContent);
643 enum ParseHTMLIntegerResultFlags {
644 eParseHTMLInteger_NoFlags = 0,
645 // eParseHTMLInteger_NonStandard is set if the string representation of the
646 // integer was not the canonical one, but matches at least one of the
647 // following:
648 // * had leading whitespaces
649 // * had '+' sign
650 // * had leading '0'
651 // * was '-0'
652 eParseHTMLInteger_NonStandard = 1 << 0,
653 eParseHTMLInteger_DidNotConsumeAllInput = 1 << 1,
654 // Set if one or more error flags were set.
655 eParseHTMLInteger_Error = 1 << 2,
656 eParseHTMLInteger_ErrorNoValue = 1 << 3,
657 eParseHTMLInteger_ErrorOverflow = 1 << 4,
658 // Use this flag to detect the difference between overflow and underflow
659 eParseHTMLInteger_Negative = 1 << 5,
661 static int32_t ParseHTMLInteger(const nsAString& aValue,
662 ParseHTMLIntegerResultFlags* aResult);
663 static int32_t ParseHTMLInteger(const nsACString& aValue,
664 ParseHTMLIntegerResultFlags* aResult);
666 private:
667 template <class StringT>
668 static int32_t ParseHTMLIntegerImpl(const StringT& aValue,
669 ParseHTMLIntegerResultFlags* aResult);
671 public:
673 * Parse a margin string of format 'top, right, bottom, left' into
674 * an nsIntMargin.
676 * @param aString the string to parse
677 * @param aResult the resulting integer
678 * @return whether the value could be parsed
680 static bool ParseIntMarginValue(const nsAString& aString,
681 nsIntMargin& aResult);
684 * Parse the value of the <font size=""> attribute according to the HTML5
685 * spec as of April 16, 2012.
687 * @param aValue the value to parse
688 * @return 1 to 7, or 0 if the value couldn't be parsed
690 static int32_t ParseLegacyFontSize(const nsAString& aValue);
692 static void Shutdown();
695 * Checks whether two nodes come from the same origin.
697 static nsresult CheckSameOrigin(const nsINode* aTrustedNode,
698 const nsINode* unTrustedNode);
700 // Check if the (JS) caller can access aNode.
701 static bool CanCallerAccess(const nsINode* aNode);
703 // Check if the (JS) caller can access aWindow.
704 // aWindow can be either outer or inner window.
705 static bool CanCallerAccess(nsPIDOMWindowInner* aWindow);
707 // Check if the principal is chrome or an addon with the permission.
708 static bool PrincipalHasPermission(nsIPrincipal& aPrincipal,
709 const nsAtom* aPerm);
711 // Check if the JS caller is chrome or an addon with the permission.
712 static bool CallerHasPermission(JSContext* aCx, const nsAtom* aPerm);
715 * Returns the triggering principal which should be used for the given URL
716 * attribute value with the given subject principal.
718 * If the attribute value is not an absolute URL, the subject principal will
719 * be ignored, and the node principal of aContent will be used instead.
720 * If aContent is non-null, this function will always return a principal.
721 * Otherewise, it may return null if aSubjectPrincipal is null or is rejected
722 * based on the attribute value.
724 * @param aContent The content on which the attribute is being set.
725 * @param aAttrValue The URL value of the attribute. For parsed attribute
726 * values, such as `srcset`, this function should be called separately
727 * for each URL value it contains.
728 * @param aSubjectPrincipal The subject principal of the scripted caller
729 * responsible for setting the attribute, or null if no scripted caller
730 * can be determined.
732 static nsIPrincipal* GetAttrTriggeringPrincipal(
733 nsIContent* aContent, const nsAString& aAttrValue,
734 nsIPrincipal* aSubjectPrincipal);
737 * Returns true if the given string is guaranteed to be treated as an absolute
738 * URL, rather than a relative URL. In practice, this means any complete URL
739 * as supported by nsStandardURL, or any string beginning with a valid scheme
740 * which is known to the IO service, and has the URI_NORELATIVE flag.
742 * If the URL may be treated as absolute in some cases, but relative in others
743 * (for instance, "http:foo", which can be either an absolute or relative URL,
744 * depending on the context), this function returns false.
746 static bool IsAbsoluteURL(const nsACString& aURL);
748 // Check if a node is in the document prolog, i.e. before the document
749 // element.
750 static bool InProlog(nsINode* aNode);
752 static nsNameSpaceManager* NameSpaceManager() { return sNameSpaceManager; }
754 static nsIIOService* GetIOService() { return sIOService; }
756 static nsIBidiKeyboard* GetBidiKeyboard();
759 * Get the cache security manager service. Can return null if the layout
760 * module has been shut down.
762 static nsIScriptSecurityManager* GetSecurityManager() {
763 return sSecurityManager;
766 // Returns the subject principal from the JSContext. May only be called
767 // from the main thread and assumes an existing compartment.
768 static nsIPrincipal* SubjectPrincipal(JSContext* aCx);
770 // Returns the subject principal. Guaranteed to return non-null. May only
771 // be called when nsContentUtils is initialized.
772 static nsIPrincipal* SubjectPrincipal();
774 // Returns the prinipal of the given JS object. This may only be called on
775 // the main thread for objects from the main thread's JSRuntime. The object
776 // must not be a cross-compartment wrapper, because CCWs are not associated
777 // with a single realm.
778 static nsIPrincipal* ObjectPrincipal(JSObject* aObj);
780 static void GenerateStateKey(nsIContent* aContent, Document* aDocument,
781 nsACString& aKey);
784 * Create a new nsIURI from aSpec, using aBaseURI as the base. The
785 * origin charset of the new nsIURI will be the document charset of
786 * aDocument.
788 static nsresult NewURIWithDocumentCharset(nsIURI** aResult,
789 const nsAString& aSpec,
790 Document* aDocument,
791 nsIURI* aBaseURI);
794 * Returns true if |aName| is a name with dashes.
796 static bool IsNameWithDash(nsAtom* aName);
799 * Returns true if |aName| is a valid name to be registered via
800 * customElements.define.
802 static bool IsCustomElementName(nsAtom* aName, uint32_t aNameSpaceID);
804 static nsresult CheckQName(const nsAString& aQualifiedName,
805 bool aNamespaceAware = true,
806 const char16_t** aColon = nullptr);
808 static nsresult SplitQName(const nsIContent* aNamespaceResolver,
809 const nsString& aQName, int32_t* aNamespace,
810 nsAtom** aLocalName);
812 static nsresult GetNodeInfoFromQName(const nsAString& aNamespaceURI,
813 const nsAString& aQualifiedName,
814 nsNodeInfoManager* aNodeInfoManager,
815 uint16_t aNodeType,
816 mozilla::dom::NodeInfo** aNodeInfo);
818 static void SplitExpatName(const char16_t* aExpatName, nsAtom** aPrefix,
819 nsAtom** aTagName, int32_t* aNameSpaceID);
821 // Get a permission-manager setting for the given principal and type.
822 // If the pref doesn't exist or if it isn't ALLOW_ACTION, false is
823 // returned, otherwise true is returned. Always returns true for the
824 // system principal, and false for a null principal.
825 static bool IsSitePermAllow(nsIPrincipal* aPrincipal,
826 const nsACString& aType);
828 // Get a permission-manager setting for the given principal and type.
829 // If the pref doesn't exist or if it isn't DENY_ACTION, false is
830 // returned, otherwise true is returned. Always returns false for the
831 // system principal, and true for a null principal.
832 static bool IsSitePermDeny(nsIPrincipal* aPrincipal, const nsACString& aType);
834 // Get a permission-manager setting for the given principal and type.
835 // If the pref doesn't exist or if it isn't ALLOW_ACTION, false is
836 // returned, otherwise true is returned. Always returns true for the
837 // system principal, and false for a null principal.
838 // This version checks the permission for an exact host match on
839 // the principal
840 static bool IsExactSitePermAllow(nsIPrincipal* aPrincipal,
841 const nsACString& aType);
843 // Get a permission-manager setting for the given principal and type.
844 // If the pref doesn't exist or if it isn't DENY_ACTION, false is
845 // returned, otherwise true is returned. Always returns false for the
846 // system principal, and true for a null principal.
847 // This version checks the permission for an exact host match on
848 // the principal
849 static bool IsExactSitePermDeny(nsIPrincipal* aPrincipal,
850 const nsACString& aType);
852 // Returns true if aDoc1 and aDoc2 have equal NodePrincipal()s.
853 static bool HaveEqualPrincipals(Document* aDoc1, Document* aDoc2);
855 static mozilla::intl::LineBreaker* LineBreaker() {
856 return sLineBreaker.get();
859 static mozilla::intl::WordBreaker* WordBreaker() {
860 return sWordBreaker.get();
864 * Regster aObserver as a shutdown observer. A strong reference is held
865 * to aObserver until UnregisterShutdownObserver is called.
867 static void RegisterShutdownObserver(nsIObserver* aObserver);
868 static void UnregisterShutdownObserver(nsIObserver* aObserver);
871 * @return true if aContent has an attribute aName in namespace aNameSpaceID,
872 * and the attribute value is non-empty.
874 static bool HasNonEmptyAttr(const nsIContent* aContent, int32_t aNameSpaceID,
875 nsAtom* aName);
878 * Method that gets the primary presContext for the node.
880 * @param aContent The content node.
881 * @return the presContext, or nullptr if the content is not in a document
882 * (if GetComposedDoc returns nullptr)
884 static nsPresContext* GetContextForContent(const nsIContent* aContent);
887 * Method that gets the pres shell for the node.
889 * @param aContent The content node.
890 * @return the pres shell, or nullptr if the content is not in a document
891 * (if GetComposedDoc returns nullptr)
893 static mozilla::PresShell* GetPresShellForContent(const nsIContent* aContent);
896 * Method to do security and content policy checks on the image URI
898 * @param aURI uri of the image to be loaded
899 * @param aNode, the context the image is loaded in (eg an element)
900 * @param aLoadingDocument the document we belong to
901 * @param aLoadingPrincipal the principal doing the load
902 * @param [aContentPolicyType=nsIContentPolicy::TYPE_INTERNAL_IMAGE]
903 * (Optional) The CP content type to use
904 * @param aImageBlockingStatus the nsIContentPolicy blocking status for this
905 * image. This will be set even if a security check fails for the
906 * image, to some reasonable REJECT_* value. This out param will only
907 * be set if it's non-null.
908 * @return true if the load can proceed, or false if it is blocked.
909 * Note that aImageBlockingStatus, if set will always be an ACCEPT
910 * status if true is returned and always be a REJECT_* status if
911 * false is returned.
913 static bool CanLoadImage(nsIURI* aURI, nsINode* aNode,
914 Document* aLoadingDocument,
915 nsIPrincipal* aLoadingPrincipal);
918 * Returns true if objects in aDocument shouldn't initiate image loads.
920 static bool DocumentInactiveForImageLoads(Document* aDocument);
923 * Convert a CORSMode into the corresponding imgILoader flags for
924 * passing to LoadImage.
925 * @param aMode CORS mode to convert
926 * @return a bitfield suitable to bitwise OR with other nsIRequest flags
928 static int32_t CORSModeToLoadImageFlags(mozilla::CORSMode aMode);
931 * Method to start an image load. This does not do any security checks.
932 * This method will attempt to make aURI immutable; a caller that wants to
933 * keep a mutable version around should pass in a clone.
935 * @param aURI uri of the image to be loaded
936 * @param aContext element of document where the result of this request
937 * will be used.
938 * @param aLoadingDocument the document we belong to
939 * @param aLoadingPrincipal the principal doing the load
940 * @param aReferrerInfo the referrerInfo use on channel creation
941 * @param aObserver the observer for the image load
942 * @param aLoadFlags the load flags to use. See nsIRequest
943 * @param [aContentPolicyType=nsIContentPolicy::TYPE_INTERNAL_IMAGE]
944 * (Optional) The CP content type to use
945 * @param aUseUrgentStartForChannel,(Optional) a flag to mark on channel if it
946 * is triggered by user input events.
947 * @return the imgIRequest for the image load
949 static nsresult LoadImage(
950 nsIURI* aURI, nsINode* aContext, Document* aLoadingDocument,
951 nsIPrincipal* aLoadingPrincipal, uint64_t aRequestContextID,
952 nsIReferrerInfo* aReferrerInfo, imgINotificationObserver* aObserver,
953 int32_t aLoadFlags, const nsAString& initiatorType,
954 imgRequestProxy** aRequest,
955 nsContentPolicyType aContentPolicyType =
956 nsIContentPolicy::TYPE_INTERNAL_IMAGE,
957 bool aUseUrgentStartForChannel = false, bool aLinkPreload = false);
960 * Obtain an image loader that respects the given document/channel's privacy
961 * status. Null document/channel arguments return the public image loader.
963 static imgLoader* GetImgLoaderForDocument(Document* aDoc);
964 static imgLoader* GetImgLoaderForChannel(nsIChannel* aChannel,
965 Document* aContext);
968 * Returns whether the given URI is in the image cache.
970 static bool IsImageInCache(nsIURI* aURI, Document* aDocument);
973 * Method to get an imgIContainer from an image loading content
975 * @param aContent The image loading content. Must not be null.
976 * @param aRequest The image request [out]
977 * @return the imgIContainer corresponding to the first frame of the image
979 static already_AddRefed<imgIContainer> GetImageFromContent(
980 nsIImageLoadingContent* aContent, imgIRequest** aRequest = nullptr);
983 * Method that decides whether a content node is draggable
985 * @param aContent The content node to test.
986 * @return whether it's draggable
988 static bool ContentIsDraggable(nsIContent* aContent);
991 * Method that decides whether a content node is a draggable image
993 * @param aContent The content node to test.
994 * @return whether it's a draggable image
996 static bool IsDraggableImage(nsIContent* aContent);
999 * Method that decides whether a content node is a draggable link
1001 * @param aContent The content node to test.
1002 * @return whether it's a draggable link
1004 static bool IsDraggableLink(const nsIContent* aContent);
1007 * Convenience method to create a new nodeinfo that differs only by prefix and
1008 * name from aNodeInfo. The new nodeinfo's name is set to aName, and prefix is
1009 * set to null.
1011 static nsresult QNameChanged(mozilla::dom::NodeInfo* aNodeInfo, nsAtom* aName,
1012 mozilla::dom::NodeInfo** aResult);
1015 * Returns the appropriate event argument names for the specified
1016 * namespace and event name. Added because we need to switch between
1017 * SVG's "evt" and the rest of the world's "event", and because onerror
1018 * on window takes 5 args.
1020 static void GetEventArgNames(int32_t aNameSpaceID, nsAtom* aEventName,
1021 bool aIsForWindow, uint32_t* aArgCount,
1022 const char*** aArgNames);
1025 * Returns true if this document is in a Private Browsing window.
1027 static bool IsInPrivateBrowsing(Document* aDoc);
1030 * Returns true if this loadGroup uses Private Browsing.
1032 static bool IsInPrivateBrowsing(nsILoadGroup* aLoadGroup);
1035 * If aNode is not an element, return true exactly when aContent's binding
1036 * parent is null.
1038 * If aNode is an element, return true exactly when aContent's binding parent
1039 * is the same as aNode's.
1041 * This method is particularly useful for callers who are trying to ensure
1042 * that they are working with a non-anonymous descendant of a given node. If
1043 * aContent is a descendant of aNode, a return value of false from this
1044 * method means that it's an anonymous descendant from aNode's point of view.
1046 * Both arguments to this method must be non-null.
1048 static bool IsInSameAnonymousTree(const nsINode* aNode,
1049 const nsIContent* aContent);
1052 * Traverse the parent chain from aElement up to aStop, and return true if
1053 * there's an interactive html content; false otherwise.
1055 * Note: This crosses shadow boundaries but not document boundaries.
1057 static bool IsInInteractiveHTMLContent(const Element* aElement,
1058 const Element* aStop);
1061 * Return the nsIXPConnect service.
1063 static nsIXPConnect* XPConnect() { return sXPConnect; }
1066 * Report simple error message to the browser console
1067 * @param aErrorText the error message
1068 * @param aCategory Name of the module reporting error
1069 * @param aFromPrivateWindow Whether from private window or not
1070 * @param aFromChromeContext Whether from chrome context or not
1071 * @param [aErrorFlags] See nsIScriptError.
1073 static void LogSimpleConsoleError(
1074 const nsAString& aErrorText, const char* aCategory,
1075 bool aFromPrivateWindow, bool aFromChromeContext,
1076 uint32_t aErrorFlags = nsIScriptError::errorFlag);
1079 * Report a non-localized error message to the error console.
1080 * @param aErrorText the error message
1081 * @param aErrorFlags See nsIScriptError.
1082 * @param aCategory Name of module reporting error.
1083 * @param aDocument Reference to the document which triggered the message.
1084 * @param [aURI=nullptr] (Optional) URI of resource containing error.
1085 * @param [aSourceLine=u""_ns] (Optional) The text of the line that
1086 contains the error (may be empty).
1087 * @param [aLineNumber=0] (Optional) Line number within resource
1088 containing error.
1089 * @param [aColumnNumber=0] (Optional) Column number within resource
1090 containing error.
1091 If aURI is null, then aDocument->GetDocumentURI() is used.
1092 * @param [aLocationMode] (Optional) Specifies the behavior if
1093 error location information is omitted.
1095 enum MissingErrorLocationMode {
1096 // Don't show location information in the error console.
1097 eOMIT_LOCATION,
1098 // Get location information from the currently executing script.
1099 eUSE_CALLING_LOCATION
1101 static nsresult ReportToConsoleNonLocalized(
1102 const nsAString& aErrorText, uint32_t aErrorFlags,
1103 const nsACString& aCategory, const Document* aDocument,
1104 nsIURI* aURI = nullptr, const nsString& aSourceLine = u""_ns,
1105 uint32_t aLineNumber = 0, uint32_t aColumnNumber = 0,
1106 MissingErrorLocationMode aLocationMode = eUSE_CALLING_LOCATION);
1109 * Report a non-localized error message to the error console base on the
1110 * innerWindowID.
1111 * @param aErrorText the error message
1112 * @param aErrorFlags See nsIScriptError.
1113 * @param aCategory Name of module reporting error.
1114 * @param [aInnerWindowID] Inner window ID for document which triggered the
1115 * message.
1116 * @param [aURI=nullptr] (Optional) URI of resource containing error.
1117 * @param [aSourceLine=u""_ns] (Optional) The text of the line that
1118 contains the error (may be empty).
1119 * @param [aLineNumber=0] (Optional) Line number within resource
1120 containing error.
1121 * @param [aColumnNumber=0] (Optional) Column number within resource
1122 containing error.
1123 If aURI is null, then aDocument->GetDocumentURI() is used.
1124 * @param [aLocationMode] (Optional) Specifies the behavior if
1125 error location information is omitted.
1127 static nsresult ReportToConsoleByWindowID(
1128 const nsAString& aErrorText, uint32_t aErrorFlags,
1129 const nsACString& aCategory, uint64_t aInnerWindowID,
1130 nsIURI* aURI = nullptr, const nsString& aSourceLine = u""_ns,
1131 uint32_t aLineNumber = 0, uint32_t aColumnNumber = 0,
1132 MissingErrorLocationMode aLocationMode = eUSE_CALLING_LOCATION);
1135 * Report a localized error message to the error console.
1136 * @param aErrorFlags See nsIScriptError.
1137 * @param aCategory Name of module reporting error.
1138 * @param aDocument Reference to the document which triggered the message.
1139 * @param aFile Properties file containing localized message.
1140 * @param aMessageName Name of localized message.
1141 * @param [aParams=empty-array] (Optional) Parameters to be substituted into
1142 localized message.
1143 * @param [aURI=nullptr] (Optional) URI of resource containing error.
1144 * @param [aSourceLine=u""_ns] (Optional) The text of the line that
1145 contains the error (may be empty).
1146 * @param [aLineNumber=0] (Optional) Line number within resource
1147 containing error.
1148 * @param [aColumnNumber=0] (Optional) Column number within resource
1149 containing error.
1150 If aURI is null, then aDocument->GetDocumentURI() is used.
1152 enum PropertiesFile {
1153 eCSS_PROPERTIES,
1154 eXUL_PROPERTIES,
1155 eLAYOUT_PROPERTIES,
1156 eFORMS_PROPERTIES,
1157 ePRINTING_PROPERTIES,
1158 eDOM_PROPERTIES,
1159 eHTMLPARSER_PROPERTIES,
1160 eSVG_PROPERTIES,
1161 eBRAND_PROPERTIES,
1162 eCOMMON_DIALOG_PROPERTIES,
1163 eMATHML_PROPERTIES,
1164 eSECURITY_PROPERTIES,
1165 eNECKO_PROPERTIES,
1166 eFORMS_PROPERTIES_en_US,
1167 eDOM_PROPERTIES_en_US,
1168 PropertiesFile_COUNT
1170 static nsresult ReportToConsole(
1171 uint32_t aErrorFlags, const nsACString& aCategory,
1172 const Document* aDocument, PropertiesFile aFile, const char* aMessageName,
1173 const nsTArray<nsString>& aParams = nsTArray<nsString>(),
1174 nsIURI* aURI = nullptr, const nsString& aSourceLine = u""_ns,
1175 uint32_t aLineNumber = 0, uint32_t aColumnNumber = 0);
1177 static void ReportEmptyGetElementByIdArg(const Document* aDoc);
1179 static void LogMessageToConsole(const char* aMsg);
1181 static bool SpoofLocaleEnglish();
1184 * Get the localized string named |aKey| in properties file |aFile|.
1186 static nsresult GetLocalizedString(PropertiesFile aFile, const char* aKey,
1187 nsAString& aResult);
1190 * Same as GetLocalizedString, except that it might use en-US locale depending
1191 * on SpoofLocaleEnglish() and whether the document is a built-in browser
1192 * page.
1194 static nsresult GetMaybeLocalizedString(PropertiesFile aFile,
1195 const char* aKey, Document* aDocument,
1196 nsAString& aResult);
1199 * A helper function that parses a sandbox attribute (of an <iframe> or a CSP
1200 * directive) and converts it to the set of flags used internally.
1202 * @param aSandboxAttr the sandbox attribute
1203 * @return the set of flags (SANDBOXED_NONE if aSandboxAttr is
1204 * null)
1206 static uint32_t ParseSandboxAttributeToFlags(const nsAttrValue* aSandboxAttr);
1209 * A helper function that checks if a string matches a valid sandbox flag.
1211 * @param aFlag the potential sandbox flag.
1212 * @return true if the flag is a sandbox flag.
1214 static bool IsValidSandboxFlag(const nsAString& aFlag);
1217 * A helper function that returns a string attribute corresponding to the
1218 * sandbox flags.
1220 * @param aFlags the sandbox flags
1221 * @param aString the attribute corresponding to the flags (null if aFlags
1222 * is zero)
1224 static void SandboxFlagsToString(uint32_t aFlags, nsAString& aString);
1227 * Helper function that generates a UUID.
1229 static nsresult GenerateUUIDInPlace(nsID& aUUID);
1232 * Infallable (with an assertion) helper function that generates a UUID.
1234 static nsID GenerateUUID();
1236 static bool PrefetchPreloadEnabled(nsIDocShell* aDocShell);
1238 static void ExtractErrorValues(JSContext* aCx, JS::Handle<JS::Value> aValue,
1239 nsAString& aSourceSpecOut, uint32_t* aLineOut,
1240 uint32_t* aColumnOut, nsString& aMessageOut);
1242 // Variant on `ExtractErrorValues` with a `nsACString`. This
1243 // method is provided for backwards compatibility. Prefer the
1244 // faster method above for your code.
1245 static void ExtractErrorValues(JSContext* aCx, JS::Handle<JS::Value> aValue,
1246 nsACString& aSourceSpecOut, uint32_t* aLineOut,
1247 uint32_t* aColumnOut, nsString& aMessageOut);
1249 static nsresult CalculateBufferSizeForImage(
1250 const uint32_t& aStride, const mozilla::gfx::IntSize& aImageSize,
1251 const mozilla::gfx::SurfaceFormat& aFormat, size_t* aMaxBufferSize,
1252 size_t* aUsedBufferSize);
1254 // Returns true if the URI's host is contained in a list which is a comma
1255 // separated domain list. Each item may start with "*.". If starts with
1256 // "*.", it matches any sub-domains.
1257 // The aList argument must be a lower-case string.
1258 static bool IsURIInList(nsIURI* aURI, const nsCString& aList);
1260 // Returns true if the URI's host is contained in a pref list which is a comma
1261 // separated domain list. Each item may start with "*.". If starts with
1262 // "*.", it matches any sub-domains.
1263 static bool IsURIInPrefList(nsIURI* aURI, const char* aPrefName);
1266 * A convenience version of FormatLocalizedString that can be used if all the
1267 * params are in same-typed strings. The variadic template args need to come
1268 * at the end, so we put aResult at the beginning to make sure it's clear
1269 * which is the output and which are the inputs.
1271 template <typename... T>
1272 static nsresult FormatLocalizedString(nsAString& aResult,
1273 PropertiesFile aFile, const char* aKey,
1274 const T&... aParams) {
1275 static_assert(sizeof...(aParams) != 0, "Use GetLocalizedString()");
1276 AutoTArray<nsString, sizeof...(aParams)> params = {
1277 aParams...,
1279 return FormatLocalizedString(aFile, aKey, params, aResult);
1283 * Same as FormatLocalizedString template version, except that it might use
1284 * en-US locale depending on SpoofLocaleEnglish() and whether the document is
1285 * a built-in browser page.
1287 template <typename... T>
1288 static nsresult FormatMaybeLocalizedString(nsAString& aResult,
1289 PropertiesFile aFile,
1290 const char* aKey,
1291 Document* aDocument,
1292 const T&... aParams) {
1293 static_assert(sizeof...(aParams) != 0, "Use GetMaybeLocalizedString()");
1294 AutoTArray<nsString, sizeof...(aParams)> params = {
1295 aParams...,
1297 return FormatMaybeLocalizedString(aFile, aKey, aDocument, params, aResult);
1301 * Fill (with the parameters given) the localized string named |aKey| in
1302 * properties file |aFile| consuming an nsTArray of nsString parameters rather
1303 * than a char16_t** for the sake of avoiding use-after-free errors involving
1304 * temporaries.
1306 static nsresult FormatLocalizedString(PropertiesFile aFile, const char* aKey,
1307 const nsTArray<nsString>& aParamArray,
1308 nsAString& aResult);
1311 * Same as FormatLocalizedString, except that it might use en-US locale
1312 * depending on SpoofLocaleEnglish() and whether the document is a built-in
1313 * browser page.
1315 static nsresult FormatMaybeLocalizedString(
1316 PropertiesFile aFile, const char* aKey, Document* aDocument,
1317 const nsTArray<nsString>& aParamArray, nsAString& aResult);
1320 * Returns true if aDocument is a chrome document
1322 static bool IsChromeDoc(const Document* aDocument);
1325 * Returns true if aDocument is in a docshell whose parent is the same type
1327 static bool IsChildOfSameType(Document* aDoc);
1330 * Returns true if the content-type will be rendered as plain-text.
1332 static bool IsPlainTextType(const nsACString& aContentType);
1335 * Returns true iff the type is rendered as plain text and doesn't support
1336 * non-UTF-8 encodings.
1338 static bool IsUtf8OnlyPlainTextType(const nsACString& aContentType);
1341 * Returns true if aDocument belongs to a chrome docshell for
1342 * display purposes. Returns false for null documents or documents
1343 * which do not belong to a docshell.
1345 static bool IsInChromeDocshell(const Document* aDocument);
1348 * Return the content policy service
1350 static nsIContentPolicy* GetContentPolicy();
1353 * Map internal content policy types to external ones.
1355 static inline ExtContentPolicyType InternalContentPolicyTypeToExternal(
1356 nsContentPolicyType aType);
1359 * Returns true if the content policy type is any of:
1360 * * TYPE_INTERNAL_SCRIPT_PRELOAD
1361 * * TYPE_INTERNAL_IMAGE_PRELOAD
1362 * * TYPE_INTERNAL_STYLESHEET_PRELOAD
1364 static bool IsPreloadType(nsContentPolicyType aType);
1367 * Returns true if the pref "security.mixed_content.upgrade_display_content"
1368 * is true and the content policy type is any of:
1369 * * TYPE_IMAGE
1370 * * TYPE_MEDIA
1372 static bool IsUpgradableDisplayType(ExtContentPolicyType aType);
1375 * Quick helper to determine whether there are any mutation listeners
1376 * of a given type that apply to this content or any of its ancestors.
1377 * The method has the side effect to call document's MayDispatchMutationEvent
1378 * using aTargetForSubtreeModified as the parameter.
1380 * @param aNode The node to search for listeners
1381 * @param aType The type of listener (NS_EVENT_BITS_MUTATION_*)
1382 * @param aTargetForSubtreeModified The node which is the target of the
1383 * possible DOMSubtreeModified event.
1385 * @return true if there are mutation listeners of the specified type
1387 static bool HasMutationListeners(nsINode* aNode, uint32_t aType,
1388 nsINode* aTargetForSubtreeModified);
1391 * Quick helper to determine whether there are any mutation listeners
1392 * of a given type that apply to any content in this document. It is valid
1393 * to pass null for aDocument here, in which case this function always
1394 * returns true.
1396 * @param aDocument The document to search for listeners
1397 * @param aType The type of listener (NS_EVENT_BITS_MUTATION_*)
1399 * @return true if there are mutation listeners of the specified type
1401 static bool HasMutationListeners(Document* aDocument, uint32_t aType);
1403 * Synchronously fire DOMNodeRemoved on aChild. Only fires the event if
1404 * there really are listeners by checking using the HasMutationListeners
1405 * function above. The function makes sure to hold the relevant objects alive
1406 * for the duration of the event firing. However there are no guarantees
1407 * that any of the objects are alive by the time the function returns.
1408 * If you depend on that you need to hold references yourself.
1410 * @param aChild The node to fire DOMNodeRemoved at.
1411 * @param aParent The parent of aChild.
1413 static void MaybeFireNodeRemoved(nsINode* aChild, nsINode* aParent);
1416 * These methods create and dispatch a trusted event.
1417 * Works only with events which can be created by calling
1418 * Document::CreateEvent() with parameter "Events".
1419 * Note that don't use these methods for "input" event. Use
1420 * DispatchInputEvent() instead.
1422 * @param aDoc The document which will be used to create the event.
1423 * @param aTarget The target of the event, should be QIable to
1424 * EventTarget.
1425 * @param aEventName The name of the event.
1426 * @param aCanBubble Whether the event can bubble.
1427 * @param aCancelable Is the event cancelable.
1428 * @param aCopmosed Is the event composed.
1429 * @param aDefaultAction Set to true if default action should be taken,
1430 * see EventTarget::DispatchEvent.
1432 // TODO: annotate with `MOZ_CAN_RUN_SCRIPT`
1433 // (https://bugzilla.mozilla.org/show_bug.cgi?id=1625902).
1434 static nsresult DispatchTrustedEvent(Document* aDoc, nsISupports* aTarget,
1435 const nsAString& aEventName, CanBubble,
1436 Cancelable,
1437 Composed aComposed = Composed::eDefault,
1438 bool* aDefaultAction = nullptr);
1440 // TODO: annotate with `MOZ_CAN_RUN_SCRIPT`
1441 // (https://bugzilla.mozilla.org/show_bug.cgi?id=1625902).
1442 static nsresult DispatchTrustedEvent(Document* aDoc, nsISupports* aTarget,
1443 const nsAString& aEventName,
1444 CanBubble aCanBubble,
1445 Cancelable aCancelable,
1446 bool* aDefaultAction) {
1447 return DispatchTrustedEvent(aDoc, aTarget, aEventName, aCanBubble,
1448 aCancelable, Composed::eDefault,
1449 aDefaultAction);
1453 * This method creates and dispatches a trusted event using an event message.
1454 * @param aDoc The document which will be used to create the event.
1455 * @param aTarget The target of the event, should be QIable to
1456 * EventTarget.
1457 * @param aEventMessage The event message.
1458 * @param aCanBubble Whether the event can bubble.
1459 * @param aCancelable Is the event cancelable.
1460 * @param aDefaultAction Set to true if default action should be taken,
1461 * see EventTarget::DispatchEvent.
1463 template <class WidgetEventType>
1464 static nsresult DispatchTrustedEvent(
1465 Document* aDoc, nsISupports* aTarget, EventMessage aEventMessage,
1466 CanBubble aCanBubble, Cancelable aCancelable,
1467 bool* aDefaultAction = nullptr,
1468 ChromeOnlyDispatch aOnlyChromeDispatch = ChromeOnlyDispatch::eNo) {
1469 WidgetEventType event(true, aEventMessage);
1470 MOZ_ASSERT(GetEventClassIDFromMessage(aEventMessage) == event.mClass);
1471 return DispatchEvent(aDoc, aTarget, event, aEventMessage, aCanBubble,
1472 aCancelable, Trusted::eYes, aDefaultAction,
1473 aOnlyChromeDispatch);
1477 * This method dispatches "beforeinput" event with EditorInputEvent or
1478 * "input" event with proper event class. If it's unsafe to dispatch,
1479 * this put the event into the script runner queue. In such case, the
1480 * event becomes not cancelable even if it's defined as cancelable by
1481 * the spec.
1482 * Input Events spec defines as:
1483 * Input events are dispatched on elements that act as editing hosts,
1484 * including elements with the contenteditable attribute set, textarea
1485 * elements, and input elements that permit text input.
1487 * @param aEventTarget The event target element of the "beforeinput"
1488 * or "input" event. Must not be nullptr.
1489 * @param aEventMessage Muse be eEditorBeforeInput or eEditorInput.
1490 * @param aEditorInputType The inputType value of InputEvent.
1491 * If aEventTarget won't dispatch "input" event
1492 * with InputEvent, set EditorInputType::eUnknown.
1493 * @param aTextEditor Optional. If this is called by editor,
1494 * editor should set this. Otherwise, leave
1495 * nullptr.
1496 * @param aOptions Optional. If aEditorInputType value requires
1497 * some additional data, they should be properly
1498 * set with this argument.
1499 * @param aEventStatus Returns nsEventStatus_eConsumeNoDefault if
1500 * the dispatching event is cancelable and the
1501 * event was canceled by script (including
1502 * chrome script). Otherwise, returns given
1503 * value. Note that this can be nullptr only
1504 * when the dispatching event is not cancelable.
1506 MOZ_CAN_RUN_SCRIPT static nsresult DispatchInputEvent(Element* aEventTarget);
1507 MOZ_CAN_RUN_SCRIPT static nsresult DispatchInputEvent(
1508 Element* aEventTarget, mozilla::EventMessage aEventMessage,
1509 mozilla::EditorInputType aEditorInputType,
1510 mozilla::TextEditor* aTextEditor, mozilla::InputEventOptions&& aOptions,
1511 nsEventStatus* aEventStatus = nullptr);
1514 * This method creates and dispatches a untrusted event.
1515 * Works only with events which can be created by calling
1516 * Document::CreateEvent() with parameter "Events".
1517 * @param aDoc The document which will be used to create the event.
1518 * @param aTarget The target of the event, should be QIable to
1519 * EventTarget.
1520 * @param aEventName The name of the event.
1521 * @param aCanBubble Whether the event can bubble.
1522 * @param aCancelable Is the event cancelable.
1523 * @param aDefaultAction Set to true if default action should be taken,
1524 * see EventTarget::DispatchEvent.
1526 static nsresult DispatchUntrustedEvent(Document* aDoc, nsISupports* aTarget,
1527 const nsAString& aEventName, CanBubble,
1528 Cancelable,
1529 bool* aDefaultAction = nullptr);
1532 * This method creates and dispatches a untrusted event using an event
1533 * message.
1534 * @param aDoc The document which will be used to create the event.
1535 * @param aTarget The target of the event, should be QIable to
1536 * EventTarget.
1537 * @param aEventMessage The event message.
1538 * @param aCanBubble Whether the event can bubble.
1539 * @param aCancelable Is the event cancelable.
1540 * @param aDefaultAction Set to true if default action should be taken,
1541 * see EventTarget::DispatchEvent.
1543 template <class WidgetEventType>
1544 static nsresult DispatchUntrustedEvent(
1545 Document* aDoc, nsISupports* aTarget, EventMessage aEventMessage,
1546 CanBubble aCanBubble, Cancelable aCancelable,
1547 bool* aDefaultAction = nullptr,
1548 ChromeOnlyDispatch aOnlyChromeDispatch = ChromeOnlyDispatch::eNo) {
1549 WidgetEventType event(false, aEventMessage);
1550 MOZ_ASSERT(GetEventClassIDFromMessage(aEventMessage) == event.mClass);
1551 return DispatchEvent(aDoc, aTarget, event, aEventMessage, aCanBubble,
1552 aCancelable, Trusted::eNo, aDefaultAction,
1553 aOnlyChromeDispatch);
1557 * This method creates and dispatches a trusted event to the chrome
1558 * event handler (the parent object of the DOM Window in the event target
1559 * chain). Note, chrome event handler is used even if aTarget is a chrome
1560 * object. Use DispatchEventOnlyToChrome if the normal event dispatching is
1561 * wanted in case aTarget is a chrome object.
1562 * Works only with events which can be created by calling
1563 * Document::CreateEvent() with parameter "Events".
1564 * @param aDocument The document which will be used to create the event,
1565 * and whose window's chrome handler will be used to
1566 * dispatch the event.
1567 * @param aTarget The target of the event, used for event->SetTarget()
1568 * @param aEventName The name of the event.
1569 * @param aCanBubble Whether the event can bubble.
1570 * @param aCancelable Is the event cancelable.
1571 * @param aDefaultAction Set to true if default action should be taken,
1572 * see EventTarget::DispatchEvent.
1574 static nsresult DispatchChromeEvent(Document* aDoc, nsISupports* aTarget,
1575 const nsAString& aEventName, CanBubble,
1576 Cancelable,
1577 bool* aDefaultAction = nullptr);
1580 * Helper to dispatch a "framefocusrequested" event to chrome, which will only
1581 * bring the window to the foreground and switch tabs if aCanRaise is true.
1583 MOZ_CAN_RUN_SCRIPT_BOUNDARY static void RequestFrameFocus(
1584 Element& aFrameElement, bool aCanRaise,
1585 mozilla::dom::CallerType aCallerType);
1588 * This method creates and dispatches a trusted event.
1589 * If aTarget is not a chrome object, the nearest chrome object in the
1590 * propagation path will be used as the start of the event target chain.
1591 * This method is different than DispatchChromeEvent, which always dispatches
1592 * events to chrome event handler. DispatchEventOnlyToChrome works like
1593 * DispatchTrustedEvent in the case aTarget is a chrome object.
1594 * Works only with events which can be created by calling
1595 * Document::CreateEvent() with parameter "Events".
1596 * @param aDoc The document which will be used to create the event.
1597 * @param aTarget The target of the event, should be QIable to
1598 * EventTarget.
1599 * @param aEventName The name of the event.
1600 * @param aCanBubble Whether the event can bubble.
1601 * @param aCancelable Is the event cancelable.
1602 * @param aComposed Is the event composed.
1603 * @param aDefaultAction Set to true if default action should be taken,
1604 * see EventTarget::DispatchEvent.
1606 static nsresult DispatchEventOnlyToChrome(
1607 Document* aDoc, nsISupports* aTarget, const nsAString& aEventName,
1608 CanBubble, Cancelable, Composed aComposed = Composed::eDefault,
1609 bool* aDefaultAction = nullptr);
1611 static nsresult DispatchEventOnlyToChrome(
1612 Document* aDoc, nsISupports* aTarget, const nsAString& aEventName,
1613 CanBubble aCanBubble, Cancelable aCancelable, bool* aDefaultAction) {
1614 return DispatchEventOnlyToChrome(aDoc, aTarget, aEventName, aCanBubble,
1615 aCancelable, Composed::eDefault,
1616 aDefaultAction);
1620 * Determines if an event attribute name (such as onclick) is valid for
1621 * a given element type. Types are from the EventNameType enumeration
1622 * defined above.
1624 * @param aName the event name to look up
1625 * @param aType the type of content
1627 static bool IsEventAttributeName(nsAtom* aName, int32_t aType);
1630 * Return the event message for the event with the given name. The name is
1631 * the event name with the 'on' prefix. Returns eUnidentifiedEvent if the
1632 * event doesn't match a known event name.
1634 * @param aName the event name to look up
1636 static EventMessage GetEventMessage(nsAtom* aName);
1639 * Returns the EventMessage and nsAtom to be used for event listener
1640 * registration.
1642 static EventMessage GetEventMessageAndAtomForListener(const nsAString& aName,
1643 nsAtom** aOnName);
1646 * Return the EventClassID for the event with the given name. The name is the
1647 * event name *without* the 'on' prefix. Returns eBasicEventClass if the event
1648 * is not known to be of any particular event class.
1650 * @param aName the event name to look up
1652 static mozilla::EventClassID GetEventClassID(const nsAString& aName);
1655 * Return the event message and atom for the event with the given name.
1656 * The name is the event name *without* the 'on' prefix.
1657 * Returns eUnidentifiedEvent on the aEventID if the
1658 * event doesn't match a known event name in the category.
1660 * @param aName the event name to look up
1661 * @param aEventClassID only return event id for aEventClassID
1663 static nsAtom* GetEventMessageAndAtom(const nsAString& aName,
1664 mozilla::EventClassID aEventClassID,
1665 EventMessage* aEventMessage);
1668 * Used only during traversal of the XPCOM graph by the cycle
1669 * collector: push a pointer to the listener manager onto the
1670 * children deque, if it exists. Do nothing if there is no listener
1671 * manager.
1673 * Crucially: does not perform any refcounting operations.
1675 * @param aNode The node to traverse.
1676 * @param children The buffer to push a listener manager pointer into.
1678 static void TraverseListenerManager(nsINode* aNode,
1679 nsCycleCollectionTraversalCallback& cb);
1682 * Get the eventlistener manager for aNode, creating it if it does not
1683 * already exist.
1685 * @param aNode The node for which to get the eventlistener manager.
1687 static mozilla::EventListenerManager* GetListenerManagerForNode(
1688 nsINode* aNode);
1690 * Get the eventlistener manager for aNode, returning null if it does not
1691 * already exist.
1693 * @param aNode The node for which to get the eventlistener manager.
1695 static mozilla::EventListenerManager* GetExistingListenerManagerForNode(
1696 const nsINode* aNode);
1698 static void AddEntryToDOMArenaTable(nsINode* aNode,
1699 mozilla::dom::DOMArena* aDOMArena);
1701 static already_AddRefed<mozilla::dom::DOMArena> TakeEntryFromDOMArenaTable(
1702 const nsINode* aNode);
1704 static void UnmarkGrayJSListenersInCCGenerationDocuments();
1707 * Remove the eventlistener manager for aNode.
1709 * @param aNode The node for which to remove the eventlistener manager.
1711 static void RemoveListenerManager(nsINode* aNode);
1713 static bool IsInitialized() { return sInitialized; }
1716 * Checks if the localname/prefix/namespace triple is valid wrt prefix
1717 * and namespace according to the Namespaces in XML and DOM Code
1718 * specfications.
1720 * @param aLocalname localname of the node
1721 * @param aPrefix prefix of the node
1722 * @param aNamespaceID namespace of the node
1724 static bool IsValidNodeName(nsAtom* aLocalName, nsAtom* aPrefix,
1725 int32_t aNamespaceID);
1728 * Creates a DocumentFragment from text using a context node to resolve
1729 * namespaces.
1731 * Please note that for safety reasons, if the node principal of
1732 * aContextNode is the system principal, this function will automatically
1733 * sanitize its input using nsTreeSanitizer.
1735 * Note! In the HTML case with the HTML5 parser enabled, this is only called
1736 * from Range.createContextualFragment() and the implementation here is
1737 * quirky accordingly (html context node behaves like a body context node).
1738 * If you don't want that quirky behavior, don't use this method as-is!
1740 * @param aContextNode the node which is used to resolve namespaces
1741 * @param aFragment the string which is parsed to a DocumentFragment
1742 * @param aReturn the resulting fragment
1743 * @param aPreventScriptExecution whether to mark scripts as already started
1745 static already_AddRefed<mozilla::dom::DocumentFragment>
1746 CreateContextualFragment(nsINode* aContextNode, const nsAString& aFragment,
1747 bool aPreventScriptExecution,
1748 mozilla::ErrorResult& aRv);
1751 * Invoke the fragment parsing algorithm (innerHTML) using the HTML parser.
1753 * Please note that for safety reasons, if the node principal of aTargetNode
1754 * is the system principal, this function will automatically sanitize its
1755 * input using nsTreeSanitizer.
1757 * @param aSourceBuffer the string being set as innerHTML
1758 * @param aTargetNode the target container
1759 * @param aContextLocalName local name of context node
1760 * @param aContextNamespace namespace of context node
1761 * @param aQuirks true to make <table> not close <p>
1762 * @param aPreventScriptExecution true to prevent scripts from executing;
1763 * don't set to false when parsing into a target node that has been
1764 * bound to tree.
1765 * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1766 * fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
1767 * long and NS_OK otherwise.
1768 * @param aFlags defaults to -1 indicating that ParseFragmentHTML will do
1769 * default sanitization for system privileged calls to it. Only
1770 * ParserUtils::ParseFragment() should ever pass explicit aFlags
1771 * which will then used for sanitization of the fragment.
1772 * To pass explicit aFlags use any of the sanitization flags
1773 * listed in nsIParserUtils.idl.
1775 static nsresult ParseFragmentHTML(const nsAString& aSourceBuffer,
1776 nsIContent* aTargetNode,
1777 nsAtom* aContextLocalName,
1778 int32_t aContextNamespace, bool aQuirks,
1779 bool aPreventScriptExecution,
1780 int32_t aFlags = -1);
1783 * Invoke the fragment parsing algorithm (innerHTML) using the XML parser.
1785 * Please note that for safety reasons, if the node principal of aDocument
1786 * is the system principal, this function will automatically sanitize its
1787 * input using nsTreeSanitizer.
1789 * @param aSourceBuffer the string being set as innerHTML
1790 * @param aDocument the target document
1791 * @param aTagStack the namespace mapping context
1792 * @param aPreventExecution whether to mark scripts as already started
1793 * @param aFlags, pass -1 and ParseFragmentXML will do default
1794 * sanitization for system privileged calls to it. Only
1795 * ParserUtils::ParseFragment() should ever pass explicit aFlags
1796 * which will then used for sanitization of the fragment.
1797 * To pass explicit aFlags use any of the sanitization flags
1798 * listed in nsIParserUtils.idl.
1799 * @param aReturn the result fragment
1800 * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1801 * fragments is made, a return code from the XML parser.
1803 static nsresult ParseFragmentXML(const nsAString& aSourceBuffer,
1804 Document* aDocument,
1805 nsTArray<nsString>& aTagStack,
1806 bool aPreventScriptExecution, int32_t aFlags,
1807 mozilla::dom::DocumentFragment** aReturn);
1810 * Parse a string into a document using the HTML parser.
1811 * Script elements are marked unexecutable.
1813 * @param aSourceBuffer the string to parse as an HTML document
1814 * @param aTargetDocument the document object to parse into. Must not have
1815 * child nodes.
1816 * @param aScriptingEnabledForNoscriptParsing whether <noscript> is parsed
1817 * as if scripting was enabled
1818 * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1819 * fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
1820 * long and NS_OK otherwise.
1822 static nsresult ParseDocumentHTML(const nsAString& aSourceBuffer,
1823 Document* aTargetDocument,
1824 bool aScriptingEnabledForNoscriptParsing);
1827 * Converts HTML source to plain text by parsing the source and using the
1828 * plain text serializer on the resulting tree.
1830 * @param aSourceBuffer the string to parse as an HTML document
1831 * @param aResultBuffer the string where the plain text result appears;
1832 * may be the same string as aSourceBuffer
1833 * @param aFlags Flags from nsIDocumentEncoder.
1834 * @param aWrapCol Number of columns after which to line wrap; 0 for no
1835 * auto-wrapping
1836 * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1837 * fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
1838 * long and NS_OK otherwise.
1840 static nsresult ConvertToPlainText(const nsAString& aSourceBuffer,
1841 nsAString& aResultBuffer, uint32_t aFlags,
1842 uint32_t aWrapCol);
1845 * Creates a 'loaded-as-data' HTML document that takes that principal,
1846 * script global, and URL from the argument, which may be null.
1848 static already_AddRefed<Document> CreateInertHTMLDocument(
1849 const Document* aTemplate);
1852 * Creates a 'loaded-as-data' XML document that takes that principal,
1853 * script global, and URL from the argument, which may be null.
1855 static already_AddRefed<Document> CreateInertXMLDocument(
1856 const Document* aTemplate);
1858 public:
1860 * Sets the text contents of a node by replacing all existing children
1861 * with a single text child.
1863 * The function always notifies.
1865 * Will reuse the first text child if one is available. Will not reuse
1866 * existing cdata children.
1868 * @param aContent Node to set contents of.
1869 * @param aValue Value to set contents to.
1870 * @param aTryReuse When true, the function will try to reuse an existing
1871 * textnodes rather than always creating a new one.
1873 static nsresult SetNodeTextContent(nsIContent* aContent,
1874 const nsAString& aValue, bool aTryReuse);
1877 * Get the textual contents of a node. This is a concatenation of all
1878 * textnodes that are direct or (depending on aDeep) indirect children
1879 * of the node.
1881 * NOTE! No serialization takes place and <br> elements
1882 * are not converted into newlines. Only textnodes and cdata nodes are
1883 * added to the result.
1885 * @see nsLayoutUtils::GetFrameTextContent
1887 * @param aNode Node to get textual contents of.
1888 * @param aDeep If true child elements of aNode are recursivly descended
1889 * into to find text children.
1890 * @param aResult the result. Out param.
1891 * @return false on out of memory errors, true otherwise.
1893 [[nodiscard]] static bool GetNodeTextContent(nsINode* aNode, bool aDeep,
1894 nsAString& aResult,
1895 const mozilla::fallible_t&);
1897 static void GetNodeTextContent(nsINode* aNode, bool aDeep,
1898 nsAString& aResult);
1901 * Same as GetNodeTextContents but appends the result rather than sets it.
1903 static bool AppendNodeTextContent(nsINode* aNode, bool aDeep,
1904 nsAString& aResult,
1905 const mozilla::fallible_t&);
1908 * Utility method that checks if a given node has any non-empty children. This
1909 * method does not descend recursively into children by default.
1911 * @param aDiscoverMode Set to eRecurseIntoChildren to descend recursively
1912 * into children.
1914 enum TextContentDiscoverMode : uint8_t {
1915 eRecurseIntoChildren,
1916 eDontRecurseIntoChildren
1919 static bool HasNonEmptyTextContent(
1920 nsINode* aNode,
1921 TextContentDiscoverMode aDiscoverMode = eDontRecurseIntoChildren);
1924 * Delete strings allocated for nsContentList matches
1926 static void DestroyMatchString(void* aData);
1929 * Notify when the first XUL menu is opened and when the all XUL menus are
1930 * closed. At opening, aInstalling should be TRUE, otherwise, it should be
1931 * FALSE.
1933 static void NotifyInstalledMenuKeyboardListener(bool aInstalling);
1936 * Check whether the nsIURI uses the given scheme.
1938 * Note that this will check the innermost URI rather than that of
1939 * the nsIURI itself.
1941 static bool SchemeIs(nsIURI* aURI, const char* aScheme);
1944 * Returns true if aPrincipal is an ExpandedPrincipal.
1946 static bool IsExpandedPrincipal(nsIPrincipal* aPrincipal);
1949 * Returns true if aPrincipal is the system or an ExpandedPrincipal.
1951 static bool IsSystemOrExpandedPrincipal(nsIPrincipal* aPrincipal);
1954 * Gets the system principal from the security manager.
1956 static nsIPrincipal* GetSystemPrincipal();
1959 * Gets the null subject principal singleton. This is only useful for
1960 * assertions.
1962 static nsIPrincipal* GetNullSubjectPrincipal() {
1963 return sNullSubjectPrincipal;
1967 * *aResourcePrincipal is a principal describing who may access the contents
1968 * of a resource. The resource can only be consumed by a principal that
1969 * subsumes *aResourcePrincipal. MAKE SURE THAT NOTHING EVER ACTS WITH THE
1970 * AUTHORITY OF *aResourcePrincipal.
1971 * It may be null to indicate that the resource has no data from any origin
1972 * in it yet and anything may access the resource.
1973 * Additional data is being mixed into the resource from aExtraPrincipal
1974 * (which may be null; if null, no data is being mixed in and this function
1975 * will do nothing). Update *aResourcePrincipal to reflect the new data.
1976 * If *aResourcePrincipal subsumes aExtraPrincipal, nothing needs to change,
1977 * otherwise *aResourcePrincipal is replaced with the system principal.
1978 * Returns true if *aResourcePrincipal changed.
1980 static bool CombineResourcePrincipals(
1981 nsCOMPtr<nsIPrincipal>* aResourcePrincipal,
1982 nsIPrincipal* aExtraPrincipal);
1985 * Trigger a link with uri aLinkURI. If aClick is false, this triggers a
1986 * mouseover on the link, otherwise it triggers a load after doing a
1987 * security check using aContent's principal.
1989 * @param aContent the node on which a link was triggered.
1990 * @param aLinkURI the URI of the link, must be non-null.
1991 * @param aTargetSpec the target (like target=, may be empty).
1992 * @param aClick whether this was a click or not (if false, this method
1993 * assumes you just hovered over the link).
1994 * @param aIsTrusted If false, JS Context will be pushed to stack
1995 * when the link is triggered.
1997 static void TriggerLink(nsIContent* aContent, nsIURI* aLinkURI,
1998 const nsString& aTargetSpec, bool aClick,
1999 bool aIsTrusted);
2002 * Get the link location.
2004 static void GetLinkLocation(mozilla::dom::Element* aElement,
2005 nsString& aLocationString);
2008 * Return top-level widget in the parent chain.
2010 static nsIWidget* GetTopLevelWidget(nsIWidget* aWidget);
2013 * Return the localized ellipsis for UI.
2015 static const nsDependentString GetLocalizedEllipsis();
2018 * Hide any XUL popups associated with aDocument, including any documents
2019 * displayed in child frames. Does nothing if aDocument is null.
2021 static void HidePopupsInDocument(Document* aDocument);
2024 * Retrieve the current drag session, or null if no drag is currently occuring
2026 static already_AddRefed<nsIDragSession> GetDragSession();
2029 * Initialize and set the dataTransfer field of an WidgetDragEvent.
2031 static nsresult SetDataTransferInEvent(mozilla::WidgetDragEvent* aDragEvent);
2033 // filters the drag and drop action to fit within the effects allowed and
2034 // returns it.
2035 static uint32_t FilterDropEffect(uint32_t aAction, uint32_t aEffectAllowed);
2038 * Return true if the target of a drop event is a content document that is
2039 * an ancestor of the document for the source of the drag.
2041 static bool CheckForSubFrameDrop(nsIDragSession* aDragSession,
2042 mozilla::WidgetDragEvent* aDropEvent);
2045 * Return true if aURI is a local file URI (i.e. file://).
2047 static bool URIIsLocalFile(nsIURI* aURI);
2050 * Get the application manifest URI for this document. The manifest URI
2051 * is specified in the manifest= attribute of the root element of the
2052 * document.
2054 * @param aDocument The document that lists the manifest.
2055 * @param aURI The manifest URI.
2057 static void GetOfflineAppManifest(Document* aDocument, nsIURI** aURI);
2060 * Check whether an application should be allowed to use offline APIs.
2062 static bool OfflineAppAllowed(nsIURI* aURI);
2065 * Check whether an application should be allowed to use offline APIs.
2067 static bool OfflineAppAllowed(nsIPrincipal* aPrincipal);
2070 * Determine whether the principal or document is allowed access to the
2071 * localization system. We don't want the web to ever see this but all our UI
2072 * including in content pages should pass this test. aDocumentURI may be
2073 * null.
2075 static bool PrincipalAllowsL10n(nsIPrincipal& aPrincipal,
2076 nsIURI* aDocumentURI);
2079 * Increases the count of blockers preventing scripts from running.
2080 * NOTE: You might want to use nsAutoScriptBlocker rather than calling
2081 * this directly
2083 static void AddScriptBlocker();
2086 * Decreases the count of blockers preventing scripts from running.
2087 * NOTE: You might want to use nsAutoScriptBlocker rather than calling
2088 * this directly
2090 * WARNING! Calling this function could synchronously execute scripts.
2092 static void RemoveScriptBlocker();
2095 * Add a runnable that is to be executed as soon as it's safe to execute
2096 * scripts.
2097 * NOTE: If it's currently safe to execute scripts, aRunnable will be run
2098 * synchronously before the function returns.
2100 * @param aRunnable The nsIRunnable to run as soon as it's safe to execute
2101 * scripts. Passing null is allowed and results in nothing
2102 * happening. It is also allowed to pass an object that
2103 * has not yet been AddRefed.
2105 static void AddScriptRunner(already_AddRefed<nsIRunnable> aRunnable);
2106 static void AddScriptRunner(nsIRunnable* aRunnable);
2109 * Returns true if it's safe to execute content script and false otherwise.
2111 * The only known case where this lies is mutation events. They run, and can
2112 * run anything else, when this function returns false, but this is ok.
2114 static bool IsSafeToRunScript();
2116 // Returns the browser window with the most recent time stamp that is
2117 // not in private browsing mode.
2118 static already_AddRefed<nsPIDOMWindowOuter> GetMostRecentNonPBWindow();
2121 * Call this function if !IsSafeToRunScript() and we fail to run the script
2122 * (rather than using AddScriptRunner as we usually do). |aDocument| is
2123 * optional as it is only used for showing the URL in the console.
2125 static void WarnScriptWasIgnored(Document* aDocument);
2128 * Add a "synchronous section", in the form of an nsIRunnable run once the
2129 * event loop has reached a "stable state". |aRunnable| must not cause any
2130 * queued events to be processed (i.e. must not spin the event loop).
2131 * We've reached a stable state when the currently executing task/event has
2132 * finished, see
2133 * http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#synchronous-section
2134 * In practice this runs aRunnable once the currently executing event
2135 * finishes. If called multiple times per task/event, all the runnables will
2136 * be executed, in the order in which RunInStableState() was called.
2138 static void RunInStableState(already_AddRefed<nsIRunnable> aRunnable);
2140 /* Add a pending IDBTransaction to be cleaned up at the end of performing a
2141 * microtask checkpoint.
2142 * See the step of "Cleanup Indexed Database Transactions" in
2143 * https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint
2145 static void AddPendingIDBTransaction(
2146 already_AddRefed<nsIRunnable> aTransaction);
2149 * Returns true if we are doing StableState/MetastableState.
2151 static bool IsInStableOrMetaStableState();
2153 static JSContext* GetCurrentJSContext();
2156 * Case insensitive comparison between two atoms.
2158 static bool EqualsIgnoreASCIICase(nsAtom* aAtom1, nsAtom* aAtom2);
2161 * Case insensitive comparison between two strings. However it only ignores
2162 * case for ASCII characters a-z.
2164 static bool EqualsIgnoreASCIICase(const nsAString& aStr1,
2165 const nsAString& aStr2);
2168 * Convert ASCII A-Z to a-z.
2170 static void ASCIIToLower(nsAString& aStr);
2171 static void ASCIIToLower(nsACString& aStr);
2172 static void ASCIIToLower(const nsAString& aSource, nsAString& aDest);
2173 static void ASCIIToLower(const nsACString& aSource, nsACString& aDest);
2176 * Convert ASCII a-z to A-Z.
2178 static void ASCIIToUpper(nsAString& aStr);
2179 static void ASCIIToUpper(nsACString& aStr);
2180 static void ASCIIToUpper(const nsAString& aSource, nsAString& aDest);
2181 static void ASCIIToUpper(const nsACString& aSource, nsACString& aDest);
2184 * Return whether aStr contains an ASCII uppercase character.
2186 static bool StringContainsASCIIUpper(const nsAString& aStr);
2188 // Returns NS_OK for same origin, error (NS_ERROR_DOM_BAD_URI) if not.
2189 static nsresult CheckSameOrigin(nsIChannel* aOldChannel,
2190 nsIChannel* aNewChannel);
2191 static nsIInterfaceRequestor* SameOriginChecker();
2194 * Get the Origin of the passed in nsIPrincipal or nsIURI. If the passed in
2195 * nsIURI or the URI of the passed in nsIPrincipal does not have a host, the
2196 * origin is set to 'null'.
2198 * The ASCII versions return a ASCII strings that are puny-code encoded,
2199 * suitable for, for example, header values. The UTF versions return strings
2200 * containing international characters.
2202 * The thread-safe versions return NS_ERROR_UNKNOWN_PROTOCOL if the
2203 * operation cannot be completed on the current thread.
2205 * @pre aPrincipal/aOrigin must not be null.
2207 * @note this should be used for HTML5 origin determination.
2209 static nsresult GetASCIIOrigin(nsIURI* aURI, nsACString& aOrigin);
2210 static nsresult GetUTFOrigin(nsIPrincipal* aPrincipal, nsAString& aOrigin);
2211 static nsresult GetUTFOrigin(nsIURI* aURI, nsAString& aOrigin);
2214 * This method creates and dispatches "command" event, which implements
2215 * XULCommandEvent.
2216 * If aPresShell is not null, dispatching goes via
2217 * PresShell::HandleDOMEventWithTarget().
2219 MOZ_CAN_RUN_SCRIPT
2220 static nsresult DispatchXULCommand(
2221 nsIContent* aTarget, bool aTrusted,
2222 mozilla::dom::Event* aSourceEvent = nullptr,
2223 mozilla::PresShell* aPresShell = nullptr, bool aCtrl = false,
2224 bool aAlt = false, bool aShift = false, bool aMeta = false,
2225 // Including MouseEventBinding here leads
2226 // to incude loops, unfortunately.
2227 uint16_t inputSource = 0 /* MouseEvent_Binding::MOZ_SOURCE_UNKNOWN */);
2229 static bool CheckMayLoad(nsIPrincipal* aPrincipal, nsIChannel* aChannel,
2230 bool aAllowIfInheritsPrincipal);
2233 * The method checks whether the caller can access native anonymous content.
2234 * If there is no JS in the stack or privileged JS is running, this
2235 * method returns true, otherwise false.
2237 static bool CanAccessNativeAnon();
2239 [[nodiscard]] static nsresult WrapNative(JSContext* cx, nsISupports* native,
2240 const nsIID* aIID,
2241 JS::MutableHandle<JS::Value> vp,
2242 bool aAllowWrapping = true) {
2243 return WrapNative(cx, native, nullptr, aIID, vp, aAllowWrapping);
2246 // Same as the WrapNative above, but use this one if aIID is nsISupports' IID.
2247 [[nodiscard]] static nsresult WrapNative(JSContext* cx, nsISupports* native,
2248 JS::MutableHandle<JS::Value> vp,
2249 bool aAllowWrapping = true) {
2250 return WrapNative(cx, native, nullptr, nullptr, vp, aAllowWrapping);
2253 [[nodiscard]] static nsresult WrapNative(JSContext* cx, nsISupports* native,
2254 nsWrapperCache* cache,
2255 JS::MutableHandle<JS::Value> vp,
2256 bool aAllowWrapping = true) {
2257 return WrapNative(cx, native, cache, nullptr, vp, aAllowWrapping);
2261 * Creates an arraybuffer from a binary string.
2263 static nsresult CreateArrayBuffer(JSContext* aCx, const nsACString& aData,
2264 JSObject** aResult);
2266 static void StripNullChars(const nsAString& aInStr, nsAString& aOutStr);
2269 * Strip all \n, \r and nulls from the given string
2270 * @param aString the string to remove newlines from [in/out]
2272 static void RemoveNewlines(nsString& aString);
2275 * Convert Windows and Mac platform linebreaks to \n.
2276 * @param aString the string to convert the newlines inside [in/out]
2278 static void PlatformToDOMLineBreaks(nsString& aString);
2279 [[nodiscard]] static bool PlatformToDOMLineBreaks(nsString& aString,
2280 const mozilla::fallible_t&);
2283 * Populates aResultString with the contents of the string-buffer aBuf, up
2284 * to aBuf's null-terminator. aBuf must not be null. Ownership of the string
2285 * is not transferred.
2287 static void PopulateStringFromStringBuffer(nsStringBuffer* aBuf,
2288 nsAString& aResultString);
2290 static bool IsHandlingKeyBoardEvent() { return sIsHandlingKeyBoardEvent; }
2292 static void SetIsHandlingKeyBoardEvent(bool aHandling) {
2293 sIsHandlingKeyBoardEvent = aHandling;
2297 * Utility method for getElementsByClassName. aRootNode is the node (either
2298 * document or element), which getElementsByClassName was called on.
2300 static already_AddRefed<nsContentList> GetElementsByClassName(
2301 nsINode* aRootNode, const nsAString& aClasses);
2304 * Returns a presshell for this document, if there is one. This will be
2305 * aDoc's direct presshell if there is one, otherwise we'll look at all
2306 * ancestor documents to try to find a presshell, so for example this can
2307 * still find a presshell for documents in display:none frames that have
2308 * no presentation. So you have to be careful how you use this presshell ---
2309 * getting generic data like a device context or widget from it is OK, but it
2310 * might not be this document's actual presentation.
2312 static mozilla::PresShell* FindPresShellForDocument(
2313 const Document* aDocument);
2316 * Returns the widget for this document if there is one. Looks at all ancestor
2317 * documents to try to find a widget, so for example this can still find a
2318 * widget for documents in display:none frames that have no presentation.
2320 * You should probably use WidgetForContent() instead of this, unless you have
2321 * a good reason to do otherwise.
2323 static nsIWidget* WidgetForDocument(const Document* aDocument);
2326 * Returns the appropriate widget for this element, if there is one. Unlike
2327 * WidgetForDocument(), this returns the correct widget for content in popups.
2329 * You should probably use this instead of WidgetForDocument().
2331 static nsIWidget* WidgetForContent(const nsIContent* aContent);
2334 * Returns a layer manager to use for the given document. Basically we
2335 * look up the document hierarchy for the first document which has
2336 * a presentation with an associated widget, and use that widget's
2337 * layer manager.
2339 * You should probably use LayerManagerForContent() instead of this, unless
2340 * you have a good reason to do otherwise.
2342 * @param aDoc the document for which to return a layer manager.
2343 * @param aAllowRetaining an outparam that states whether the returned
2344 * layer manager should be used for retained layers
2346 static already_AddRefed<mozilla::layers::LayerManager>
2347 LayerManagerForDocument(const Document* aDoc);
2350 * Returns a layer manager to use for the given content. Unlike
2351 * LayerManagerForDocument(), this returns the correct layer manager for
2352 * content in popups.
2354 * You should probably use this instead of LayerManagerForDocument().
2356 static already_AddRefed<mozilla::layers::LayerManager> LayerManagerForContent(
2357 const nsIContent* aContent);
2360 * Returns a layer manager to use for the given document. Basically we
2361 * look up the document hierarchy for the first document which has
2362 * a presentation with an associated widget, and use that widget's
2363 * layer manager. In addition to the normal layer manager lookup this will
2364 * specifically request a persistent layer manager. This means that the layer
2365 * manager is expected to remain the layer manager for the document in the
2366 * forseeable future. This function should be used carefully as it may change
2367 * the document's layer manager.
2369 * @param aDoc the document for which to return a layer manager.
2370 * @param aAllowRetaining an outparam that states whether the returned
2371 * layer manager should be used for retained layers
2373 static already_AddRefed<mozilla::layers::LayerManager>
2374 PersistentLayerManagerForDocument(Document* aDoc);
2377 * Determine whether a content node is focused or not,
2379 * @param aContent the content node to check
2380 * @return true if the content node is focused, false otherwise.
2382 static bool IsFocusedContent(const nsIContent* aContent);
2385 * Returns true if calling execCommand with 'cut' or 'copy' arguments is
2386 * allowed for the given subject principal. These are only allowed if the user
2387 * initiated them (like with a mouse-click or key press).
2389 static bool IsCutCopyAllowed(Document* aDocument,
2390 nsIPrincipal& aSubjectPrincipal);
2393 * Returns true if the browser should attempt to prevent the given caller type
2394 * from collecting distinctive information about the browser that could
2395 * be used to "fingerprint" and track the user across websites.
2397 static bool ResistFingerprinting(mozilla::dom::CallerType aCallerType) {
2398 return aCallerType != mozilla::dom::CallerType::System &&
2399 ShouldResistFingerprinting();
2403 * Returns true if CSSOM origin check should be skipped for WebDriver
2404 * based crawl to be able to collect data from cross-origin CSS style
2405 * sheets. This can be enabled by setting environment variable
2406 * MOZ_BYPASS_CSSOM_ORIGIN_CHECK.
2408 static bool BypassCSSOMOriginCheck() {
2409 #ifdef RELEASE_OR_BETA
2410 return false;
2411 #else
2412 return sBypassCSSOMOriginCheck;
2413 #endif
2417 * Fire mutation events for changes caused by parsing directly into a
2418 * context node.
2420 * @param aDoc the document of the node
2421 * @param aDest the destination node that got stuff appended to it
2422 * @param aOldChildCount the number of children the node had before parsing
2424 static void FireMutationEventsForDirectParsing(Document* aDoc,
2425 nsIContent* aDest,
2426 int32_t aOldChildCount);
2429 * Returns true if the content is in a document and contains a plugin
2430 * which we don't control event dispatch for, i.e. do any plugins in this
2431 * doc tree receive key events outside of our control? This always returns
2432 * false on MacOSX.
2434 static bool HasPluginWithUncontrolledEventDispatch(nsIContent* aContent);
2437 * Returns the root document in a document hierarchy. Normally this
2438 * will be the chrome document.
2440 static Document* GetRootDocument(Document* aDoc);
2442 static void GetShiftText(nsAString& text);
2443 static void GetControlText(nsAString& text);
2444 static void GetMetaText(nsAString& text);
2445 static void GetOSText(nsAString& text);
2446 static void GetAltText(nsAString& text);
2447 static void GetModifierSeparatorText(nsAString& text);
2450 * Returns if aContent has a tabbable subdocument.
2451 * A sub document isn't tabbable when it's a zombie document.
2453 * @param aElement element to test.
2455 * @return Whether the subdocument is tabbable.
2457 static bool IsSubDocumentTabbable(nsIContent* aContent);
2460 * Returns if aContent has the 'scrollgrab' property.
2461 * aContent may be null (in this case false is returned).
2463 static bool HasScrollgrab(nsIContent* aContent);
2466 * Flushes the layout tree (recursively)
2468 * @param aWindow the window the flush should start at
2471 static void FlushLayoutForTree(nsPIDOMWindowOuter* aWindow);
2474 * Returns true if content with the given principal is allowed to use XUL
2475 * and XBL and false otherwise.
2477 static bool AllowXULXBLForPrincipal(nsIPrincipal* aPrincipal);
2480 * Perform cleanup that's appropriate for XPCOM shutdown.
2482 static void XPCOMShutdown();
2485 * Checks if internal PDF viewer is enabled.
2487 static bool IsPDFJSEnabled();
2490 * Checks to see whether the given principal is the internal PDF
2491 * viewer principal.
2493 static bool IsPDFJS(nsIPrincipal* aPrincipal);
2495 * Same, but from WebIDL bindings. Checks whether the subject principal is for
2496 * the internal PDF viewer.
2498 static bool IsPDFJS(JSContext*, JSObject*);
2501 * Checks if internal SWF player is enabled.
2503 static bool IsSWFPlayerEnabled();
2505 enum ContentViewerType {
2506 TYPE_UNSUPPORTED,
2507 TYPE_CONTENT,
2508 TYPE_PLUGIN,
2509 TYPE_UNKNOWN
2512 static already_AddRefed<nsIDocumentLoaderFactory> FindInternalContentViewer(
2513 const nsACString& aType, ContentViewerType* aLoaderType = nullptr);
2516 * This helper method returns true if the aPattern pattern matches aValue.
2517 * aPattern should not contain leading and trailing slashes (/).
2518 * The pattern has to match the entire value not just a subset.
2519 * aDocument must be a valid pointer (not null).
2521 * This is following the HTML5 specification:
2522 * http://dev.w3.org/html5/spec/forms.html#attr-input-pattern
2524 * WARNING: This method mutates aPattern and aValue!
2526 * @param aValue the string to check.
2527 * @param aPattern the string defining the pattern.
2528 * @param aDocument the owner document of the element.
2529 * @result whether the given string is matches the pattern, or
2530 * Nothing() if the pattern couldn't be evaluated.
2532 static mozilla::Maybe<bool> IsPatternMatching(nsAString& aValue,
2533 nsAString& aPattern,
2534 const Document* aDocument);
2537 * Calling this adds support for
2538 * ontouch* event handler DOM attributes.
2540 static void InitializeTouchEventTable();
2543 * Test whether the given URI always inherits a security context
2544 * from the document it comes from.
2546 static nsresult URIInheritsSecurityContext(nsIURI* aURI, bool* aResult);
2549 * Called before a channel is created to query whether the new
2550 * channel should inherit the principal.
2552 * The argument aLoadingPrincipal must not be null. The argument
2553 * aURI must be the URI of the new channel. If aInheritForAboutBlank
2554 * is true, then about:blank will be told to inherit the principal.
2555 * If aForceInherit is true, the new channel will be told to inherit
2556 * the principal no matter what.
2558 * The return value is whether the new channel should inherit
2559 * the principal.
2561 static bool ChannelShouldInheritPrincipal(nsIPrincipal* aLoadingPrincipal,
2562 nsIURI* aURI,
2563 bool aInheritForAboutBlank,
2564 bool aForceInherit);
2566 static nsresult Btoa(const nsAString& aBinaryData,
2567 nsAString& aAsciiBase64String);
2569 static nsresult Atob(const nsAString& aAsciiString, nsAString& aBinaryData);
2572 * Returns whether the input element passed in parameter has the autocomplete
2573 * functionality enabled. It is taking into account the form owner.
2574 * NOTE: the caller has to make sure autocomplete makes sense for the
2575 * element's type.
2577 * @param aInput the input element to check. NOTE: aInput can't be null.
2578 * @return whether the input element has autocomplete enabled.
2580 static bool IsAutocompleteEnabled(mozilla::dom::HTMLInputElement* aInput);
2582 enum AutocompleteAttrState : uint8_t {
2583 eAutocompleteAttrState_Unknown = 1,
2584 eAutocompleteAttrState_Invalid,
2585 eAutocompleteAttrState_Valid,
2588 * Parses the value of the autocomplete attribute into aResult, ensuring it's
2589 * composed of valid tokens, otherwise the value "" is used.
2590 * Note that this method is used for form fields, not on a <form> itself.
2592 * @return whether aAttr was valid and can be cached.
2594 static AutocompleteAttrState SerializeAutocompleteAttribute(
2595 const nsAttrValue* aAttr, nsAString& aResult,
2596 AutocompleteAttrState aCachedState = eAutocompleteAttrState_Unknown);
2598 /* Variation that is used to retrieve a dictionary of the parts of the
2599 * autocomplete attribute.
2601 * @return whether aAttr was valid and can be cached.
2603 static AutocompleteAttrState SerializeAutocompleteAttribute(
2604 const nsAttrValue* aAttr, mozilla::dom::AutocompleteInfo& aInfo,
2605 AutocompleteAttrState aCachedState = eAutocompleteAttrState_Unknown,
2606 bool aGrantAllValidValue = false);
2609 * This will parse aSource, to extract the value of the pseudo attribute
2610 * with the name specified in aName. See
2611 * http://www.w3.org/TR/xml-stylesheet/#NT-StyleSheetPI for the specification
2612 * which is used to parse aSource.
2614 * @param aSource the string to parse
2615 * @param aName the name of the attribute to get the value for
2616 * @param aValue [out] the value for the attribute with name specified in
2617 * aAttribute. Empty if the attribute isn't present.
2618 * @return true if the attribute exists and was successfully parsed.
2619 * false if the attribute doesn't exist, or has a malformed
2620 * value, such as an unknown or unterminated entity.
2622 static bool GetPseudoAttributeValue(const nsString& aSource, nsAtom* aName,
2623 nsAString& aValue);
2626 * Returns true if the language name is a version of JavaScript and
2627 * false otherwise
2629 static bool IsJavaScriptLanguage(const nsString& aName);
2631 static bool IsJavascriptMIMEType(const nsAString& aMIMEType);
2633 static void SplitMimeType(const nsAString& aValue, nsString& aType,
2634 nsString& aParams);
2637 * Function checks if the user is idle.
2639 * @param aRequestedIdleTimeInMS The idle observer's requested idle time.
2640 * @param aUserIsIdle boolean indicating if the user
2641 * is currently idle or not.
2642 * @return NS_OK NS_OK returned if the requested idle
2643 * service and the current idle time were
2644 * successfully obtained.
2645 * NS_ERROR_FAILURE returned if the the
2646 * requested idle service or the current
2647 * idle were not obtained.
2649 static nsresult IsUserIdle(uint32_t aRequestedIdleTimeInMS,
2650 bool* aUserIsIdle);
2653 * Takes a selection, and a text control element (<input> or <textarea>), and
2654 * returns the offsets in the text content corresponding to the selection.
2655 * The selection's anchor and focus must both be in the root node passed or a
2656 * descendant.
2658 * @param aSelection Selection to check
2659 * @param aRoot Root <input> or <textarea> element
2660 * @param aOutStartOffset Output start offset
2661 * @param aOutEndOffset Output end offset
2663 static void GetSelectionInTextControl(mozilla::dom::Selection* aSelection,
2664 Element* aRoot,
2665 uint32_t& aOutStartOffset,
2666 uint32_t& aOutEndOffset);
2669 * Takes a frame for anonymous content within a text control (<input> or
2670 * <textarea>), and returns an offset in the text content, adjusted for a
2671 * trailing <br> frame.
2673 * @param aOffsetFrame Frame for the text content in which the offset
2674 * lies
2675 * @param aOffset Offset as calculated by GetContentOffsetsFromPoint
2676 * @param aOutOffset Output adjusted offset
2678 * @see GetSelectionInTextControl for the original basis of this function.
2680 static int32_t GetAdjustedOffsetInTextControl(nsIFrame* aOffsetFrame,
2681 int32_t aOffset);
2684 * Returns pointer to HTML editor instance for the aPresContext when there is.
2685 * The HTML editor is shared by contenteditable elements or used in
2686 * designMode. When there are no contenteditable elements and the document
2687 * is not in designMode, this returns nullptr.
2689 static mozilla::HTMLEditor* GetHTMLEditor(nsPresContext* aPresContext);
2690 static mozilla::HTMLEditor* GetHTMLEditor(nsDocShell* aDocShell);
2693 * Returns pointer to a text editor if <input> or <textarea> element is
2694 * active element in the document for aPresContext, or pointer to HTML
2695 * editor if there is (i.e., even if non-editable element has focus or
2696 * nobody has focus). The reason is, HTML editor may handle some input
2697 * even if there is no active editing host.
2698 * Note that this does not return editor in descendant documents.
2700 static mozilla::TextEditor* GetActiveEditor(nsPresContext* aPresContext);
2701 static mozilla::TextEditor* GetActiveEditor(nsPIDOMWindowOuter* aWindow);
2704 * Returns `TextEditor` which manages `aAnonymousContent` if there is.
2705 * Note that this method returns `nullptr` if `TextEditor` for the
2706 * `aAnonymousContent` hasn't been created yet.
2708 static mozilla::TextEditor* GetTextEditorFromAnonymousNodeWithoutCreation(
2709 nsIContent* aAnonymousContent);
2712 * Returns whether a node has an editable ancestor.
2714 * @param aNode The node to test.
2716 static bool IsNodeInEditableRegion(nsINode* aNode);
2719 * Returns a LogModule that dump calls from content script are logged to.
2720 * This can be enabled with the 'Dump' module, and is useful for synchronizing
2721 * content JS to other logging modules.
2723 static mozilla::LogModule* DOMDumpLog();
2726 * Returns whether a given header is forbidden for an XHR or fetch
2727 * request.
2729 static bool IsForbiddenRequestHeader(const nsACString& aHeader);
2732 * Returns whether a given header is forbidden for a system XHR
2733 * request.
2735 static bool IsForbiddenSystemRequestHeader(const nsACString& aHeader);
2738 * Returns whether a given header has characters that aren't permitted
2740 static bool IsCorsUnsafeRequestHeaderValue(const nsACString& aHeaderValue);
2743 * Returns whether a given Accept header value is allowed
2744 * for a non-CORS XHR or fetch request.
2746 static bool IsAllowedNonCorsAccept(const nsACString& aHeaderValue);
2749 * Returns whether a given Content-Type header value is allowed
2750 * for a non-CORS XHR or fetch request.
2752 static bool IsAllowedNonCorsContentType(const nsACString& aHeaderValue);
2755 * Returns whether a given Content-Language or accept-language header value is
2756 * allowed for a non-CORS XHR or fetch request.
2758 static bool IsAllowedNonCorsLanguage(const nsACString& aHeaderValue);
2761 * Returns whether a given header and value is a CORS-safelisted request
2762 * header per https://fetch.spec.whatwg.org/#cors-safelisted-request-header
2764 static bool IsCORSSafelistedRequestHeader(const nsACString& aName,
2765 const nsACString& aValue);
2768 * Returns whether a given header is forbidden for an XHR or fetch
2769 * response.
2771 static bool IsForbiddenResponseHeader(const nsACString& aHeader);
2774 * Returns the inner window ID for the window associated with a request.
2776 static uint64_t GetInnerWindowID(nsIRequest* aRequest);
2779 * Returns the inner window ID for the window associated with a load group.
2781 static uint64_t GetInnerWindowID(nsILoadGroup* aLoadGroup);
2784 * Encloses aHost in brackets if it is an IPv6 address.
2786 static void MaybeFixIPv6Host(nsACString& aHost);
2789 * If the hostname for aURI is an IPv6 it encloses it in brackets,
2790 * otherwise it just outputs the hostname in aHost.
2792 static nsresult GetHostOrIPv6WithBrackets(nsIURI* aURI, nsAString& aHost);
2793 static nsresult GetHostOrIPv6WithBrackets(nsIURI* aURI, nsACString& aHost);
2794 static nsresult GetHostOrIPv6WithBrackets(nsIPrincipal* aPrincipal,
2795 nsACString& aHost);
2798 * Call the given callback on all remote children of the given top-level
2799 * window. Return Callstate::Stop from the callback to stop calling further
2800 * children.
2802 static void CallOnAllRemoteChildren(
2803 nsPIDOMWindowOuter* aWindow,
2804 const std::function<mozilla::CallState(mozilla::dom::BrowserParent*)>&
2805 aCallback);
2808 * Call nsPIDOMWindow::SetKeyboardIndicators all all remote children. This is
2809 * in here rather than nsGlobalWindow because BrowserParent indirectly
2810 * includes Windows headers which aren't allowed there.
2812 static void SetKeyboardIndicatorsOnRemoteChildren(
2813 nsPIDOMWindowOuter* aWindow, UIStateChangeType aShowFocusRings);
2816 * Given an nsIFile, attempts to read it into aString.
2818 * Note: Use sparingly! This causes main-thread I/O, which causes jank and all
2819 * other bad things.
2821 static nsresult SlurpFileToString(nsIFile* aFile, nsACString& aString);
2824 * Returns true if the mime service thinks this file contains an image.
2826 * The content type is returned in aType.
2828 static bool IsFileImage(nsIFile* aFile, nsACString& aType);
2831 * Given an IPCDataTransferItem that has a flavor for which IsFlavorImage
2832 * returns true and whose IPCDataTransferData is of type nsCString (raw image
2833 * data), construct an imgIContainer for the image encoded by the transfer
2834 * item.
2836 static nsresult DataTransferItemToImage(
2837 const mozilla::dom::IPCDataTransferItem& aItem,
2838 imgIContainer** aContainer);
2841 * Given a flavor obtained from an IPCDataTransferItem or nsITransferable,
2842 * returns true if we should treat the data as an image.
2844 static bool IsFlavorImage(const nsACString& aFlavor);
2846 static nsresult IPCTransferableToTransferable(
2847 const mozilla::dom::IPCDataTransfer& aDataTransfer,
2848 const bool& aIsPrivateData, nsIPrincipal* aRequestingPrincipal,
2849 const nsContentPolicyType& aContentPolicyType,
2850 nsITransferable* aTransferable,
2851 mozilla::dom::ContentParent* aContentParent,
2852 mozilla::dom::BrowserChild* aBrowserChild);
2854 static void TransferablesToIPCTransferables(
2855 nsIArray* aTransferables, nsTArray<mozilla::dom::IPCDataTransfer>& aIPC,
2856 bool aInSyncMessage, mozilla::dom::ContentChild* aChild,
2857 mozilla::dom::ContentParent* aParent);
2859 static void TransferableToIPCTransferable(
2860 nsITransferable* aTransferable,
2861 mozilla::dom::IPCDataTransfer* aIPCDataTransfer, bool aInSyncMessage,
2862 mozilla::dom::ContentChild* aChild, mozilla::dom::ContentParent* aParent);
2865 * Get the pixel data from the given source surface and return it as a buffer.
2866 * The length and stride will be assigned from the surface.
2868 static mozilla::UniquePtr<char[]> GetSurfaceData(
2869 mozilla::NotNull<mozilla::gfx::DataSourceSurface*> aSurface,
2870 size_t* aLength, int32_t* aStride);
2873 * Get the pixel data from the given source surface and fill it in Shmem.
2874 * The length and stride will be assigned from the surface.
2876 static mozilla::Maybe<mozilla::ipc::Shmem> GetSurfaceData(
2877 mozilla::gfx::DataSourceSurface* aSurface, size_t* aLength,
2878 int32_t* aStride, mozilla::ipc::IShmemAllocator* aAlloc);
2880 // Helpers shared by the implementations of nsContentUtils methods and
2881 // nsIDOMWindowUtils methods.
2882 static mozilla::Modifiers GetWidgetModifiers(int32_t aModifiers);
2883 static nsIWidget* GetWidget(mozilla::PresShell* aPresShell, nsPoint* aOffset);
2884 static int16_t GetButtonsFlagForButton(int32_t aButton);
2885 static mozilla::LayoutDeviceIntPoint ToWidgetPoint(
2886 const mozilla::CSSPoint& aPoint, const nsPoint& aOffset,
2887 nsPresContext* aPresContext);
2888 static nsView* GetViewToDispatchEvent(nsPresContext* aPresContext,
2889 mozilla::PresShell** aPresShell);
2892 * Synthesize a mouse event to the given widget
2893 * (see nsIDOMWindowUtils.sendMouseEvent).
2895 MOZ_CAN_RUN_SCRIPT
2896 static nsresult SendMouseEvent(
2897 mozilla::PresShell* aPresShell, const nsAString& aType, float aX,
2898 float aY, int32_t aButton, int32_t aButtons, int32_t aClickCount,
2899 int32_t aModifiers, bool aIgnoreRootScrollFrame, float aPressure,
2900 unsigned short aInputSourceArg, uint32_t aIdentifier, bool aToWindow,
2901 bool* aPreventDefault, bool aIsDOMEventSynthesized,
2902 bool aIsWidgetEventSynthesized);
2904 static void FirePageShowEventForFrameLoaderSwap(
2905 nsIDocShellTreeItem* aItem,
2906 mozilla::dom::EventTarget* aChromeEventHandler, bool aFireIfShowing,
2907 bool aOnlySystemGroup = false);
2909 static void FirePageHideEventForFrameLoaderSwap(
2910 nsIDocShellTreeItem* aItem,
2911 mozilla::dom::EventTarget* aChromeEventHandler,
2912 bool aOnlySystemGroup = false);
2914 static already_AddRefed<nsPIWindowRoot> GetWindowRoot(Document* aDoc);
2917 * If there is a Referrer-Policy response header in |aChannel|, parse a
2918 * referrer policy from the header.
2920 * @param the channel from which to get the Referrer-Policy header
2921 * @return referrer policy from the response header in aChannel
2923 static mozilla::dom::ReferrerPolicy GetReferrerPolicyFromChannel(
2924 nsIChannel* aChannel);
2926 static bool IsNonSubresourceRequest(nsIChannel* aChannel);
2928 static bool IsNonSubresourceInternalPolicyType(nsContentPolicyType aType);
2930 public:
2932 * Returns true if this window/channel is a 3rd party context.
2934 static bool IsThirdPartyWindowOrChannel(nsPIDOMWindowInner* aWindow,
2935 nsIChannel* aChannel, nsIURI* aURI);
2938 * Returns true if this window's channel has been marked as a third-party
2939 * tracking resource.
2941 static bool IsThirdPartyTrackingResourceWindow(nsPIDOMWindowInner* aWindow);
2944 * Returns true if this window's channel has been marked as a first-party
2945 * tracking resource.
2947 static bool IsFirstPartyTrackingResourceWindow(nsPIDOMWindowInner* aWindow);
2950 * Serializes a HTML nsINode into its markup representation.
2952 static bool SerializeNodeToMarkup(nsINode* aRoot, bool aDescendentsOnly,
2953 nsAString& aOut);
2956 * Returns true iff the provided JSObject is a global, and its URI matches
2957 * the provided about: URI.
2958 * @param aGlobal the JSObject whose URI to check, if it is a global.
2959 * @param aUri the URI to match, e.g. "about:feeds"
2961 static bool IsSpecificAboutPage(JSObject* aGlobal, const char* aUri);
2963 static void SetScrollbarsVisibility(nsIDocShell* aDocShell, bool aVisible);
2966 * Try to find the docshell corresponding to the given event target.
2968 static nsIDocShell* GetDocShellForEventTarget(
2969 mozilla::dom::EventTarget* aTarget);
2972 * Returns true if the "HTTPS state" of the document should be "modern". See:
2974 * https://html.spec.whatwg.org/#concept-document-https-state
2975 * https://fetch.spec.whatwg.org/#concept-response-https-state
2977 static bool HttpsStateIsModern(Document* aDocument);
2980 * Returns true if the channel is for top-level window and is over secure
2981 * context.
2982 * https://github.com/whatwg/html/issues/4930 tracks the spec side of this.
2984 static bool ComputeIsSecureContext(nsIChannel* aChannel);
2987 * Try to upgrade an element.
2988 * https://html.spec.whatwg.org/multipage/custom-elements.html#concept-try-upgrade
2990 static void TryToUpgradeElement(Element* aElement);
2993 * Creates a new XUL or XHTML element applying any appropriate custom element
2994 * definition.
2996 * If aFromParser != FROM_PARSER_FRAGMENT, a nested event loop permits
2997 * arbitrary changes to the world before this function returns. This should
2998 * probably just be MOZ_CAN_RUN_SCRIPT - bug 1543259.
3000 MOZ_CAN_RUN_SCRIPT_BOUNDARY static nsresult NewXULOrHTMLElement(
3001 Element** aResult, mozilla::dom::NodeInfo* aNodeInfo,
3002 mozilla::dom::FromParser aFromParser, nsAtom* aIsAtom,
3003 mozilla::dom::CustomElementDefinition* aDefinition);
3005 static mozilla::dom::CustomElementRegistry* GetCustomElementRegistry(
3006 Document*);
3009 * Looking up a custom element definition.
3010 * https://html.spec.whatwg.org/#look-up-a-custom-element-definition
3012 static mozilla::dom::CustomElementDefinition* LookupCustomElementDefinition(
3013 Document* aDoc, nsAtom* aNameAtom, uint32_t aNameSpaceID,
3014 nsAtom* aTypeAtom);
3016 static void RegisterCallbackUpgradeElement(Element* aElement,
3017 nsAtom* aTypeName);
3019 static void RegisterUnresolvedElement(Element* aElement, nsAtom* aTypeName);
3020 static void UnregisterUnresolvedElement(Element* aElement);
3022 static void EnqueueUpgradeReaction(
3023 Element* aElement, mozilla::dom::CustomElementDefinition* aDefinition);
3025 static void EnqueueLifecycleCallback(
3026 mozilla::dom::ElementCallbackType aType, Element* aCustomElement,
3027 mozilla::dom::LifecycleCallbackArgs* aArgs = nullptr,
3028 mozilla::dom::LifecycleAdoptedCallbackArgs* aAdoptedCallbackArgs =
3029 nullptr,
3030 mozilla::dom::CustomElementDefinition* aDefinition = nullptr);
3033 * Appends all "document level" native anonymous content subtree roots for
3034 * aDocument to aElements. Document level NAC subtrees are those created
3035 * by ancestor frames of the document element's primary frame, such as
3036 * the scrollbar elements created by the root scroll frame.
3038 static void AppendDocumentLevelNativeAnonymousContentTo(
3039 Document* aDocument, nsTArray<nsIContent*>& aElements);
3042 * Appends all native anonymous content subtree roots generated by `aContent`
3043 * to `aKids`.
3045 * See `AllChildrenIterator` for the description of the `aFlags` parameter.
3047 static void AppendNativeAnonymousChildren(const nsIContent* aContent,
3048 nsTArray<nsIContent*>& aKids,
3049 uint32_t aFlags);
3052 * Query triggeringPrincipal if there's a 'triggeringprincipal' attribute on
3053 * aLoadingNode, if no such attribute is specified, aDefaultPrincipal is
3054 * returned if it is provided, otherwise the NodePrincipal of aLoadingNode is
3055 * returned.
3057 * Return true if aLoadingNode has a 'triggeringprincipal' attribute, and
3058 * the value 'triggeringprincipal' is also successfully deserialized,
3059 * otherwise return false.
3061 static bool QueryTriggeringPrincipal(nsIContent* aLoadingNode,
3062 nsIPrincipal* aDefaultPrincipal,
3063 nsIPrincipal** aTriggeringPrincipal);
3065 static bool QueryTriggeringPrincipal(nsIContent* aLoadingNode,
3066 nsIPrincipal** aTriggeringPrincipal) {
3067 return QueryTriggeringPrincipal(aLoadingNode, nullptr,
3068 aTriggeringPrincipal);
3072 * Returns the content policy type that should be used for loading images
3073 * for displaying in the UI. The sources of such images can be <xul:image>,
3074 * <xul:menuitem> on OSX where we load the image through nsMenuItemIconX, etc.
3076 static void GetContentPolicyTypeForUIImageLoading(
3077 nsIContent* aLoadingNode, nsIPrincipal** aTriggeringPrincipal,
3078 nsContentPolicyType& aContentPolicyType, uint64_t* aRequestContextID);
3080 static nsresult CreateJSValueFromSequenceOfObject(
3081 JSContext* aCx, const mozilla::dom::Sequence<JSObject*>& aTransfer,
3082 JS::MutableHandle<JS::Value> aValue);
3085 * Returns true if reserved key events should be prevented from being sent
3086 * to their target. Instead, the key event should be handled by chrome only.
3088 static bool ShouldBlockReservedKeys(mozilla::WidgetKeyboardEvent* aKeyEvent);
3091 * Returns the nsIPluginTag for the plugin we should try to use for a given
3092 * MIME type.
3094 * @param aMIMEType The MIME type of the document being loaded.
3095 * @param aNoFakePlugin If false then this method should consider JS plugins.
3097 static already_AddRefed<nsIPluginTag> PluginTagForType(
3098 const nsCString& aMIMEType, bool aNoFakePlugin);
3101 * Returns one of the nsIObjectLoadingContent::TYPE_ values describing the
3102 * content type which will be used for the given MIME type when loaded within
3103 * an nsObjectLoadingContent.
3105 * NOTE: This method doesn't take capabilities into account. The caller must
3106 * take that into account.
3108 * @param aMIMEType The MIME type of the document being loaded.
3109 * @param aNoFakePlugin If false then this method should consider JS plugins.
3110 * @param aContent The nsIContent object which is performing the load. May be
3111 * nullptr in which case the docshell's plugin permissions
3112 * will not be checked.
3114 static uint32_t HtmlObjectContentTypeForMIMEType(const nsCString& aMIMEType,
3115 bool aNoFakePlugin,
3116 nsIContent* aContent);
3118 static already_AddRefed<nsISerialEventTarget> GetEventTargetByLoadInfo(
3119 nsILoadInfo* aLoadInfo, mozilla::TaskCategory aCategory);
3122 * Detect whether a string is a local-url.
3123 * https://drafts.csswg.org/css-values/#local-urls
3125 static bool IsLocalRefURL(const nsAString& aString);
3128 * Compose a tab id with process id and a serial number.
3130 static uint64_t GenerateTabId();
3133 * Compose a browser id with process id and a serial number.
3135 static uint64_t GenerateBrowserId();
3138 * Generate an id for a BrowsingContext using a range of serial
3139 * numbers reserved for the current process.
3141 static uint64_t GenerateBrowsingContextId();
3144 * Generate an id using a range of serial numbers reserved for the current
3145 * process. aId should be a counter that's incremented every time
3146 * GenerateProcessSpecificId is called.
3148 static uint64_t GenerateProcessSpecificId(uint64_t aId);
3150 static std::tuple<uint64_t, uint64_t> SplitProcessSpecificId(uint64_t aId);
3153 * Generate a window ID which is unique across processes and will never be
3154 * recycled.
3156 static uint64_t GenerateWindowId();
3159 * Generate an ID for a load which is unique across processes and will never
3160 * be recycled.
3162 static uint64_t GenerateLoadIdentifier();
3165 * Determine whether or not the user is currently interacting with the web
3166 * browser. This method is safe to call from off of the main thread.
3168 static bool GetUserIsInteracting();
3170 // Alternate data MIME type used by the ScriptLoader to register and read
3171 // bytecode out of the nsCacheInfoChannel.
3172 [[nodiscard]] static bool InitJSBytecodeMimeType();
3173 static nsCString& JSBytecodeMimeType() {
3174 MOZ_ASSERT(sJSBytecodeMimeType);
3175 return *sJSBytecodeMimeType;
3179 * Checks if the passed-in name is one of the special names: "_blank", "_top",
3180 * "_parent" or "_self".
3182 static bool IsSpecialName(const nsAString& aName);
3185 * Checks if the passed-in name should override an existing name on the
3186 * window. Values which should not override include: "", "_blank", "_top",
3187 * "_parent" and "_self".
3189 static bool IsOverridingWindowName(const nsAString& aName);
3192 * If there is a SourceMap (higher precedence) or X-SourceMap (lower
3193 * precedence) response header in |aChannel|, set |aResult| to the
3194 * header's value and return true. Otherwise, return false.
3196 * @param aChannel The HTTP channel
3197 * @param aResult The string result.
3199 static bool GetSourceMapURL(nsIHttpChannel* aChannel, nsACString& aResult);
3202 * Returns true if the passed-in mesasge is a pending InputEvent.
3204 * @param aMsg The message to check
3206 static bool IsMessageInputEvent(const IPC::Message& aMsg);
3209 * Returns true if the passed-in message is a critical InputEvent.
3211 * @param aMsg The message to check
3213 static bool IsMessageCriticalInputEvent(const IPC::Message& aMsg);
3215 static void AsyncPrecreateStringBundles();
3217 static bool ContentIsLink(nsIContent* aContent);
3219 static already_AddRefed<mozilla::dom::ContentFrameMessageManager>
3220 TryGetBrowserChildGlobal(nsISupports* aFrom);
3222 // Get a serial number for a newly created inner or outer window.
3223 static uint32_t InnerOrOuterWindowCreated();
3224 // Record that an inner or outer window has been destroyed.
3225 static void InnerOrOuterWindowDestroyed();
3226 // Get the current number of inner or outer windows.
3227 static int32_t GetCurrentInnerOrOuterWindowCount() {
3228 return sInnerOrOuterWindowCount;
3232 * Serializes a JSON-like JS::Value into a string.
3234 * Usage:
3235 * nsAutoString serializedValue;
3236 * nsContentUtils::StringifyJSON(cx, &value, serializedValue);
3238 static bool StringifyJSON(JSContext* aCx, JS::MutableHandle<JS::Value> vp,
3239 nsAString& aOutStr);
3242 * Returns true if the top level ancestor content document of aDocument hasn't
3243 * yet had the first contentful paint and there is a high priority event
3244 * pending in the main thread.
3246 static bool HighPriorityEventPendingForTopLevelDocumentBeforeContentfulPaint(
3247 Document* aDocument);
3249 static nsGlobalWindowInner* CallerInnerWindow();
3252 * Return safe area insets of window that defines as
3253 * https://drafts.csswg.org/css-env-1/#safe-area-insets.
3255 static mozilla::ScreenIntMargin GetWindowSafeAreaInsets(
3256 nsIScreen* aScreen, const mozilla::ScreenIntMargin& aSafeareaInsets,
3257 const mozilla::LayoutDeviceIntRect& aWindowRect);
3259 struct SubresourceCacheValidationInfo {
3260 // The expiration time, in seconds, if known.
3261 mozilla::Maybe<uint32_t> mExpirationTime;
3262 bool mMustRevalidate = false;
3266 * Gets cache validation info for subresources such as images or CSS
3267 * stylesheets.
3269 static SubresourceCacheValidationInfo GetSubresourceCacheValidationInfo(
3270 nsIRequest*);
3272 static uint32_t SecondsFromPRTime(PRTime aTime) {
3273 return uint32_t(int64_t(aTime) / int64_t(PR_USEC_PER_SEC));
3277 * Converts the given URL to a string and truncates it to the given length.
3279 * Returns an empty string if aURL is null.
3281 static nsCString TruncatedURLForDisplay(nsIURI* aURL, uint32_t aMaxLen = 128);
3283 private:
3284 static bool InitializeEventTable();
3286 static nsresult EnsureStringBundle(PropertiesFile aFile);
3288 static bool CanCallerAccess(nsIPrincipal* aSubjectPrincipal,
3289 nsIPrincipal* aPrincipal);
3291 static nsresult WrapNative(JSContext* cx, nsISupports* native,
3292 nsWrapperCache* cache, const nsIID* aIID,
3293 JS::MutableHandle<JS::Value> vp,
3294 bool aAllowWrapping);
3296 static nsresult DispatchEvent(Document* aDoc, nsISupports* aTarget,
3297 const nsAString& aEventName, CanBubble,
3298 Cancelable, Composed, Trusted,
3299 bool* aDefaultAction = nullptr,
3300 ChromeOnlyDispatch = ChromeOnlyDispatch::eNo);
3302 static nsresult DispatchEvent(Document* aDoc, nsISupports* aTarget,
3303 mozilla::WidgetEvent& aWidgetEvent,
3304 EventMessage aEventMessage, CanBubble,
3305 Cancelable, Trusted,
3306 bool* aDefaultAction = nullptr,
3307 ChromeOnlyDispatch = ChromeOnlyDispatch::eNo);
3309 static void InitializeModifierStrings();
3311 static void DropFragmentParsers();
3313 static bool MatchClassNames(mozilla::dom::Element* aElement,
3314 int32_t aNamespaceID, nsAtom* aAtom, void* aData);
3315 static void DestroyClassNameArray(void* aData);
3316 static void* AllocClassMatchingInfo(nsINode* aRootNode,
3317 const nsString* aClasses);
3319 static mozilla::EventClassID GetEventClassIDFromMessage(
3320 EventMessage aEventMessage);
3322 // Fills in aInfo with the tokens from the supplied autocomplete attribute.
3323 static AutocompleteAttrState InternalSerializeAutocompleteAttribute(
3324 const nsAttrValue* aAttrVal, mozilla::dom::AutocompleteInfo& aInfo,
3325 bool aGrantAllValidValue = false);
3327 static mozilla::CallState CallOnAllRemoteChildren(
3328 mozilla::dom::MessageBroadcaster* aManager,
3329 const std::function<mozilla::CallState(mozilla::dom::BrowserParent*)>&
3330 aCallback);
3332 static nsINode* GetCommonAncestorHelper(nsINode* aNode1, nsINode* aNode2);
3333 static nsIContent* GetCommonFlattenedTreeAncestorHelper(
3334 nsIContent* aContent1, nsIContent* aContent2);
3336 static nsIXPConnect* sXPConnect;
3338 static nsIScriptSecurityManager* sSecurityManager;
3339 static nsIPrincipal* sSystemPrincipal;
3340 static nsIPrincipal* sNullSubjectPrincipal;
3342 static nsNameSpaceManager* sNameSpaceManager;
3344 static nsIIOService* sIOService;
3345 static nsIUUIDGenerator* sUUIDGenerator;
3347 static nsIConsoleService* sConsoleService;
3349 static nsTHashMap<nsRefPtrHashKey<nsAtom>, EventNameMapping>* sAtomEventTable;
3350 static nsTHashMap<nsStringHashKey, EventNameMapping>* sStringEventTable;
3351 static nsTArray<RefPtr<nsAtom>>* sUserDefinedEvents;
3353 static nsIStringBundleService* sStringBundleService;
3354 static nsIStringBundle* sStringBundles[PropertiesFile_COUNT];
3355 class nsContentUtilsReporter;
3357 static nsIContentPolicy* sContentPolicyService;
3358 static bool sTriedToGetContentPolicy;
3360 static RefPtr<mozilla::intl::LineBreaker> sLineBreaker;
3361 static RefPtr<mozilla::intl::WordBreaker> sWordBreaker;
3363 static mozilla::StaticRefPtr<nsIBidiKeyboard> sBidiKeyboard;
3365 static bool sInitialized;
3366 static uint32_t sScriptBlockerCount;
3367 static uint32_t sDOMNodeRemovedSuppressCount;
3369 // Not an nsCOMArray because removing elements from those is slower
3370 static AutoTArray<nsCOMPtr<nsIRunnable>, 8>* sBlockedScriptRunners;
3371 static uint32_t sRunnersCountAtFirstBlocker;
3372 static uint32_t sScriptBlockerCountWhereRunnersPrevented;
3374 static nsIInterfaceRequestor* sSameOriginChecker;
3376 static bool sIsHandlingKeyBoardEvent;
3377 #ifndef RELEASE_OR_BETA
3378 static bool sBypassCSSOMOriginCheck;
3379 #endif
3381 class UserInteractionObserver;
3382 static UserInteractionObserver* sUserInteractionObserver;
3384 static nsHtml5StringParser* sHTMLFragmentParser;
3385 static nsIParser* sXMLFragmentParser;
3386 static nsIFragmentContentSink* sXMLFragmentSink;
3389 * True if there's a fragment parser activation on the stack.
3391 static bool sFragmentParsingActive;
3393 static nsString* sShiftText;
3394 static nsString* sControlText;
3395 static nsString* sMetaText;
3396 static nsString* sOSText;
3397 static nsString* sAltText;
3398 static nsString* sModifierSeparator;
3400 // Alternate data mime type, used by the ScriptLoader to register and read the
3401 // bytecode out of the nsCacheInfoChannel.
3402 static nsCString* sJSBytecodeMimeType;
3404 static mozilla::LazyLogModule sDOMDumpLog;
3406 static int32_t sInnerOrOuterWindowCount;
3407 static uint32_t sInnerOrOuterWindowSerialCounter;
3410 /* static */ inline ExtContentPolicyType
3411 nsContentUtils::InternalContentPolicyTypeToExternal(nsContentPolicyType aType) {
3412 switch (aType) {
3413 case nsIContentPolicy::TYPE_INTERNAL_SCRIPT:
3414 case nsIContentPolicy::TYPE_INTERNAL_SCRIPT_PRELOAD:
3415 case nsIContentPolicy::TYPE_INTERNAL_MODULE:
3416 case nsIContentPolicy::TYPE_INTERNAL_MODULE_PRELOAD:
3417 case nsIContentPolicy::TYPE_INTERNAL_WORKER:
3418 case nsIContentPolicy::TYPE_INTERNAL_SHARED_WORKER:
3419 case nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER:
3420 case nsIContentPolicy::TYPE_INTERNAL_WORKER_IMPORT_SCRIPTS:
3421 case nsIContentPolicy::TYPE_INTERNAL_AUDIOWORKLET:
3422 case nsIContentPolicy::TYPE_INTERNAL_PAINTWORKLET:
3423 case nsIContentPolicy::TYPE_INTERNAL_CHROMEUTILS_COMPILED_SCRIPT:
3424 case nsIContentPolicy::TYPE_INTERNAL_FRAME_MESSAGEMANAGER_SCRIPT:
3425 return ExtContentPolicy::TYPE_SCRIPT;
3427 case nsIContentPolicy::TYPE_INTERNAL_EMBED:
3428 case nsIContentPolicy::TYPE_INTERNAL_OBJECT:
3429 return ExtContentPolicy::TYPE_OBJECT;
3431 case nsIContentPolicy::TYPE_INTERNAL_FRAME:
3432 case nsIContentPolicy::TYPE_INTERNAL_IFRAME:
3433 return ExtContentPolicy::TYPE_SUBDOCUMENT;
3435 case nsIContentPolicy::TYPE_INTERNAL_AUDIO:
3436 case nsIContentPolicy::TYPE_INTERNAL_VIDEO:
3437 case nsIContentPolicy::TYPE_INTERNAL_TRACK:
3438 return ExtContentPolicy::TYPE_MEDIA;
3440 case nsIContentPolicy::TYPE_INTERNAL_XMLHTTPREQUEST:
3441 case nsIContentPolicy::TYPE_INTERNAL_EVENTSOURCE:
3442 return ExtContentPolicy::TYPE_XMLHTTPREQUEST;
3444 case nsIContentPolicy::TYPE_INTERNAL_IMAGE:
3445 case nsIContentPolicy::TYPE_INTERNAL_IMAGE_PRELOAD:
3446 case nsIContentPolicy::TYPE_INTERNAL_IMAGE_FAVICON:
3447 return ExtContentPolicy::TYPE_IMAGE;
3449 case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET:
3450 case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD:
3451 return ExtContentPolicy::TYPE_STYLESHEET;
3453 case nsIContentPolicy::TYPE_INTERNAL_DTD:
3454 case nsIContentPolicy::TYPE_INTERNAL_FORCE_ALLOWED_DTD:
3455 return ExtContentPolicy::TYPE_DTD;
3457 case nsIContentPolicy::TYPE_INTERNAL_FONT_PRELOAD:
3458 return ExtContentPolicy::TYPE_FONT;
3460 case nsIContentPolicy::TYPE_INTERNAL_FETCH_PRELOAD:
3461 return ExtContentPolicy::TYPE_FETCH;
3463 default:
3464 return static_cast<ExtContentPolicyType>(aType);
3468 class MOZ_RAII nsAutoScriptBlocker {
3469 public:
3470 explicit nsAutoScriptBlocker() { nsContentUtils::AddScriptBlocker(); }
3471 ~nsAutoScriptBlocker() { nsContentUtils::RemoveScriptBlocker(); }
3473 private:
3476 class MOZ_STACK_CLASS nsAutoScriptBlockerSuppressNodeRemoved
3477 : public nsAutoScriptBlocker {
3478 public:
3479 nsAutoScriptBlockerSuppressNodeRemoved() {
3480 ++nsContentUtils::sDOMNodeRemovedSuppressCount;
3482 ~nsAutoScriptBlockerSuppressNodeRemoved() {
3483 --nsContentUtils::sDOMNodeRemovedSuppressCount;
3487 namespace mozilla {
3488 namespace dom {
3490 class TreeOrderComparator {
3491 public:
3492 bool Equals(nsINode* aElem1, nsINode* aElem2) const {
3493 return aElem1 == aElem2;
3495 bool LessThan(nsINode* aElem1, nsINode* aElem2) const {
3496 return nsContentUtils::PositionIsBefore(aElem1, aElem2);
3500 } // namespace dom
3501 } // namespace mozilla
3503 #define NS_INTERFACE_MAP_ENTRY_TEAROFF(_interface, _allocator) \
3504 if (aIID.Equals(NS_GET_IID(_interface))) { \
3505 foundInterface = static_cast<_interface*>(_allocator); \
3506 if (!foundInterface) { \
3507 *aInstancePtr = nullptr; \
3508 return NS_ERROR_OUT_OF_MEMORY; \
3510 } else
3513 * In the following helper macros we exploit the fact that the result of a
3514 * series of additions will not be finite if any one of the operands in the
3515 * series is not finite.
3517 #define NS_ENSURE_FINITE(f, rv) \
3518 if (!mozilla::IsFinite(f)) { \
3519 return (rv); \
3522 #define NS_ENSURE_FINITE2(f1, f2, rv) \
3523 if (!mozilla::IsFinite((f1) + (f2))) { \
3524 return (rv); \
3527 #define NS_ENSURE_FINITE4(f1, f2, f3, f4, rv) \
3528 if (!mozilla::IsFinite((f1) + (f2) + (f3) + (f4))) { \
3529 return (rv); \
3532 #define NS_ENSURE_FINITE5(f1, f2, f3, f4, f5, rv) \
3533 if (!mozilla::IsFinite((f1) + (f2) + (f3) + (f4) + (f5))) { \
3534 return (rv); \
3537 #define NS_ENSURE_FINITE6(f1, f2, f3, f4, f5, f6, rv) \
3538 if (!mozilla::IsFinite((f1) + (f2) + (f3) + (f4) + (f5) + (f6))) { \
3539 return (rv); \
3542 // Deletes a linked list iteratively to avoid blowing up the stack (bug 460444).
3543 #define NS_CONTENT_DELETE_LIST_MEMBER(type_, ptr_, member_) \
3545 type_* cur = (ptr_)->member_; \
3546 (ptr_)->member_ = nullptr; \
3547 while (cur) { \
3548 type_* next = cur->member_; \
3549 cur->member_ = nullptr; \
3550 delete cur; \
3551 cur = next; \
3555 #endif /* nsContentUtils_h___ */