Add an experimental API to find elements across shadow boundaries
authorrniwa@webkit.org <rniwa@webkit.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 18 Nov 2016 05:30:24 +0000 (05:30 +0000)
committerrniwa@webkit.org <rniwa@webkit.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 18 Nov 2016 05:30:24 +0000 (05:30 +0000)
https://bugs.webkit.org/show_bug.cgi?id=164851
<rdar://problem/28220092>

Reviewed by Sam Weinig.

Source/JavaScriptCore:

* runtime/CommonIdentifiers.h:

Source/WebCore:

Add window.collectMatchingElementsInFlatTree(Node node, DOMString selectors)
as an experimental API which finds a list of elements that matches the given CSS selectors
and expose it to a JSWorld on which WKBundleScriptWorldMakeAllShadowRootsOpen was called.

No new tests. More test cases are added to WebKit2.InjectedBundleMakeAllShadowRootsOpen.

* bindings/scripts/CodeGeneratorJS.pm:
(NeedsRuntimeCheck): Added. Abstracts checks for EnabledAtRuntime and EnabledForWorld.
(OperationShouldBeOnInstance):
(GeneratePropertiesHashTable):
(GetRuntimeEnableFunctionName): Use worldForDOMObject(this).condition() for EnabledForWorld.
Also split the line for EnabledAtRuntime and EnabledAtRuntime for a better readability.
(GenerateImplementation):
(addIterableProperties):
* bindings/scripts/IDLAttributes.txt:
* bindings/scripts/preprocess-idls.pl:
(GenerateConstructorAttribute):
* bindings/scripts/test/JS/JSTestGlobalObject.cpp:
(WebCore::JSTestGlobalObject::finishCreation):
(WebCore::jsTestGlobalObjectInstanceFunctionEnabledInSpecificWorld):
(WebCore::jsTestGlobalObjectInstanceFunctionEnabledInSpecificWorldCaller):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjPrototype::finishCreation):
(WebCore::jsTestObjPrototypeFunctionWorldSpecificMethod):
(WebCore::jsTestObjPrototypeFunctionWorldSpecificMethodCaller):
* bindings/scripts/test/TestGlobalObject.idl: Added a test case.
* bindings/scripts/test/TestObj.idl: Ditto.
* page/DOMWindow.cpp:
(WebCore::DOMWindow::collectMatchingElementsInFlatTree): Added. Implements the feature by
calling SelectorQuery's matches on a node yielded by ComposedTreeIterator.
* page/DOMWindow.h:
* page/DOMWindow.idl:

Tools:

Added test cases for window.collectMatchingElementsInFlatTree to WebKit2.InjectedBundleMakeAllShadowRootOpen.

* TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
* TestWebKitAPI/Tests/WebKit2/InjectedBundleMakeAllShadowRoot*s*Open_Bundle.cpp: Renamed
from InjectedBundleMakeAllShadowRootOpen_Bundle.cpp.
(TestWebKitAPI::InjectedBundleMakeAllShadowRootOpenTest::initialize): Added test cases for
window.collectMatchingElementsInFlatTree by calling alert() many times.
* TestWebKitAPI/Tests/WebKit2/InjectedBundleMakeAllShadowRootsOpen.cpp:
(TestWebKitAPI::runJavaScriptAlert): Added expectations for multiple test cases. Each test case
finishes with a call to alert, and moves testNumber forward.
(TestWebKitAPI::TEST): Use the newly added closed-shadow-tree-test.html
* TestWebKitAPI/Tests/WebKit2/closed-shadow-tree-test.html: Added. Creates a shadow tree with slots
and tests that window.collectMatchingElementsInFlatTree is not present when
an event named "testnormalworld" is dispatched by the injected bundle.

git-svn-id: https://svn.webkit.org/repository/webkit/trunk@208878 268f45cc-cd09-0410-ab3c-d52691b4dbfc

18 files changed:
Source/JavaScriptCore/ChangeLog
Source/JavaScriptCore/runtime/CommonIdentifiers.h
Source/WebCore/ChangeLog
Source/WebCore/bindings/scripts/CodeGeneratorJS.pm
Source/WebCore/bindings/scripts/IDLAttributes.txt
Source/WebCore/bindings/scripts/preprocess-idls.pl
Source/WebCore/bindings/scripts/test/JS/JSTestGlobalObject.cpp
Source/WebCore/bindings/scripts/test/JS/JSTestObj.cpp
Source/WebCore/bindings/scripts/test/TestGlobalObject.idl
Source/WebCore/bindings/scripts/test/TestObj.idl
Source/WebCore/page/DOMWindow.cpp
Source/WebCore/page/DOMWindow.h
Source/WebCore/page/DOMWindow.idl
Tools/ChangeLog
Tools/TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj
Tools/TestWebKitAPI/Tests/WebKit2/InjectedBundleMakeAllShadowRootsOpen.cpp
Tools/TestWebKitAPI/Tests/WebKit2/InjectedBundleMakeAllShadowRootsOpen_Bundle.cpp [moved from Tools/TestWebKitAPI/Tests/WebKit2/InjectedBundleMakeAllShadowRootOpen_Bundle.cpp with 66% similarity]
Tools/TestWebKitAPI/Tests/WebKit2/closed-shadow-tree-test.html [new file with mode: 0644]

index ed2be2a..0320d44 100644 (file)
@@ -1,3 +1,13 @@
+2016-11-17  Ryosuke Niwa  <rniwa@webkit.org>
+
+        Add an experimental API to find elements across shadow boundaries
+        https://bugs.webkit.org/show_bug.cgi?id=164851
+        <rdar://problem/28220092>
+
+        Reviewed by Sam Weinig.
+
+        * runtime/CommonIdentifiers.h:
+
 2016-11-17  Yusuke Suzuki  <utatane.tea@gmail.com>
 
         [JSC] Drop arguments.caller
index d51361b..96636f6 100644 (file)
     macro(value) \
     macro(valueOf) \
     macro(webkit) \
+    macro(collectMatchingElementsInFlatTree) \
     macro(webkitIDBCursor) \
     macro(webkitIDBDatabase) \
     macro(webkitIDBFactory) \
index 1efa174..80eb626 100644 (file)
@@ -1,3 +1,44 @@
+2016-11-17  Ryosuke Niwa  <rniwa@webkit.org>
+
+        Add an experimental API to find elements across shadow boundaries
+        https://bugs.webkit.org/show_bug.cgi?id=164851
+        <rdar://problem/28220092>
+
+        Reviewed by Sam Weinig.
+
+        Add window.collectMatchingElementsInFlatTree(Node node, DOMString selectors)
+        as an experimental API which finds a list of elements that matches the given CSS selectors
+        and expose it to a JSWorld on which WKBundleScriptWorldMakeAllShadowRootsOpen was called.
+
+        No new tests. More test cases are added to WebKit2.InjectedBundleMakeAllShadowRootsOpen.
+
+        * bindings/scripts/CodeGeneratorJS.pm:
+        (NeedsRuntimeCheck): Added. Abstracts checks for EnabledAtRuntime and EnabledForWorld.
+        (OperationShouldBeOnInstance):
+        (GeneratePropertiesHashTable):
+        (GetRuntimeEnableFunctionName): Use worldForDOMObject(this).condition() for EnabledForWorld.
+        Also split the line for EnabledAtRuntime and EnabledAtRuntime for a better readability.
+        (GenerateImplementation):
+        (addIterableProperties):
+        * bindings/scripts/IDLAttributes.txt:
+        * bindings/scripts/preprocess-idls.pl:
+        (GenerateConstructorAttribute):
+        * bindings/scripts/test/JS/JSTestGlobalObject.cpp:
+        (WebCore::JSTestGlobalObject::finishCreation):
+        (WebCore::jsTestGlobalObjectInstanceFunctionEnabledInSpecificWorld):
+        (WebCore::jsTestGlobalObjectInstanceFunctionEnabledInSpecificWorldCaller):
+        * bindings/scripts/test/JS/JSTestObj.cpp:
+        (WebCore::JSTestObjPrototype::finishCreation):
+        (WebCore::jsTestObjPrototypeFunctionWorldSpecificMethod):
+        (WebCore::jsTestObjPrototypeFunctionWorldSpecificMethodCaller):
+        * bindings/scripts/test/TestGlobalObject.idl: Added a test case.
+        * bindings/scripts/test/TestObj.idl: Ditto.
+        * page/DOMWindow.cpp:
+        (WebCore::DOMWindow::collectMatchingElementsInFlatTree): Added. Implements the feature by
+        calling SelectorQuery's matches on a node yielded by ComposedTreeIterator.
+        * page/DOMWindow.h:
+        * page/DOMWindow.idl:
+
 2016-11-17  Sam Weinig  <sam@webkit.org>
 
         [WebIDL] Add support for ByteString
index 9d15050..6be75ef 100644 (file)
@@ -693,6 +693,13 @@ sub AttributeShouldBeOnInstance
     return 0;
 }
 
+sub NeedsRuntimeCheck
+{
+    my $interface = shift;
+    return $interface->extendedAttributes->{EnabledAtRuntime}
+        || $interface->extendedAttributes->{EnabledForWorld};
+}
+
 # https://heycam.github.io/webidl/#es-operations
 sub OperationShouldBeOnInstance
 {
@@ -702,7 +709,7 @@ sub OperationShouldBeOnInstance
     return 1 if IsGlobalOrPrimaryGlobalInterface($interface);
 
     # FIXME: The bindings generator does not support putting runtime-enabled operations on the instance yet (except for global objects).
-    return 0 if $function->extendedAttributes->{EnabledAtRuntime};
+    return 0 if NeedsRuntimeCheck($function);
 
     # [Unforgeable] operations should be on the instance. https://heycam.github.io/webidl/#Unforgeable
     return 1 if IsUnforgeable($interface, $function);
@@ -1875,7 +1882,7 @@ sub GeneratePropertiesHashTable
         next if AttributeShouldBeOnInstance($interface, $attribute) != $isInstance;
 
         # Global objects add RuntimeEnabled attributes after creation so do not add them to the static table.
-        if ($isInstance && $attribute->extendedAttributes->{EnabledAtRuntime}) {
+        if ($isInstance && NeedsRuntimeCheck($attribute)) {
             $propertyCount -= 1;
             next;
         }
@@ -1904,7 +1911,7 @@ sub GeneratePropertiesHashTable
         my $conditional = $attribute->extendedAttributes->{Conditional};
         $conditionals->{$name} = $conditional if $conditional;
 
-        if ($attribute->extendedAttributes->{EnabledAtRuntime}) {
+        if (NeedsRuntimeCheck($attribute)) {
             push(@$runtimeEnabledAttributes, $attribute);
         }
     }
@@ -1920,7 +1927,7 @@ sub GeneratePropertiesHashTable
         next if $function->name eq "[Symbol.Iterator]";
 
         # Global objects add RuntimeEnabled operations after creation so do not add them to the static table.
-        if ($isInstance && $function->extendedAttributes->{EnabledAtRuntime}) {
+        if ($isInstance && NeedsRuntimeCheck($function)) {
             $propertyCount -= 1;
             next;
         }
@@ -1947,7 +1954,7 @@ sub GeneratePropertiesHashTable
         my $conditional = getConditionalForFunctionConsideringOverloads($function);
         $conditionals->{$name} = $conditional if $conditional;
 
-        if ($function->extendedAttributes->{EnabledAtRuntime}) {
+        if (NeedsRuntimeCheck($function)) {
             push(@$runtimeEnabledFunctions, $function);
         }
     }
@@ -2511,8 +2518,16 @@ sub GetRuntimeEnableFunctionName
 {
     my $context = shift;
 
+    AddToImplIncludes("RuntimeEnabledFeatures.h");
+    
+    if ($context->extendedAttributes->{EnabledForWorld}) {
+        return "worldForDOMObject(this)." . ToMethodName($context->extendedAttributes->{EnabledForWorld});
+    }
+
     # If a parameter is given (e.g. "EnabledAtRuntime=FeatureName") return the RuntimeEnabledFeatures::sharedFeatures().{FeatureName}Enabled() method.
-    return "RuntimeEnabledFeatures::sharedFeatures()." . ToMethodName($context->extendedAttributes->{EnabledAtRuntime}) . "Enabled" if ($context->extendedAttributes->{EnabledAtRuntime} && $context->extendedAttributes->{EnabledAtRuntime} ne "VALUE_IS_MISSING");
+    if ($context->extendedAttributes->{EnabledAtRuntime} && $context->extendedAttributes->{EnabledAtRuntime} ne "VALUE_IS_MISSING") {
+        return "RuntimeEnabledFeatures::sharedFeatures()." . ToMethodName($context->extendedAttributes->{EnabledAtRuntime}) . "Enabled";
+    }
 
     # Otherwise return a function named RuntimeEnabledFeatures::sharedFeatures().{methodName}Enabled().
     return "RuntimeEnabledFeatures::sharedFeatures()." . ToMethodName($context->name) . "Enabled";
@@ -3000,10 +3015,9 @@ sub GenerateImplementation
 
     # Support for RuntimeEnabled attributes on instances.
     foreach my $attribute (@{$interface->attributes}) {
-        next unless $attribute->extendedAttributes->{EnabledAtRuntime};
+        next unless NeedsRuntimeCheck($attribute);
         next unless AttributeShouldBeOnInstance($interface, $attribute);
 
-        AddToImplIncludes("RuntimeEnabledFeatures.h");
         my $conditionalString = $codeGenerator->GenerateConditionalString($attribute);
         push(@implContent, "#if ${conditionalString}\n") if $conditionalString;
         my $enable_function = GetRuntimeEnableFunctionName($attribute);
@@ -3035,11 +3049,10 @@ sub GenerateImplementation
 
     # Support for RuntimeEnabled operations on instances.
     foreach my $function (@{$interface->functions}) {
-        next unless $function->extendedAttributes->{EnabledAtRuntime};
+        next unless NeedsRuntimeCheck($function);
         next unless OperationShouldBeOnInstance($interface, $function);
         next if $function->{overloadIndex} && $function->{overloadIndex} > 1;
 
-        AddToImplIncludes("RuntimeEnabledFeatures.h");
         my $conditionalString = $codeGenerator->GenerateConditionalString($function);
         push(@implContent, "#if ${conditionalString}\n") if $conditionalString;
         my $enable_function = GetRuntimeEnableFunctionName($function);
@@ -5027,8 +5040,7 @@ sub addIterableProperties()
     my $interface = shift;
     my $className = shift;
 
-    if ($interface->iterable->extendedAttributes->{EnabledAtRuntime}) {
-        AddToImplIncludes("RuntimeEnabledFeatures.h");
+    if (NeedsRuntimeCheck($interface->iterable)) {
         my $enable_function = GetRuntimeEnableFunctionName($interface->iterable);
         push(@implContent, "    if (${enable_function}())\n    ");
     }
index 24307ba..1ea267f 100644 (file)
@@ -59,6 +59,7 @@ DoNotCheckSecurityOnSetter
 DocumentEventHandler
 EnabledAtRuntime=*
 EnabledBySetting=*
+EnabledForWorld=*
 EnforceRange
 ExportMacro=WEBCORE_EXPORT|WEBCORE_TESTSUPPORT_EXPORT
 ExportToWrappedFunction
index 73715ee..a984ab7 100644 (file)
@@ -246,7 +246,7 @@ sub GenerateConstructorAttribute
     my $code = "    ";
     my @extendedAttributesList;
     foreach my $attributeName (sort keys %{$extendedAttributes}) {
-      next unless ($attributeName eq "Conditional" || $attributeName eq "EnabledAtRuntime" || $attributeName eq "EnabledBySetting" || $attributeName eq "PrivateIdentifier" || $attributeName eq "PublicIdentifier");
+      next unless ($attributeName eq "Conditional" || $attributeName eq "EnabledAtRuntime" || $attributeName eq "EnabledForWorld" || $attributeName eq "EnabledBySetting" || $attributeName eq "PrivateIdentifier" || $attributeName eq "PublicIdentifier");
       my $extendedAttribute = $attributeName;
       $extendedAttribute .= "=" . $extendedAttributes->{$attributeName} unless $extendedAttributes->{$attributeName} eq "VALUE_IS_MISSING";
       push(@extendedAttributesList, $extendedAttribute);
index a2b4637..e618200 100644 (file)
@@ -44,6 +44,7 @@ JSC::EncodedJSValue JSC_HOST_CALL jsTestGlobalObjectInstanceFunctionRegularOpera
 #if ENABLE(TEST_FEATURE)
 JSC::EncodedJSValue JSC_HOST_CALL jsTestGlobalObjectInstanceFunctionEnabledAtRuntimeOperation(JSC::ExecState*);
 #endif
+JSC::EncodedJSValue JSC_HOST_CALL jsTestGlobalObjectInstanceFunctionEnabledInSpecificWorld(JSC::ExecState*);
 #if ENABLE(TEST_FEATURE)
 JSC::EncodedJSValue JSC_HOST_CALL jsTestGlobalObjectInstanceFunctionTestPrivateFunction(JSC::ExecState*);
 #endif
@@ -159,6 +160,8 @@ void JSTestGlobalObject::finishCreation(VM& vm)
     if (RuntimeEnabledFeatures::sharedFeatures().testFeatureEnabled())
         putDirectNativeFunction(vm, this, vm.propertyNames->enabledAtRuntimeOperation, 1, jsTestGlobalObjectInstanceFunctionEnabledAtRuntimeOperation, NoIntrinsic, attributesForStructure(JSC::Function));
 #endif
+    if (worldForDOMObject(this).specificWorld())
+        putDirectNativeFunction(vm, this, vm.propertyNames->enabledInSpecificWorld, 1, jsTestGlobalObjectInstanceFunctionEnabledInSpecificWorld, NoIntrinsic, attributesForStructure(JSC::Function));
 #if ENABLE(TEST_FEATURE)
     if (RuntimeEnabledFeatures::sharedFeatures().testFeatureEnabled())
         putDirectNativeFunction(vm, this, static_cast<JSVMClientData*>(vm.clientData)->builtinNames().testPrivateFunctionPrivateName(), 0, jsTestGlobalObjectInstanceFunctionTestPrivateFunction, NoIntrinsic, attributesForStructure(JSC::Function));
@@ -451,6 +454,26 @@ EncodedJSValue JSC_HOST_CALL jsTestGlobalObjectInstanceFunctionEnabledAtRuntimeO
 }
 #endif
 
+static inline JSC::EncodedJSValue jsTestGlobalObjectInstanceFunctionEnabledInSpecificWorldCaller(JSC::ExecState*, JSTestGlobalObject*, JSC::ThrowScope&);
+
+EncodedJSValue JSC_HOST_CALL jsTestGlobalObjectInstanceFunctionEnabledInSpecificWorld(ExecState* state)
+{
+    return BindingCaller<JSTestGlobalObject>::callOperation<jsTestGlobalObjectInstanceFunctionEnabledInSpecificWorldCaller>(state, "enabledInSpecificWorld");
+}
+
+static inline JSC::EncodedJSValue jsTestGlobalObjectInstanceFunctionEnabledInSpecificWorldCaller(JSC::ExecState* state, JSTestGlobalObject* castedThis, JSC::ThrowScope& throwScope)
+{
+    UNUSED_PARAM(state);
+    UNUSED_PARAM(throwScope);
+    auto& impl = castedThis->wrapped();
+    if (UNLIKELY(state->argumentCount() < 1))
+        return throwVMError(state, throwScope, createNotEnoughArgumentsError(state));
+    auto testParam = convert<IDLLong>(*state, state->uncheckedArgument(0), IntegerConversionConfiguration::Normal);
+    RETURN_IF_EXCEPTION(throwScope, encodedJSValue());
+    impl.enabledInSpecificWorld(WTFMove(testParam));
+    return JSValue::encode(jsUndefined());
+}
+
 #if ENABLE(TEST_FEATURE)
 static inline JSC::EncodedJSValue jsTestGlobalObjectInstanceFunctionTestPrivateFunctionCaller(JSC::ExecState*, JSTestGlobalObject*, JSC::ThrowScope&);
 
index 4692665..bd36f59 100644 (file)
@@ -938,6 +938,7 @@ template<> TestObj::ConditionalDictionaryC convertDictionary<TestObj::Conditiona
 #if ENABLE(TEST_FEATURE)
 JSC::EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionEnabledAtRuntimeOperation(JSC::ExecState*);
 #endif
+JSC::EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionWorldSpecificMethod(JSC::ExecState*);
 JSC::EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionVoidMethod(JSC::ExecState*);
 JSC::EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionVoidMethodWithArgs(JSC::ExecState*);
 JSC::EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionByteMethod(JSC::ExecState*);
@@ -1545,6 +1546,7 @@ static const HashTableValue JSTestObjPrototypeTableValues[] =
 #else
     { 0, 0, NoIntrinsic, { 0, 0 } },
 #endif
+    { "worldSpecificMethod", JSC::Function, NoIntrinsic, { (intptr_t)static_cast<NativeFunction>(jsTestObjPrototypeFunctionWorldSpecificMethod), (intptr_t) (1) } },
     { "voidMethod", JSC::Function, NoIntrinsic, { (intptr_t)static_cast<NativeFunction>(jsTestObjPrototypeFunctionVoidMethod), (intptr_t) (0) } },
     { "voidMethodWithArgs", JSC::Function, NoIntrinsic, { (intptr_t)static_cast<NativeFunction>(jsTestObjPrototypeFunctionVoidMethodWithArgs), (intptr_t) (3) } },
     { "byteMethod", JSC::Function, NoIntrinsic, { (intptr_t)static_cast<NativeFunction>(jsTestObjPrototypeFunctionByteMethod), (intptr_t) (0) } },
@@ -1726,6 +1728,11 @@ void JSTestObjPrototype::finishCreation(VM& vm)
         JSObject::deleteProperty(this, globalObject()->globalExec(), propertyName);
     }
 #endif
+    if (!worldForDOMObject(this).someWorld()) {
+        Identifier propertyName = Identifier::fromString(&vm, reinterpret_cast<const LChar*>("worldSpecificMethod"), strlen("worldSpecificMethod"));
+        VM::DeletePropertyModeScope scope(vm, VM::DeletePropertyMode::IgnoreConfigurable);
+        JSObject::deleteProperty(this, globalObject()->globalExec(), propertyName);
+    }
 #if ENABLE(TEST_FEATURE)
     if (!RuntimeEnabledFeatures::sharedFeatures().testFeatureEnabled()) {
         Identifier propertyName = Identifier::fromString(&vm, reinterpret_cast<const LChar*>("enabledAtRuntimeAttribute"), strlen("enabledAtRuntimeAttribute"));
@@ -4711,6 +4718,26 @@ EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionEnabledAtRuntimeOperation
 }
 #endif
 
+static inline JSC::EncodedJSValue jsTestObjPrototypeFunctionWorldSpecificMethodCaller(JSC::ExecState*, JSTestObj*, JSC::ThrowScope&);
+
+EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionWorldSpecificMethod(ExecState* state)
+{
+    return BindingCaller<JSTestObj>::callOperation<jsTestObjPrototypeFunctionWorldSpecificMethodCaller>(state, "worldSpecificMethod");
+}
+
+static inline JSC::EncodedJSValue jsTestObjPrototypeFunctionWorldSpecificMethodCaller(JSC::ExecState* state, JSTestObj* castedThis, JSC::ThrowScope& throwScope)
+{
+    UNUSED_PARAM(state);
+    UNUSED_PARAM(throwScope);
+    auto& impl = castedThis->wrapped();
+    if (UNLIKELY(state->argumentCount() < 1))
+        return throwVMError(state, throwScope, createNotEnoughArgumentsError(state));
+    auto testParam = convert<IDLLong>(*state, state->uncheckedArgument(0), IntegerConversionConfiguration::Normal);
+    RETURN_IF_EXCEPTION(throwScope, encodedJSValue());
+    impl.worldSpecificMethod(WTFMove(testParam));
+    return JSValue::encode(jsUndefined());
+}
+
 static inline JSC::EncodedJSValue jsTestObjPrototypeFunctionVoidMethodCaller(JSC::ExecState*, JSTestObj*, JSC::ThrowScope&);
 
 EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionVoidMethod(ExecState* state)
index c941b34..1245aad 100644 (file)
@@ -35,6 +35,8 @@
     [Conditional=TEST_FEATURE, EnabledAtRuntime=TestFeature] void enabledAtRuntimeOperation(DOMString testParam);
     [Conditional=TEST_FEATURE, EnabledAtRuntime=TestFeature] void enabledAtRuntimeOperation(long testParam);
 
+    [EnabledForWorld=specificWorld] void enabledInSpecificWorld(long testParam);
+
     [PrivateIdentifier, Conditional=TEST_FEATURE, EnabledAtRuntime=TestFeature] void testPrivateFunction();
     [JSBuiltin, Conditional=TEST_FEATURE, EnabledAtRuntime=TestFeature] void testJSBuiltinFunction();
 };
index 2c71e83..599eba8 100644 (file)
@@ -109,6 +109,8 @@ enum TestConfidence { "high", "kinda-low" };
     [Conditional=TEST_FEATURE, EnabledAtRuntime=TestFeature] void enabledAtRuntimeOperation(DOMString testParam);
     [Conditional=TEST_FEATURE, EnabledAtRuntime=TestFeature] void enabledAtRuntimeOperation(long testParam);
 
+    [EnabledForWorld=someWorld] void worldSpecificMethod(long testParam);
+
     // TypedArray attribute
     attribute Float32Array typedArrayAttr;
 
index ed5881d..2a9393a 100644 (file)
@@ -35,6 +35,7 @@
 #include "CSSRuleList.h"
 #include "Chrome.h"
 #include "ChromeClient.h"
+#include "ComposedTreeIterator.h"
 #include "ContentExtensionActions.h"
 #include "ContentExtensionRule.h"
 #include "Crypto.h"
 #include "SecurityOrigin.h"
 #include "SecurityOriginData.h"
 #include "SecurityPolicy.h"
+#include "SelectorQuery.h"
 #include "SerializedScriptValue.h"
 #include "Settings.h"
+#include "StaticNodeList.h"
 #include "Storage.h"
 #include "StorageArea.h"
 #include "StorageNamespace.h"
@@ -632,6 +635,33 @@ CustomElementRegistry& DOMWindow::ensureCustomElementRegistry()
     return *m_customElementRegistry;
 }
 
+ExceptionOr<Ref<NodeList>> DOMWindow::collectMatchingElementsInFlatTree(Node& scope, const String& selectors)
+{
+    if (!m_frame)
+        return Exception { NOT_SUPPORTED_ERR };
+
+    Document* document = m_frame->document();
+    if (!document)
+        return Exception { NOT_SUPPORTED_ERR };
+
+    auto queryOrException = document->selectorQueryForString(selectors);
+    if (queryOrException.hasException())
+        return queryOrException.releaseException();
+
+    if (!is<ContainerNode>(scope))
+        return Ref<NodeList> { StaticElementList::create() };
+
+    SelectorQuery& query = queryOrException.releaseReturnValue();
+
+    Vector<Ref<Element>> result;
+    for (auto& node : composedTreeDescendants(downcast<ContainerNode>(scope))) {
+        if (is<Element>(node) && query.matches(downcast<Element>(node)))
+            result.append(downcast<Element>(node));
+    }
+
+    return Ref<NodeList> { StaticElementList::create(WTFMove(result)) };
+}
+
 #if ENABLE(ORIENTATION_EVENTS)
 
 int DOMWindow::orientation() const
index de7ad41..c9f9bbc 100644 (file)
@@ -71,6 +71,7 @@ class MessageEvent;
 class MessagePort;
 class Navigator;
 class Node;
+class NodeList;
 class Page;
 class PageConsoleClient;
 class Performance;
@@ -295,6 +296,8 @@ public:
     CustomElementRegistry* customElementRegistry() { return m_customElementRegistry.get(); }
     CustomElementRegistry& ensureCustomElementRegistry();
 
+    ExceptionOr<Ref<NodeList>> collectMatchingElementsInFlatTree(Node&, const String& selectors);
+
 #if ENABLE(ORIENTATION_EVENTS)
     // This is the interface orientation in degrees. Some examples are:
     //  0 is straight up; -90 is when the device is rotated 90 clockwise;
index 0a32b69..d4b59c4 100644 (file)
 
     [EnabledAtRuntime=CustomElements, ImplementedAs=ensureCustomElementRegistry] readonly attribute CustomElementRegistry customElements;
 
+    [MayThrowException, EnabledForWorld=shadowRootIsAlwaysOpen]
+    NodeList collectMatchingElementsInFlatTree(Node scope, DOMString selectors);
+
     // Event handlers unique to Element and DOMWindow.
     // FIXME: Should these be exposed on Document as well (and therefore moved to GlobalEventHandlers.idl)?
     [NotEnumerable] attribute EventHandler onanimationend;
index f67b54f..a669318 100644 (file)
@@ -1,3 +1,26 @@
+2016-11-17  Ryosuke Niwa  <rniwa@webkit.org>
+
+        Add an experimental API to find elements across shadow boundaries
+        https://bugs.webkit.org/show_bug.cgi?id=164851
+        <rdar://problem/28220092>
+
+        Reviewed by Sam Weinig.
+
+        Added test cases for window.collectMatchingElementsInFlatTree to WebKit2.InjectedBundleMakeAllShadowRootOpen.
+
+        * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
+        * TestWebKitAPI/Tests/WebKit2/InjectedBundleMakeAllShadowRoot*s*Open_Bundle.cpp: Renamed
+        from InjectedBundleMakeAllShadowRootOpen_Bundle.cpp.
+        (TestWebKitAPI::InjectedBundleMakeAllShadowRootOpenTest::initialize): Added test cases for
+        window.collectMatchingElementsInFlatTree by calling alert() many times.
+        * TestWebKitAPI/Tests/WebKit2/InjectedBundleMakeAllShadowRootsOpen.cpp:
+        (TestWebKitAPI::runJavaScriptAlert): Added expectations for multiple test cases. Each test case
+        finishes with a call to alert, and moves testNumber forward.
+        (TestWebKitAPI::TEST): Use the newly added closed-shadow-tree-test.html
+        * TestWebKitAPI/Tests/WebKit2/closed-shadow-tree-test.html: Added. Creates a shadow tree with slots
+        and tests that window.collectMatchingElementsInFlatTree is not present when
+        an event named "testnormalworld" is dispatched by the injected bundle.
+
 2016-11-17  Brady Eidson  <beidson@apple.com>
 
         Add _WKIconLoadingDelegate SPI.
index 54e7e8a..34d539a 100644 (file)
                93F7E86F14DC8E5C00C84A99 /* NewFirstVisuallyNonEmptyLayoutFrames_Bundle.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 93F7E86E14DC8E5B00C84A99 /* NewFirstVisuallyNonEmptyLayoutFrames_Bundle.cpp */; };
                9984FACC1CFFAF60008D198C /* WKWebViewTextInput.mm in Sources */ = {isa = PBXBuildFile; fileRef = 9984FACA1CFFAEEE008D198C /* WKWebViewTextInput.mm */; };
                9984FACE1CFFB090008D198C /* editable-body.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = 9984FACD1CFFB038008D198C /* editable-body.html */; };
-               9B0786A51C5885C300D159E3 /* InjectedBundleMakeAllShadowRootOpen_Bundle.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B0786A41C5885C300D159E3 /* InjectedBundleMakeAllShadowRootOpen_Bundle.cpp */; };
+               9B0786A51C5885C300D159E3 /* InjectedBundleMakeAllShadowRootsOpen_Bundle.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B0786A41C5885C300D159E3 /* InjectedBundleMakeAllShadowRootsOpen_Bundle.cpp */; };
                9B26FCCA159D16DE00CC3765 /* HTMLFormCollectionNamedItem.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = 9B26FCB4159D15E700CC3765 /* HTMLFormCollectionNamedItem.html */; };
+               9B270FEE1DDC2C0B002D53F3 /* closed-shadow-tree-test.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = 9B270FED1DDC25FD002D53F3 /* closed-shadow-tree-test.html */; };
                9B4F8FA7159D52DD002D9F94 /* HTMLCollectionNamedItem.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = 9B4F8FA6159D52CA002D9F94 /* HTMLCollectionNamedItem.html */; };
                9C64DC321D76198A004B598E /* YouTubePluginReplacement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9C64DC311D76198A004B598E /* YouTubePluginReplacement.cpp */; };
                A1146A8D1D2D7115000FE710 /* ContentFiltering.mm in Sources */ = {isa = PBXBuildFile; fileRef = A1146A8A1D2D704F000FE710 /* ContentFiltering.mm */; };
                        dstPath = TestWebKitAPI.resources;
                        dstSubfolderSpec = 7;
                        files = (
+                               9B270FEE1DDC2C0B002D53F3 /* closed-shadow-tree-test.html in Copy Resources */,
                                F4C2AB221DD6D95E00E06D5B /* enormous-video-with-sound.html in Copy Resources */,
                                8349D3C41DB9728E004A9F65 /* link-with-download-attribute.html in Copy Resources */,
                                AD57AC221DA7466E00FF1BDE /* many-iframes.html in Copy Resources */,
                9984FACA1CFFAEEE008D198C /* WKWebViewTextInput.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WKWebViewTextInput.mm; sourceTree = "<group>"; };
                9984FACD1CFFB038008D198C /* editable-body.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = "editable-body.html"; sourceTree = "<group>"; };
                9B0786A21C58830F00D159E3 /* InjectedBundleMakeAllShadowRootsOpen.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = InjectedBundleMakeAllShadowRootsOpen.cpp; sourceTree = "<group>"; };
-               9B0786A41C5885C300D159E3 /* InjectedBundleMakeAllShadowRootOpen_Bundle.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = InjectedBundleMakeAllShadowRootOpen_Bundle.cpp; sourceTree = "<group>"; };
+               9B0786A41C5885C300D159E3 /* InjectedBundleMakeAllShadowRootsOpen_Bundle.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = InjectedBundleMakeAllShadowRootsOpen_Bundle.cpp; sourceTree = "<group>"; };
                9B26FC6B159D061000CC3765 /* HTMLFormCollectionNamedItem.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = HTMLFormCollectionNamedItem.mm; sourceTree = "<group>"; };
                9B26FCB4159D15E700CC3765 /* HTMLFormCollectionNamedItem.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = HTMLFormCollectionNamedItem.html; sourceTree = "<group>"; };
+               9B270FED1DDC25FD002D53F3 /* closed-shadow-tree-test.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = "closed-shadow-tree-test.html"; sourceTree = "<group>"; };
                9B4F8FA3159D52B1002D9F94 /* HTMLCollectionNamedItem.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = HTMLCollectionNamedItem.mm; sourceTree = "<group>"; };
                9B4F8FA6159D52CA002D9F94 /* HTMLCollectionNamedItem.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = HTMLCollectionNamedItem.html; sourceTree = "<group>"; };
                9B79164F1BD89D0D00D50B8F /* FirstResponderScrollingPosition.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = FirstResponderScrollingPosition.mm; sourceTree = "<group>"; };
                                378E64751632655D00B6C676 /* InjectedBundleFrameHitTest_Bundle.cpp */,
                                F660AA1215A619C8003A1243 /* InjectedBundleInitializationUserDataCallbackWins.cpp */,
                                F660AA1415A61ABF003A1243 /* InjectedBundleInitializationUserDataCallbackWins_Bundle.cpp */,
-                               9B0786A41C5885C300D159E3 /* InjectedBundleMakeAllShadowRootOpen_Bundle.cpp */,
+                               9B0786A41C5885C300D159E3 /* InjectedBundleMakeAllShadowRootsOpen_Bundle.cpp */,
                                9B0786A21C58830F00D159E3 /* InjectedBundleMakeAllShadowRootsOpen.cpp */,
                                93D3D19D17B1A84200C7C415 /* LayoutMilestonesWithAllContentInFrame.cpp */,
                                52CB47401448FB9300873995 /* LoadAlternateHTMLStringWithNonDirectoryURL.cpp */,
                                76E182DE15475A8300F1FADD /* auto-submitting-form.html */,
                                7C486BA01AA1254B003F6F9B /* bundle-file.html */,
                                1A50AA1F1A2A4EA500F4C345 /* close-from-within-create-page.html */,
+                               9B270FED1DDC25FD002D53F3 /* closed-shadow-tree-test.html */,
                                290F4274172A1FDE00939FF0 /* custom-protocol-sync-xhr.html */,
                                C5E1AFFD16B22179006CC1F2 /* execCopy.html */,
                                BC2D004A12A9FEB300E732A3 /* file-with-anchor.html */,
                                378E64771632655E00B6C676 /* InjectedBundleFrameHitTest_Bundle.cpp in Sources */,
                                F660AA1515A61ABF003A1243 /* InjectedBundleInitializationUserDataCallbackWins_Bundle.cpp in Sources */,
                                BC575A97126E74F1006F0F12 /* InjectedBundleMain.cpp in Sources */,
-                               9B0786A51C5885C300D159E3 /* InjectedBundleMakeAllShadowRootOpen_Bundle.cpp in Sources */,
+                               9B0786A51C5885C300D159E3 /* InjectedBundleMakeAllShadowRootsOpen_Bundle.cpp in Sources */,
                                33DC89141419579F00747EF7 /* LoadCanceledNoServerRedirectCallback_Bundle.cpp in Sources */,
                                33BE5AF9137B5AAE00705813 /* MouseMoveAfterCrash_Bundle.cpp in Sources */,
                                93F1DB3414DA20870024C362 /* NewFirstVisuallyNonEmptyLayout_Bundle.cpp in Sources */,
index 982e696..9418f85 100644 (file)
@@ -34,6 +34,7 @@
 
 namespace TestWebKitAPI {
 
+static unsigned testNumber = 0;
 static bool done;
 
 static void runJavaScriptAlert(WKPageRef page, WKStringRef alertText, WKFrameRef frame, const void* clientInfo)
@@ -41,9 +42,27 @@ static void runJavaScriptAlert(WKPageRef page, WKStringRef alertText, WKFrameRef
     ASSERT_NOT_NULL(frame);
 
     EXPECT_EQ(page, WKFrameGetPage(frame));
-    EXPECT_WK_STREQ("PASS", alertText);
-
-    done = true;
+    switch (++testNumber) {
+    case 1:
+        EXPECT_WK_STREQ("PASS: shadowRoot created in injected bundle", alertText);
+        break;
+    case 2:
+        EXPECT_WK_STREQ("PASS: shadowRoot created by normal world", alertText);
+        break;
+    case 3:
+        EXPECT_WK_STREQ("PASS: query method exists", alertText);
+        break;
+    case 4:
+        EXPECT_WK_STREQ("PASS: query method was not present in the normal world", alertText);
+        break;
+    case 5:
+        EXPECT_WK_STREQ("Found:1,2,3,4,5,6", alertText);
+        break;
+    case 6:
+        EXPECT_WK_STREQ("Found:2,3,4", alertText);
+        done = true;
+        break;
+    }
 }
 
 TEST(WebKit2, InjectedBundleMakeAllShadowRootOpenTest)
@@ -61,7 +80,7 @@ TEST(WebKit2, InjectedBundleMakeAllShadowRootOpenTest)
 
     WKPageSetPageUIClient(webView.page(), &uiClient.base);
 
-    WKRetainPtr<WKURLRef> url(AdoptWK, Util::createURLForResource("simple", "html"));
+    WKRetainPtr<WKURLRef> url(AdoptWK, Util::createURLForResource("closed-shadow-tree-test", "html"));
     WKPageLoadURL(webView.page(), url.get());
 
     Util::run(&done);
@@ -51,9 +51,27 @@ public:
         WKBundleScriptWorldMakeAllShadowRootsOpen(world);
 
         WKRetainPtr<WKStringRef> source(AdoptWK, WKStringCreateWithUTF8CString(
-            "var element = document.createElement('div');"
-            "element.attachShadow({mode: 'closed'});"
-            "alert(element.shadowRoot ? 'PASS' : 'FAIL');"));
+            "window.onload = function () {\n"
+            "    const element = document.createElement('div');\n"
+            "    const queryMethodName = 'collectMatchingElementsInFlatTree';\n"
+            "    element.attachShadow({mode: 'closed'});\n"
+            // Test 1
+            "    alert(element.shadowRoot ? 'PASS: shadowRoot created in injected bundle' : 'FAIL');\n"
+            // Test 2
+            "    alert(document.querySelector('shadow-host').shadowRoot ? 'PASS: shadowRoot created by normal world' : 'FAIL');\n"
+            // Test 3
+            "    alert(window[queryMethodName] ? 'PASS: query method exists' : 'FAIL');\n"
+            // Test 4
+            "    document.dispatchEvent(new Event('testnormalworld'));\n"
+            // Test 5
+            "    const queryMethod = window[queryMethodName];\n"
+            "    let queryResult = Array.from(queryMethod(document, 'span'));\n"
+            "    alert('Found:' + queryResult.map((span) => span.textContent).join(','));\n"
+            // Test 6
+            "    const innerHost = queryMethod(document, 'inner-host')[0];\n"
+            "    queryResult = Array.from(queryMethod(innerHost, 'span'));\n"
+            "    alert('Found:' + queryResult.map((span) => span.textContent).join(','));\n"
+            "}\n"));
         WKBundleAddUserScript(bundle, pageGroup, world, source.get(), 0, 0, 0, kWKInjectAtDocumentStart, kWKInjectInAllFrames);
     }
 };
diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/closed-shadow-tree-test.html b/Tools/TestWebKitAPI/Tests/WebKit2/closed-shadow-tree-test.html
new file mode 100644 (file)
index 0000000..3a76bfb
--- /dev/null
@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<html>
+<body>
+<shadow-host><span>5</span><span slot="bar">2</span></shadow-host>
+<script>
+const shadowRoot = document.querySelector('shadow-host').attachShadow({mode: 'closed'});
+shadowRoot.innerHTML = `
+    <span>1</span>
+    <inner-host>
+        <slot name="bar" slot="foo"><span>FAIL - named slot fallback</span></slot>
+        <span>FAIL - unassigned content</span>
+        <span slot="foo">3</span>
+    </inner-host>
+    <slot><span>FAIL - default slot fallback</span></slot>
+    <span>6</span>`;
+const innerHost = shadowRoot.querySelector('inner-host');
+innerHost.attachShadow({mode: 'closed'}).innerHTML = `
+    <slot name="foo"></slot>
+    <span>4</span>`;
+
+document.addEventListener('testnormalworld', function () {
+    alert(window.collectMatchingElementsInFlatTree ?
+        'FAIL' : 'PASS: query method was not present in the normal world');
+});
+
+</script>
+</body>
+</html>