1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2  *
3  * This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #include "nsTraversal.h"
8 
9 #include "nsError.h"
10 #include "nsINode.h"
11 #include "mozilla/AutoRestore.h"
12 #include "mozilla/dom/NodeFilterBinding.h"
13 
14 #include "nsGkAtoms.h"
15 
16 using namespace mozilla;
17 using namespace mozilla::dom;
18 
nsTraversal(nsINode * aRoot,uint32_t aWhatToShow,NodeFilter * aFilter)19 nsTraversal::nsTraversal(nsINode* aRoot, uint32_t aWhatToShow,
20                          NodeFilter* aFilter)
21     : mRoot(aRoot),
22       mWhatToShow(aWhatToShow),
23       mFilter(aFilter),
24       mInAcceptNode(false) {
25   NS_ASSERTION(aRoot, "invalid root in call to nsTraversal constructor");
26 }
27 
~nsTraversal()28 nsTraversal::~nsTraversal() { /* destructor code */
29 }
30 
31 /*
32  * Tests if and how a node should be filtered. Uses mWhatToShow and
33  * mFilter to test the node.
34  * @param aNode     Node to test
35  * @param aResult   Whether we succeeded
36  * @returns         Filtervalue. See NodeFilter.webidl
37  */
TestNode(nsINode * aNode,mozilla::ErrorResult & aResult,nsCOMPtr<nsINode> * aUnskippedNode)38 int16_t nsTraversal::TestNode(nsINode* aNode, mozilla::ErrorResult& aResult,
39                               nsCOMPtr<nsINode>* aUnskippedNode) {
40   if (mInAcceptNode) {
41     aResult.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
42     return 0;
43   }
44 
45   uint16_t nodeType = aNode->NodeType();
46 
47   if (nodeType <= 12 && !((1 << (nodeType - 1)) & mWhatToShow)) {
48     return NodeFilter_Binding::FILTER_SKIP;
49   }
50 
51   if (aUnskippedNode) {
52     *aUnskippedNode = aNode;
53   }
54 
55   if (!mFilter) {
56     // No filter, just accept
57     return NodeFilter_Binding::FILTER_ACCEPT;
58   }
59 
60   AutoRestore<bool> inAcceptNode(mInAcceptNode);
61   mInAcceptNode = true;
62   // No need to pass in an execution reason, since the generated default,
63   // "NodeFilter.acceptNode", is pretty much exactly what we'd say anyway.
64   return mFilter->AcceptNode(*aNode, aResult, nullptr,
65                              CallbackObject::eRethrowExceptions);
66 }
67