More is<> and downcast<>, less static_cast<>
authordarin@apple.com <darin@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Mon, 13 Nov 2017 06:12:09 +0000 (06:12 +0000)
committerdarin@apple.com <darin@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Mon, 13 Nov 2017 06:12:09 +0000 (06:12 +0000)
https://bugs.webkit.org/show_bug.cgi?id=179600

Reviewed by Chris Dumez.

Source/JavaScriptCore:

* runtime/JSString.h:
(JSC::jsSubstring): Removed unneeded static_cast; length already returns unsigned.
(JSC::jsSubstringOfResolved): Ditto.

Source/WebCore:

* Modules/fetch/FetchBody.cpp:
(WebCore::FetchBody::extract): Use downcast instead of static_cast.
(WebCore::FetchBody::bodyAsFormData const): Ditto.
* Modules/indexeddb/IDBObjectStore.cpp:
(WebCore::IDBObjectStore::putOrAdd): Ditto.
* Modules/mediastream/CanvasCaptureMediaStreamTrack.cpp:
(WebCore::CanvasCaptureMediaStreamTrack::Source::canvasChanged): Ditto.
* Modules/mediastream/libwebrtc/LibWebRTCPeerConnectionBackend.cpp:
(WebCore::libWebRTCProvider): Ditto.

* accessibility/AccessibilityMediaControls.cpp:
(WebCore::AccessibilityMediaTimeDisplay::stringValue const): Got rid of local
variable and used std::abs instead of fabsf. Did not use downcast here because
it doesn't exist for this class.

* bindings/js/JSEventTargetCustom.h:
(WebCore::IDLOperation<JSEventTarget>::call): Use downcast instead of toDOMWindow.
* dom/DocumentEventQueue.cpp:
(WebCore::DocumentEventQueue::dispatchEvent): Ditto.

* dom/Element.h: Added is/downcast for EventTarget.

* dom/EventContext.cpp:
(WebCore::TouchEventContext::checkReachability const): Use downcast instead
of toNode.
* dom/EventContext.h:
(WebCore::EventContext::isUnreachableNode const): Ditto.
* dom/EventPath.cpp:
(WebCore::shouldEventCrossShadowBoundary): Ditto.
(WebCore::EventPath::setRelatedTarget): Ditto.
(WebCore::EventPath::retargetTouch): Ditto.
(WebCore::EventPath::EventPath): Ditto.

* dom/EventTarget.cpp:
(WebCore::EventTarget::toNode): Deleted.
(WebCore::EventTarget::isNode const): Added.
(WebCore::EventTarget::toDOMWindow): Deleted.
(WebCore::EventTarget::isMessagePort const): Deleted. This was not used.
(WebCore::EventTarget::addEventListener): Use downcast instead of toDOMWindow
and toNode.
* dom/EventTarget.h: Updated for the above.

* dom/MessagePort.h: Deleted unused isMessagePort.

* dom/MouseEvent.cpp:
(WebCore::MouseEvent::toElement const): Use downcast instead of toNode.
Also refactored to make function a little smaller.
(WebCore::MouseEvent::fromElement const): Ditto.

* dom/MouseRelatedEvent.cpp:
(WebCore::MouseRelatedEvent::computeRelativePosition): Use downcast
instead of toNode.

* dom/Node.cpp:
(WebCore::Node::isNode const): Added.
(WebCore::Node::toNode): Deleted.
* dom/Node.h: Updated for the above. Also added SPECIALIZE_TYPE_TRAITS
so we can do is/downcast.

* dom/ScopedEventQueue.cpp:
(WebCore::ScopedEventQueue::enqueueEvent): Use is instead of toNode.
(WebCore::ScopedEventQueue::dispatchEvent const): Use downcast instead of toNode.

* dom/make_names.pl:
(printTypeHelpers): Added support for is/downcast from EventTarget.

* editing/Editor.cpp:
(WebCore::Editor::selectionForCommand): Use is/downcast instead of toNode.
* editing/EditorCommand.cpp:
(WebCore::targetFrame): Ditto.
* html/HTMLAnchorElement.cpp:
(WebCore::appendServerMapMousePosition): Ditto.

* html/HTMLCanvasElement.cpp:
(WebCore::HTMLCanvasElement::createContextWebGL): Use downcast instead of
static_cast.
(WebCore::HTMLCanvasElement::getContextWebGL): Ditto.
(WebCore::HTMLCanvasElement::getImageData): Ditto.

* html/HTMLElement.h: Added support for is/downcast from EventTarget.

* html/HTMLFormElement.cpp:
(WebCore::HTMLFormElement::handleLocalEvents): Use is instead of toNode.
(WebCore::submitElementFromEvent): Deleted. Was a duplicate of findSubmitButton.
(WebCore::HTMLFormElement::prepareForSubmission): Rewrote code that calls
submitElementFromEvent to call findSubmitButton instead. Also don't bother
finding the submit button unless we are going to validate, since all we do
after finding it is reconsider whether we should validate.
(WebCore::HTMLFormElement::findSubmitButton const): Rewrote to use is,
downcast, and lineageOfType rather than a handwritten loop and toNode.
Relies on the fact that the target is an element, never a text node.

* html/HTMLLabelElement.cpp:
(WebCore::HTMLLabelElement::defaultEventHandler): Use is and downcast instead
of toNode.

* html/HTMLPlugInImageElement.cpp:
(WebCore::HTMLPlugInImageElement::partOfSnapshotOverlay const): Changed argument
type to EventTarget so we can do the type checking and casting here instead of at
each of the callers.
* html/HTMLPlugInImageElement.h: Updated for the above.

* html/HTMLSummaryElement.cpp:
(WebCore::isClickableControl): Changed argument type to EventTarget so we can do
the type checking and casting here instead of at each of the callers.
(WebCore::HTMLSummaryElement::defaultEventHandler): Removed call to toNode.

* html/HTMLTextFormControlElement.h: Added support for is/downcast from EventTarget.

* html/MediaDocument.cpp:
(WebCore::MediaDocument::defaultEventHandler): Use is/downcast instead of toNode.
* html/RangeInputType.cpp:
(WebCore::RangeInputType::handleMouseDownEvent): Ditto.
* html/shadow/MediaControlElements.cpp:
(WebCore::MediaControlVolumeSliderContainerElement::defaultEventHandler): Ditto.
(WebCore::MediaControlClosedCaptionsTrackListElement::defaultEventHandler): Ditto.
Also use get instead of find/end.

* html/shadow/MediaControls.cpp:
(WebCore::MediaControls::containsRelatedTarget): Use is/downcast instead of toNode.
* inspector/InspectorFrontendHost.cpp:
(WebCore::InspectorFrontendHost::dispatchEventAsContextMenuEvent): Ditto.
* inspector/agents/InspectorDOMAgent.cpp:
(WebCore::InspectorDOMAgent::didAddEventListener): Ditto.
(WebCore::InspectorDOMAgent::willRemoveEventListener): Ditto.
* page/ContextMenuController.cpp:
(WebCore::ContextMenuController::maybeCreateContextMenu): Ditto.

* page/DOMWindow.cpp:
(WebCore::DOMWindow::toDOMWindow): Deleted.
* page/DOMWindow.h: Updated for the above. Also added SPECIALIZE_TYPE_TRAITS
so we can do is/downcast.

* page/EventHandler.cpp:
(WebCore::EventHandler::handleTouchEvent): Use is/downcast instead of toNode.

* platform/graphics/WidthCache.h:
(WebCore::WidthCache::add): Removed unneeded static_cast; length already returns unsigned.

* rendering/RenderSnapshottedPlugIn.cpp:
(WebCore::RenderSnapshottedPlugIn::handleEvent): Removed unneeded toNode now that
partOfSnapshotOverlay takes an EventTarget.

Source/WebKit:

* WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMPrivate.cpp:
(WebKit::wrap): Use is/downcast.
* WebProcess/WebCoreSupport/gtk/WebEditorClientGtk.cpp:
(WebKit::WebEditorClient::handleKeyboardEvent): Ditto.
* WebProcess/WebCoreSupport/wpe/WebEditorClientWPE.cpp:
(WebKit::WebEditorClient::handleKeyboardEvent): Ditto.
* WebProcess/WebPage/WebPage.cpp:
(WebKit::WebPage::handleEditingKeyboardEvent): Ditto.
* WebProcess/WebPage/mac/WebPageMac.mm:
(WebKit::frameForEvent): Ditto.

Source/WebKitLegacy/mac:

* DOM/DOM.mm:
(kit): Use is/downcast.
* WebCoreSupport/WebEditorClient.mm:
(WebEditorClient::handleKeyboardEvent): Ditto.
(WebEditorClient::handleInputMethodKeydown): Ditto.
* WebView/WebHTMLView.mm:
(-[WebHTMLView _interpretKeyEvent:savingCommands:]): Ditto.

Source/WebKitLegacy/win:

* WebView.cpp:
(WebView::handleEditingKeyboardEvent): Use downcast.

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

58 files changed:
Source/JavaScriptCore/ChangeLog
Source/JavaScriptCore/runtime/JSString.h
Source/WebCore/ChangeLog
Source/WebCore/Modules/fetch/FetchBody.cpp
Source/WebCore/Modules/indexeddb/IDBObjectStore.cpp
Source/WebCore/Modules/mediastream/CanvasCaptureMediaStreamTrack.cpp
Source/WebCore/Modules/mediastream/libwebrtc/LibWebRTCPeerConnectionBackend.cpp
Source/WebCore/accessibility/AccessibilityMediaControls.cpp
Source/WebCore/bindings/js/JSEventTargetCustom.h
Source/WebCore/dom/DocumentEventQueue.cpp
Source/WebCore/dom/Element.h
Source/WebCore/dom/EventContext.cpp
Source/WebCore/dom/EventContext.h
Source/WebCore/dom/EventPath.cpp
Source/WebCore/dom/EventTarget.cpp
Source/WebCore/dom/EventTarget.h
Source/WebCore/dom/MessagePort.h
Source/WebCore/dom/MouseEvent.cpp
Source/WebCore/dom/MouseRelatedEvent.cpp
Source/WebCore/dom/Node.cpp
Source/WebCore/dom/Node.h
Source/WebCore/dom/ScopedEventQueue.cpp
Source/WebCore/dom/make_names.pl
Source/WebCore/editing/Editor.cpp
Source/WebCore/editing/EditorCommand.cpp
Source/WebCore/html/HTMLAnchorElement.cpp
Source/WebCore/html/HTMLCanvasElement.cpp
Source/WebCore/html/HTMLElement.h
Source/WebCore/html/HTMLFormElement.cpp
Source/WebCore/html/HTMLLabelElement.cpp
Source/WebCore/html/HTMLPlugInImageElement.cpp
Source/WebCore/html/HTMLPlugInImageElement.h
Source/WebCore/html/HTMLSummaryElement.cpp
Source/WebCore/html/HTMLTextFormControlElement.h
Source/WebCore/html/MediaDocument.cpp
Source/WebCore/html/RangeInputType.cpp
Source/WebCore/html/shadow/MediaControlElements.cpp
Source/WebCore/html/shadow/MediaControls.cpp
Source/WebCore/inspector/InspectorFrontendHost.cpp
Source/WebCore/inspector/agents/InspectorDOMAgent.cpp
Source/WebCore/page/ContextMenuController.cpp
Source/WebCore/page/DOMWindow.cpp
Source/WebCore/page/DOMWindow.h
Source/WebCore/page/EventHandler.cpp
Source/WebCore/platform/graphics/WidthCache.h
Source/WebCore/rendering/RenderSnapshottedPlugIn.cpp
Source/WebKit/ChangeLog
Source/WebKit/WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMPrivate.cpp
Source/WebKit/WebProcess/WebCoreSupport/gtk/WebEditorClientGtk.cpp
Source/WebKit/WebProcess/WebCoreSupport/wpe/WebEditorClientWPE.cpp
Source/WebKit/WebProcess/WebPage/WebPage.cpp
Source/WebKit/WebProcess/WebPage/mac/WebPageMac.mm
Source/WebKitLegacy/mac/ChangeLog
Source/WebKitLegacy/mac/DOM/DOM.mm
Source/WebKitLegacy/mac/WebCoreSupport/WebEditorClient.mm
Source/WebKitLegacy/mac/WebView/WebHTMLView.mm
Source/WebKitLegacy/win/ChangeLog
Source/WebKitLegacy/win/WebView.cpp

index 4552b57..ea5b2a5 100644 (file)
@@ -1,3 +1,14 @@
+2017-11-12  Darin Adler  <darin@apple.com>
+
+        More is<> and downcast<>, less static_cast<>
+        https://bugs.webkit.org/show_bug.cgi?id=179600
+
+        Reviewed by Chris Dumez.
+
+        * runtime/JSString.h:
+        (JSC::jsSubstring): Removed unneeded static_cast; length already returns unsigned.
+        (JSC::jsSubstringOfResolved): Ditto.
+
 2017-11-12  Mark Lam  <mark.lam@apple.com>
 
         We should ensure that operationStrCat2 and operationStrCat3 are never passed Symbols as arguments.
index 7aae0cd..2c7c9dc 100644 (file)
@@ -581,9 +581,9 @@ inline JSString* jsString(VM* vm, const String& s)
 
 inline JSString* jsSubstring(VM& vm, ExecState* exec, JSString* s, unsigned offset, unsigned length)
 {
-    ASSERT(offset <= static_cast<unsigned>(s->length()));
-    ASSERT(length <= static_cast<unsigned>(s->length()));
-    ASSERT(offset + length <= static_cast<unsigned>(s->length()));
+    ASSERT(offset <= s->length());
+    ASSERT(length <= s->length());
+    ASSERT(offset + length <= s->length());
     if (!length)
         return vm.smallStrings.emptyString();
     if (!offset && length == s->length())
@@ -593,9 +593,9 @@ inline JSString* jsSubstring(VM& vm, ExecState* exec, JSString* s, unsigned offs
 
 inline JSString* jsSubstringOfResolved(VM& vm, GCDeferralContext* deferralContext, JSString* s, unsigned offset, unsigned length)
 {
-    ASSERT(offset <= static_cast<unsigned>(s->length()));
-    ASSERT(length <= static_cast<unsigned>(s->length()));
-    ASSERT(offset + length <= static_cast<unsigned>(s->length()));
+    ASSERT(offset <= s->length());
+    ASSERT(length <= s->length());
+    ASSERT(offset + length <= s->length());
     if (!length)
         return vm.smallStrings.emptyString();
     if (!offset && length == s->length())
@@ -615,9 +615,9 @@ inline JSString* jsSubstring(ExecState* exec, JSString* s, unsigned offset, unsi
 
 inline JSString* jsSubstring(VM* vm, const String& s, unsigned offset, unsigned length)
 {
-    ASSERT(offset <= static_cast<unsigned>(s.length()));
-    ASSERT(length <= static_cast<unsigned>(s.length()));
-    ASSERT(offset + length <= static_cast<unsigned>(s.length()));
+    ASSERT(offset <= s.length());
+    ASSERT(length <= s.length());
+    ASSERT(offset + length <= s.length());
     if (!length)
         return vm->smallStrings.emptyString();
     if (length == 1) {
index e46ca72..3698181 100644 (file)
@@ -1,3 +1,153 @@
+2017-11-12  Darin Adler  <darin@apple.com>
+
+        More is<> and downcast<>, less static_cast<>
+        https://bugs.webkit.org/show_bug.cgi?id=179600
+
+        Reviewed by Chris Dumez.
+
+        * Modules/fetch/FetchBody.cpp:
+        (WebCore::FetchBody::extract): Use downcast instead of static_cast.
+        (WebCore::FetchBody::bodyAsFormData const): Ditto.
+        * Modules/indexeddb/IDBObjectStore.cpp:
+        (WebCore::IDBObjectStore::putOrAdd): Ditto.
+        * Modules/mediastream/CanvasCaptureMediaStreamTrack.cpp:
+        (WebCore::CanvasCaptureMediaStreamTrack::Source::canvasChanged): Ditto.
+        * Modules/mediastream/libwebrtc/LibWebRTCPeerConnectionBackend.cpp:
+        (WebCore::libWebRTCProvider): Ditto.
+
+        * accessibility/AccessibilityMediaControls.cpp:
+        (WebCore::AccessibilityMediaTimeDisplay::stringValue const): Got rid of local
+        variable and used std::abs instead of fabsf. Did not use downcast here because
+        it doesn't exist for this class.
+
+        * bindings/js/JSEventTargetCustom.h:
+        (WebCore::IDLOperation<JSEventTarget>::call): Use downcast instead of toDOMWindow.
+        * dom/DocumentEventQueue.cpp:
+        (WebCore::DocumentEventQueue::dispatchEvent): Ditto.
+
+        * dom/Element.h: Added is/downcast for EventTarget.
+
+        * dom/EventContext.cpp:
+        (WebCore::TouchEventContext::checkReachability const): Use downcast instead
+        of toNode.
+        * dom/EventContext.h:
+        (WebCore::EventContext::isUnreachableNode const): Ditto.
+        * dom/EventPath.cpp:
+        (WebCore::shouldEventCrossShadowBoundary): Ditto.
+        (WebCore::EventPath::setRelatedTarget): Ditto.
+        (WebCore::EventPath::retargetTouch): Ditto.
+        (WebCore::EventPath::EventPath): Ditto.
+
+        * dom/EventTarget.cpp:
+        (WebCore::EventTarget::toNode): Deleted.
+        (WebCore::EventTarget::isNode const): Added.
+        (WebCore::EventTarget::toDOMWindow): Deleted.
+        (WebCore::EventTarget::isMessagePort const): Deleted. This was not used.
+        (WebCore::EventTarget::addEventListener): Use downcast instead of toDOMWindow
+        and toNode.
+        * dom/EventTarget.h: Updated for the above.
+
+        * dom/MessagePort.h: Deleted unused isMessagePort.
+
+        * dom/MouseEvent.cpp:
+        (WebCore::MouseEvent::toElement const): Use downcast instead of toNode.
+        Also refactored to make function a little smaller.
+        (WebCore::MouseEvent::fromElement const): Ditto.
+
+        * dom/MouseRelatedEvent.cpp:
+        (WebCore::MouseRelatedEvent::computeRelativePosition): Use downcast
+        instead of toNode.
+
+        * dom/Node.cpp:
+        (WebCore::Node::isNode const): Added.
+        (WebCore::Node::toNode): Deleted.
+        * dom/Node.h: Updated for the above. Also added SPECIALIZE_TYPE_TRAITS
+        so we can do is/downcast.
+
+        * dom/ScopedEventQueue.cpp:
+        (WebCore::ScopedEventQueue::enqueueEvent): Use is instead of toNode.
+        (WebCore::ScopedEventQueue::dispatchEvent const): Use downcast instead of toNode.
+
+        * dom/make_names.pl:
+        (printTypeHelpers): Added support for is/downcast from EventTarget.
+
+        * editing/Editor.cpp:
+        (WebCore::Editor::selectionForCommand): Use is/downcast instead of toNode.
+        * editing/EditorCommand.cpp:
+        (WebCore::targetFrame): Ditto.
+        * html/HTMLAnchorElement.cpp:
+        (WebCore::appendServerMapMousePosition): Ditto.
+
+        * html/HTMLCanvasElement.cpp:
+        (WebCore::HTMLCanvasElement::createContextWebGL): Use downcast instead of
+        static_cast.
+        (WebCore::HTMLCanvasElement::getContextWebGL): Ditto.
+        (WebCore::HTMLCanvasElement::getImageData): Ditto.
+
+        * html/HTMLElement.h: Added support for is/downcast from EventTarget.
+
+        * html/HTMLFormElement.cpp:
+        (WebCore::HTMLFormElement::handleLocalEvents): Use is instead of toNode.
+        (WebCore::submitElementFromEvent): Deleted. Was a duplicate of findSubmitButton.
+        (WebCore::HTMLFormElement::prepareForSubmission): Rewrote code that calls
+        submitElementFromEvent to call findSubmitButton instead. Also don't bother
+        finding the submit button unless we are going to validate, since all we do
+        after finding it is reconsider whether we should validate.
+        (WebCore::HTMLFormElement::findSubmitButton const): Rewrote to use is,
+        downcast, and lineageOfType rather than a handwritten loop and toNode.
+        Relies on the fact that the target is an element, never a text node.
+
+        * html/HTMLLabelElement.cpp:
+        (WebCore::HTMLLabelElement::defaultEventHandler): Use is and downcast instead
+        of toNode.
+
+        * html/HTMLPlugInImageElement.cpp:
+        (WebCore::HTMLPlugInImageElement::partOfSnapshotOverlay const): Changed argument
+        type to EventTarget so we can do the type checking and casting here instead of at
+        each of the callers.
+        * html/HTMLPlugInImageElement.h: Updated for the above.
+
+        * html/HTMLSummaryElement.cpp:
+        (WebCore::isClickableControl): Changed argument type to EventTarget so we can do
+        the type checking and casting here instead of at each of the callers.
+        (WebCore::HTMLSummaryElement::defaultEventHandler): Removed call to toNode.
+
+        * html/HTMLTextFormControlElement.h: Added support for is/downcast from EventTarget.
+
+        * html/MediaDocument.cpp:
+        (WebCore::MediaDocument::defaultEventHandler): Use is/downcast instead of toNode.
+        * html/RangeInputType.cpp:
+        (WebCore::RangeInputType::handleMouseDownEvent): Ditto.
+        * html/shadow/MediaControlElements.cpp:
+        (WebCore::MediaControlVolumeSliderContainerElement::defaultEventHandler): Ditto.
+        (WebCore::MediaControlClosedCaptionsTrackListElement::defaultEventHandler): Ditto.
+        Also use get instead of find/end.
+
+        * html/shadow/MediaControls.cpp:
+        (WebCore::MediaControls::containsRelatedTarget): Use is/downcast instead of toNode.
+        * inspector/InspectorFrontendHost.cpp:
+        (WebCore::InspectorFrontendHost::dispatchEventAsContextMenuEvent): Ditto.
+        * inspector/agents/InspectorDOMAgent.cpp:
+        (WebCore::InspectorDOMAgent::didAddEventListener): Ditto.
+        (WebCore::InspectorDOMAgent::willRemoveEventListener): Ditto.
+        * page/ContextMenuController.cpp:
+        (WebCore::ContextMenuController::maybeCreateContextMenu): Ditto.
+
+        * page/DOMWindow.cpp:
+        (WebCore::DOMWindow::toDOMWindow): Deleted.
+        * page/DOMWindow.h: Updated for the above. Also added SPECIALIZE_TYPE_TRAITS
+        so we can do is/downcast.
+
+        * page/EventHandler.cpp:
+        (WebCore::EventHandler::handleTouchEvent): Use is/downcast instead of toNode.
+
+        * platform/graphics/WidthCache.h:
+        (WebCore::WidthCache::add): Removed unneeded static_cast; length already returns unsigned.
+
+        * rendering/RenderSnapshottedPlugIn.cpp:
+        (WebCore::RenderSnapshottedPlugIn::handleEvent): Removed unneeded toNode now that
+        partOfSnapshotOverlay takes an EventTarget.
+
 2017-11-12  Gabriel Ivascu  <givascu@igalia.com>
 
         [GTK] Add functionality to handle font sizes in points
index bb3ff1a..2e15cd7 100644 (file)
@@ -48,7 +48,7 @@ FetchBody FetchBody::extract(ScriptExecutionContext& context, Init&& value, Stri
         return FetchBody(WTFMove(blob));
     }, [&](RefPtr<DOMFormData>& value) mutable {
         Ref<DOMFormData> domFormData = value.releaseNonNull();
-        auto formData = FormData::createMultiPart(domFormData.get(), &static_cast<Document&>(context));
+        auto formData = FormData::createMultiPart(domFormData.get(), &downcast<Document>(context));
         contentType = makeString("multipart/form-data; boundary=", formData->boundary().data());
         return FetchBody(WTFMove(formData));
     }, [&](RefPtr<URLSearchParams>& value) mutable {
@@ -228,7 +228,7 @@ RefPtr<FormData> FetchBody::bodyAsFormData(ScriptExecutionContext& context) cons
     if (isFormData()) {
         ASSERT(!context.isWorkerGlobalScope());
         RefPtr<FormData> body = const_cast<FormData*>(&formDataBody());
-        body->generateFiles(static_cast<Document*>(&context));
+        body->generateFiles(&downcast<Document>(context));
         return body;
     }
     ASSERT_NOT_REACHED();
index 6e582b5..08a784b 100644 (file)
@@ -321,8 +321,8 @@ ExceptionOr<Ref<IDBRequest>> IDBObjectStore::putOrAdd(ExecState& state, JSValue
     }
 
     bool privateBrowsingEnabled = false;
-    if (context->isDocument()) {
-        if (auto* page = static_cast<Document*>(context)->page())
+    if (is<Document>(*context)) {
+        if (auto* page = downcast<Document>(*context).page())
             privateBrowsingEnabled = page->sessionID().isEphemeral();
     }
 
index dc21615..91d8b3a 100644 (file)
@@ -126,8 +126,8 @@ void CanvasCaptureMediaStreamTrack::Source::canvasChanged(HTMLCanvasElement& can
     // FIXME: We need to preserve drawing buffer as we are currently grabbing frames asynchronously.
     // We should instead add an anchor point for both 2d and 3d contexts where canvas will actually paint.
     // And call canvas observers from that point.
-    if (canvas.renderingContext() && canvas.renderingContext()->isWebGL()) {
-        auto& context = static_cast<WebGLRenderingContextBase&>(*canvas.renderingContext());
+    if (is<WebGLRenderingContextBase>(canvas.renderingContext())) {
+        auto& context = downcast<WebGLRenderingContextBase>(*canvas.renderingContext());
         if (!context.isPreservingDrawingBuffer()) {
             canvas.document().addConsoleMessage(MessageSource::JS, MessageLevel::Warning, ASCIILiteral("Turning drawing buffer preservation for the WebGL canvas being captured"));
             context.setPreserveDrawingBuffer(true);
index 3468fc4..01f38d8 100644 (file)
@@ -54,9 +54,7 @@ CreatePeerConnectionBackend PeerConnectionBackend::create = createLibWebRTCPeerC
 
 static inline LibWebRTCProvider& libWebRTCProvider(RTCPeerConnection& peerConnection)
 {
-    ASSERT(peerConnection.scriptExecutionContext()->isDocument());
-    auto* page = static_cast<Document*>(peerConnection.scriptExecutionContext())->page();
-    return page->libWebRTCProvider();
+    return downcast<Document>(*peerConnection.scriptExecutionContext()).page()->libWebRTCProvider();
 }
 
 LibWebRTCPeerConnectionBackend::LibWebRTCPeerConnectionBackend(RTCPeerConnection& peerConnection)
index fe293bc..5c4697e 100644 (file)
@@ -327,9 +327,8 @@ String AccessibilityMediaTimeDisplay::stringValue() const
     if (!m_renderer || !m_renderer->node())
         return String();
 
-    MediaControlTimeDisplayElement* element = static_cast<MediaControlTimeDisplayElement*>(m_renderer->node());
-    float time = element->currentValue();
-    return localizedMediaTimeDescription(fabsf(time));
+    float time = static_cast<MediaControlTimeDisplayElement*>(m_renderer->node())->currentValue();
+    return localizedMediaTimeDescription(std::abs(time));
 }
 
 } // namespace WebCore
index 9365fd9..3843433 100644 (file)
@@ -57,18 +57,20 @@ public:
     using ClassParameter = JSEventTargetWrapper*;
     using Operation = JSC::EncodedJSValue(JSC::ExecState*, ClassParameter, JSC::ThrowScope&);
 
-    template<Operation operation, CastedThisErrorBehavior shouldThrow = CastedThisErrorBehavior::Throw>
+    template<Operation operation, CastedThisErrorBehavior = CastedThisErrorBehavior::Throw>
     static JSC::EncodedJSValue call(JSC::ExecState& state, const char* operationName)
     {
-        JSC::VM& vm = state.vm();
+        auto& vm = state.vm();
         auto throwScope = DECLARE_THROW_SCOPE(vm);
 
         auto thisObject = jsEventTargetCast(vm, state.thisValue().toThis(&state, JSC::NotStrictMode));
         if (UNLIKELY(!thisObject))
             return throwThisTypeError(state, throwScope, "EventTarget", operationName);
 
-        if (auto* window = thisObject->wrapped().toDOMWindow()) {
-            if (!window->frame() || !BindingSecurity::shouldAllowAccessToDOMWindow(&state, *window, ThrowSecurityError))
+        auto& wrapped = thisObject->wrapped();
+        if (is<DOMWindow>(wrapped)) {
+            auto& window = downcast<DOMWindow>(wrapped);
+            if (!window.frame() || !BindingSecurity::shouldAllowAccessToDOMWindow(&state, window, ThrowSecurityError))
                 return JSC::JSValue::encode(JSC::jsUndefined());
         }
 
index a46460f..f66f437 100644 (file)
@@ -141,11 +141,12 @@ void DocumentEventQueue::pendingEventTimerFired()
 
 void DocumentEventQueue::dispatchEvent(Event& event)
 {
-    // FIXME: Where did this special case for the DOM window come from?
-    // Why do we have this special case here instead of a virtual function on EventTarget?
-    EventTarget& eventTarget = *event.target();
-    if (DOMWindow* window = eventTarget.toDOMWindow())
-        window->dispatchEvent(event, nullptr);
+    // FIXME: Why do we have this special case here instead of a virtual function?
+    // If it's not safe to call EventTarget::dispatchEvent on a DOMWindow, then we
+    // likely have problems elsewhere.
+    auto& eventTarget = *event.target();
+    if (is<DOMWindow>(eventTarget))
+        downcast<DOMWindow>(eventTarget).dispatchEvent(event, nullptr);
     else
         eventTarget.dispatchEvent(event);
 }
index 3f4cf4d..d8999d1 100644 (file)
@@ -801,4 +801,5 @@ inline void Element::setHasFocusWithin(bool flag)
 
 SPECIALIZE_TYPE_TRAITS_BEGIN(WebCore::Element)
     static bool isType(const WebCore::Node& node) { return node.isElementNode(); }
+    static bool isType(const WebCore::EventTarget& target) { return is<WebCore::Node>(target) && isType(downcast<WebCore::Node>(target)); }
 SPECIALIZE_TYPE_TRAITS_END()
index b680b4c..65e32fd 100644 (file)
@@ -120,7 +120,7 @@ void TouchEventContext::checkReachability(const Ref<TouchList>& touchList) const
 {
     size_t length = touchList->length();
     for (size_t i = 0; i < length; ++i)
-        ASSERT(!isUnreachableNode(touchList->item(i)->target()->toNode().get()));
+        ASSERT(!isUnreachableNode(downcast<Node>(touchList->item(i)->target())->get()));
 }
 
 #endif
index 70789af..5c73f62 100644 (file)
@@ -101,7 +101,7 @@ private:
 inline bool EventContext::isUnreachableNode(EventTarget* target) const
 {
     // FIXME: Checks also for SVG elements.
-    return target && target->toNode() && !target->toNode()->isSVGElement() && m_node->isClosedShadowHidden(*target->toNode());
+    return is<Node>(target) && !downcast<Node>(*target).isSVGElement() && m_node->isClosedShadowHidden(downcast<Node>(*target));
 }
 
 #endif
index b53eba9..2f196af 100644 (file)
@@ -54,13 +54,11 @@ void WindowEventContext::handleLocalEvents(Event& event) const
 
 static inline bool shouldEventCrossShadowBoundary(Event& event, ShadowRoot& shadowRoot, EventTarget& target)
 {
-    auto targetNode = target.toNode();
-
 #if ENABLE(FULLSCREEN_API) && ENABLE(VIDEO)
     // Video-only full screen is a mode where we use the shadow DOM as an implementation
     // detail that should not be detectable by the web content.
-    if (targetNode) {
-        if (auto* element = targetNode->document().webkitCurrentFullScreenElement()) {
+    if (is<Node>(target)) {
+        if (auto* element = downcast<Node>(target).document().webkitCurrentFullScreenElement()) {
             // FIXME: We assume that if the full screen element is a media element that it's
             // the video-only full screen. Both here and elsewhere. But that is probably wrong.
             if (element->isMediaElement() && shadowRoot.host() == element)
@@ -69,7 +67,7 @@ static inline bool shouldEventCrossShadowBoundary(Event& event, ShadowRoot& shad
     }
 #endif
 
-    bool targetIsInShadowRoot = targetNode && &targetNode->treeScope().rootNode() == &shadowRoot;
+    bool targetIsInShadowRoot = is<Node>(target) && &downcast<Node>(target).treeScope().rootNode() == &shadowRoot;
     return !targetIsInShadowRoot || event.composed();
 }
 
@@ -174,13 +172,13 @@ void EventPath::buildPath(Node& originalTarget, Event& event)
 
 void EventPath::setRelatedTarget(Node& origin, EventTarget& relatedTarget)
 {
-    auto relatedNode = relatedTarget.toNode();
-    if (!relatedNode || m_path.isEmpty())
+    if (!is<Node>(relatedTarget) || m_path.isEmpty())
         return;
 
-    RelatedNodeRetargeter retargeter(*relatedNode, *m_path[0]->node());
+    auto& relatedNode = downcast<Node>(relatedTarget);
+    RelatedNodeRetargeter retargeter(relatedNode, *m_path[0]->node());
 
-    bool originIsRelatedTarget = &origin == relatedNode;
+    bool originIsRelatedTarget = &origin == &relatedNode;
     Node& rootNodeInOriginTreeScope = origin.treeScope().rootNode();
     TreeScope* previousTreeScope = nullptr;
     size_t originalEventPathSize = m_path.size();
@@ -216,15 +214,11 @@ void EventPath::setRelatedTarget(Node& origin, EventTarget& relatedTarget)
 
 void EventPath::retargetTouch(TouchEventContext::TouchListType type, const Touch& touch)
 {
-    EventTarget* eventTarget = touch.target();
-    if (!eventTarget)
-        return;
-
-    auto targetNode = eventTarget->toNode();
-    if (!targetNode)
+    auto* eventTarget = touch.target();
+    if (!is<Node>(eventTarget))
         return;
 
-    RelatedNodeRetargeter retargeter(*targetNode, *m_path[0]->node());
+    RelatedNodeRetargeter retargeter(downcast<Node>(*eventTarget), *m_path[0]->node());
     TreeScope* previousTreeScope = nullptr;
     for (auto& context : m_path) {
         Node& currentTarget = *context->node();
@@ -260,20 +254,18 @@ void EventPath::retargetTouchLists(const TouchEvent& event)
 Vector<EventTarget*> EventPath::computePathUnclosedToTarget(const EventTarget& target) const
 {
     Vector<EventTarget*> path;
-    auto targetNode = const_cast<EventTarget&>(target).toNode();
-    if (!targetNode) {
-        auto* domWindow = const_cast<EventTarget&>(target).toDOMWindow();
-        if (!domWindow)
-            return path;
-        targetNode = domWindow->document();
+    path.reserveInitialCapacity(m_path.size());
+    const Node* targetNode = nullptr;
+    if (is<Node>(target))
+        targetNode = &downcast<Node>(target);
+    else if (is<DOMWindow>(target)) {
+        targetNode = downcast<DOMWindow>(target).document();
         ASSERT(targetNode);
     }
     for (auto& context : m_path) {
-        if (auto nodeInPath = context->currentTarget()->toNode()) {
-            if (!targetNode->isClosedShadowHidden(*nodeInPath))
-                path.append(context->currentTarget());
-        } else
-            path.append(context->currentTarget());
+        auto* currentTarget = context->currentTarget();
+        if (!is<Node>(currentTarget) || !targetNode || !targetNode->isClosedShadowHidden(downcast<Node>(*currentTarget)))
+            path.uncheckedAppend(currentTarget);
     }
     return path;
 }
@@ -282,7 +274,7 @@ EventPath::EventPath(const Vector<EventTarget*>& targets)
 {
     for (auto* target : targets) {
         ASSERT(target);
-        ASSERT(!target->toNode());
+        ASSERT(!is<Node>(target));
         m_path.append(std::make_unique<EventContext>(nullptr, target, *targets.begin()));
     }
 }
index 7e14f3a..36b9eb3 100644 (file)
 #include <wtf/StdLibExtras.h>
 #include <wtf/Vector.h>
 
-
 namespace WebCore {
-using namespace WTF;
-
-RefPtr<Node> EventTarget::toNode()
-{
-    return nullptr;
-}
 
-DOMWindow* EventTarget::toDOMWindow()
-{
-    return nullptr;
-}
+using namespace WTF;
 
-bool EventTarget::isMessagePort() const
+bool EventTarget::isNode() const
 {
     return false;
 }
@@ -72,10 +62,11 @@ bool EventTarget::addEventListener(const AtomicString& eventType, Ref<EventListe
     auto passive = options.passive;
 
     if (!passive.has_value() && eventNames().isTouchScrollBlockingEventType(eventType)) {
-        if (toDOMWindow())
+        if (is<DOMWindow>(*this))
             passive = true;
-        else if (auto node = toNode()) {
-            if (node->isDocumentNode() || node->document().documentElement() == node || node->document().body() == node)
+        else if (is<Node>(*this)) {
+            auto& node = downcast<Node>(*this);
+            if (is<Document>(node) || node.document().documentElement() == &node || node.document().body() == &node)
                 passive = true;
         }
     }
index ec5b06d..90b122a 100644 (file)
@@ -40,9 +40,7 @@
 
 namespace WebCore {
 
-class DOMWindow;
 class DOMWrapperWorld;
-class Node;
 
 struct EventTargetData {
     WTF_MAKE_NONCOPYABLE(EventTargetData); WTF_MAKE_FAST_ALLOCATED;
@@ -68,9 +66,7 @@ public:
     virtual EventTargetInterface eventTargetInterface() const = 0;
     virtual ScriptExecutionContext* scriptExecutionContext() const = 0;
 
-    virtual RefPtr<Node> toNode();
-    virtual DOMWindow* toDOMWindow();
-    virtual bool isMessagePort() const;
+    virtual bool isNode() const;
 
     struct ListenerOptions {
         ListenerOptions(bool capture = false)
index 1bf676d..660ca51 100644 (file)
@@ -82,7 +82,6 @@ private:
     void refEventTarget() final { ref(); }
     void derefEventTarget() final { deref(); }
 
-    bool isMessagePort() const final { return true; }
     EventTargetInterface eventTargetInterface() const final { return MessagePortEventTargetInterfaceType; }
 
     bool addEventListener(const AtomicString& eventType, Ref<EventListener>&&, const AddEventListenerOptions&) final;
index c06dfab..a147e12 100644 (file)
@@ -222,23 +222,23 @@ int MouseEvent::which() const
 RefPtr<Node> MouseEvent::toElement() const
 {
     // MSIE extension - "the object toward which the user is moving the mouse pointer"
-    if (type() == eventNames().mouseoutEvent || type() == eventNames().mouseleaveEvent) {
-        EventTarget* relatedTarget = this->relatedTarget();
-        return relatedTarget ? relatedTarget->toNode() : nullptr;
-    }
-
-    return target() ? target()->toNode() : nullptr;
+    EventTarget* target;
+    if (type() == eventNames().mouseoutEvent || type() == eventNames().mouseleaveEvent)
+        target = relatedTarget();
+    else
+        target = this->target();
+    return is<Node>(target) ? &downcast<Node>(*target) : nullptr;
 }
 
 RefPtr<Node> MouseEvent::fromElement() const
 {
     // MSIE extension - "object from which activation or the mouse pointer is exiting during the event" (huh?)
-    if (type() != eventNames().mouseoutEvent && type() != eventNames().mouseleaveEvent) {
-        EventTarget* relatedTarget = this->relatedTarget();
-        return relatedTarget ? relatedTarget->toNode() : nullptr;
-    }
-
-    return target() ? target()->toNode() : nullptr;
+    EventTarget* target;
+    if (type() == eventNames().mouseoutEvent || type() == eventNames().mouseleaveEvent)
+        target = this->target();
+    else
+        target = relatedTarget();
+    return is<Node>(target) ? &downcast<Node>(*target) : nullptr;
 }
 
 } // namespace WebCore
index 2d9b49a..853714d 100644 (file)
@@ -146,19 +146,19 @@ void MouseRelatedEvent::receivedTarget()
 
 void MouseRelatedEvent::computeRelativePosition()
 {
-    auto targetNode = target() ? target()->toNode() : nullptr;
-    if (!targetNode)
+    if (!is<Node>(target()))
         return;
+    auto& targetNode = downcast<Node>(*target());
 
     // Compute coordinates that are based on the target.
     m_layerLocation = m_pageLocation;
     m_offsetLocation = m_pageLocation;
 
     // Must have an updated render tree for this math to work correctly.
-    targetNode->document().updateLayoutIgnorePendingStylesheets();
+    targetNode.document().updateLayoutIgnorePendingStylesheets();
 
     // Adjust offsetLocation to be relative to the target's position.
-    if (RenderObject* r = targetNode->renderer()) {
+    if (RenderObject* r = targetNode.renderer()) {
         m_offsetLocation = LayoutPoint(r->absoluteToLocal(absoluteLocation(), UseTransforms));
         float scaleFactor = 1 / documentToAbsoluteScaleFactor();
         if (scaleFactor != 1.0f)
@@ -169,7 +169,7 @@ void MouseRelatedEvent::computeRelativePosition()
     // FIXME: event.layerX and event.layerY are poorly defined,
     // and probably don't always correspond to RenderLayer offsets.
     // https://bugs.webkit.org/show_bug.cgi?id=21868
-    Node* n = targetNode.get();
+    Node* n = &targetNode;
     while (n && !n->renderer())
         n = n->parentNode();
 
index 2748079..cfc8dfd 100644 (file)
@@ -356,9 +356,9 @@ void Node::clearRareData()
     clearFlag(HasRareDataFlag);
 }
 
-RefPtr<Node> Node::toNode()
+bool Node::isNode() const
 {
-    return this;
+    return true;
 }
 
 String Node::nodeValue() const
index a106948..eb857fe 100644 (file)
@@ -486,8 +486,6 @@ public:
 
     WEBCORE_EXPORT unsigned short compareDocumentPosition(Node&);
 
-    RefPtr<Node> toNode() override;
-
     EventTargetInterface eventTargetInterface() const override;
     ScriptExecutionContext* scriptExecutionContext() const final; // Implemented in Document.h
 
@@ -661,8 +659,9 @@ private:
 
     WEBCORE_EXPORT void removedLastRef();
 
-    void refEventTarget() override;
-    void derefEventTarget() override;
+    void refEventTarget() final;
+    void derefEventTarget() final;
+    bool isNode() const final;
 
     void trackForDebugging();
     void materializeRareData();
@@ -804,3 +803,7 @@ inline void Node::setTreeScopeRecursively(TreeScope& newTreeScope)
 void showTree(const WebCore::Node*);
 void showNodePath(const WebCore::Node*);
 #endif
+
+SPECIALIZE_TYPE_TRAITS_BEGIN(WebCore::Node)
+    static bool isType(const WebCore::EventTarget& target) { return target.isNode(); }
+SPECIALIZE_TYPE_TRAITS_END()
index e8d5e5e..7a831f0 100644 (file)
@@ -45,8 +45,7 @@ ScopedEventQueue& ScopedEventQueue::singleton()
 
 void ScopedEventQueue::enqueueEvent(Ref<Event>&& event)
 {
-    ASSERT(event->target());
-    ASSERT(event->target()->toNode());
+    ASSERT(is<Node>(event->target()));
     if (m_scopingLevel)
         m_queuedEvents.append(WTFMove(event));
     else
@@ -55,7 +54,7 @@ void ScopedEventQueue::enqueueEvent(Ref<Event>&& event)
 
 void ScopedEventQueue::dispatchEvent(Event& event) const
 {
-    event.target()->toNode()->dispatchEvent(event);
+    downcast<Node>(*event.target()).dispatchEvent(event);
 }
 
 void ScopedEventQueue::dispatchAllEvents()
index 43e282b..af0d33d 100755 (executable)
@@ -658,8 +658,7 @@ namespace WebCore {
 class $class;
 }
 namespace WTF {
-template <typename ArgType>
-class TypeCastTraits<const WebCore::$class, ArgType, false /* isBaseType */> {
+template<typename ArgType> class TypeCastTraits<const WebCore::$class, ArgType, false /* isBaseType */> {
 public:
     static bool isOfType(ArgType& node) { return checkTagName(node); }
 private:
@@ -679,6 +678,7 @@ END
            ;
        }
        print F <<END
+    static bool checkTagName(const WebCore::EventTarget& target) { return is<WebCore::Node>(target) && checkTagName(downcast<WebCore::Node>(target)); }
 };
 }
 END
index 95ba418..09660a3 100644 (file)
@@ -233,16 +233,18 @@ TemporarySelectionChange::~TemporarySelectionChange()
 // we should use the target control's selection for this editing operation.
 VisibleSelection Editor::selectionForCommand(Event* event)
 {
-    VisibleSelection selection = m_frame.selection().selection();
+    auto selection = m_frame.selection().selection();
     if (!event)
         return selection;
     // If the target is a text control, and the current selection is outside of its shadow tree,
     // then use the saved selection for that text control.
-    HTMLTextFormControlElement* textFormControlOfSelectionStart = enclosingTextFormControl(selection.start());
-    HTMLTextFormControlElement* textFromControlOfTarget = is<HTMLTextFormControlElement>(*event->target()->toNode()) ? downcast<HTMLTextFormControlElement>(event->target()->toNode().get()) : nullptr;
-    if (textFromControlOfTarget && (selection.start().isNull() || textFromControlOfTarget != textFormControlOfSelectionStart)) {
-        if (RefPtr<Range> range = textFromControlOfTarget->selection())
-            return VisibleSelection(*range, DOWNSTREAM, selection.isDirectional());
+    if (is<HTMLTextFormControlElement>(event->target())) {
+        auto& target = downcast<HTMLTextFormControlElement>(*event->target());
+        auto start = selection.start();
+        if (start.isNull() || &target != enclosingTextFormControl(start)) {
+            if (auto range = target.selection())
+                return { *range, DOWNSTREAM, selection.isDirectional() };
+        }
     }
     return selection;
 }
index f341605..9ec1f0d 100644 (file)
@@ -91,10 +91,9 @@ static Frame* targetFrame(Frame& frame, Event* event)
 {
     if (!event)
         return &frame;
-    auto node = event->target()->toNode();
-    if (!node)
+    if (!is<Node>(event->target()))
         return &frame;
-    return node->document().frame();
+    return downcast<Node>(*event->target()).document().frame();
 }
 
 static bool applyCommandToFrame(Frame& frame, EditorCommandSource source, EditAction action, Ref<EditingStyle>&& style)
index 2a5f79c..ead1145 100644 (file)
@@ -144,13 +144,10 @@ static void appendServerMapMousePosition(StringBuilder& url, Event& event)
         return;
     auto& mouseEvent = downcast<MouseEvent>(event);
 
-    ASSERT(mouseEvent.target());
-    auto target = mouseEvent.target()->toNode();
-    ASSERT(target);
-    if (!is<HTMLImageElement>(*target))
+    if (!is<HTMLImageElement>(mouseEvent.target()))
         return;
 
-    auto& imageElement = downcast<HTMLImageElement>(*target);
+    auto& imageElement = downcast<HTMLImageElement>(*mouseEvent.target());
     if (!imageElement.isServerMap())
         return;
 
index 26ab458..ceea56f 100644 (file)
@@ -393,6 +393,7 @@ CanvasRenderingContext2D* HTMLCanvasElement::getContext2d(const String& type)
 }
 
 #if ENABLE(WEBGL)
+
 static bool requiresAcceleratedCompositingForWebGL()
 {
 #if PLATFORM(GTK)
@@ -439,7 +440,7 @@ WebGLRenderingContextBase* HTMLCanvasElement::createContextWebGL(const String& t
         InspectorInstrumentation::didCreateCanvasRenderingContext(*this);
     }
 
-    return static_cast<WebGLRenderingContextBase*>(m_context.get());
+    return downcast<WebGLRenderingContextBase>(m_context.get());
 }
 
 WebGLRenderingContextBase* HTMLCanvasElement::getContextWebGL(const String& type, WebGLContextAttributes&& attrs)
@@ -454,11 +455,13 @@ WebGLRenderingContextBase* HTMLCanvasElement::getContextWebGL(const String& type
 
     if (!m_context)
         return createContextWebGL(type, WTFMove(attrs));
-    return static_cast<WebGLRenderingContextBase*>(m_context.get());
+    return &downcast<WebGLRenderingContextBase>(*m_context);
 }
-#endif
+
+#endif // ENABLE(WEBGL)
 
 #if ENABLE(WEBGPU)
+
 bool HTMLCanvasElement::isWebGPUType(const String& type)
 {
     return type == "webgpu";
@@ -779,15 +782,10 @@ ExceptionOr<void> HTMLCanvasElement::toBlob(ScriptExecutionContext& context, Ref
 RefPtr<ImageData> HTMLCanvasElement::getImageData()
 {
 #if ENABLE(WEBGL)
-    if (!m_context || !m_context->isWebGL())
-        return nullptr;
-
-    WebGLRenderingContextBase* ctx = static_cast<WebGLRenderingContextBase*>(m_context.get());
-
-    return ctx->paintRenderingResultsToImageData();
-#else
-    return nullptr;
+    if (is<WebGLRenderingContextBase>(m_context.get()))
+        return downcast<WebGLRenderingContextBase>(*m_context).paintRenderingResultsToImageData();
 #endif
+    return nullptr;
 }
 
 #if ENABLE(MEDIA_STREAM)
index 3bada1b..685aac9 100644 (file)
@@ -162,6 +162,7 @@ inline bool Node::hasTagName(const HTMLQualifiedName& name) const
 
 SPECIALIZE_TYPE_TRAITS_BEGIN(WebCore::HTMLElement)
     static bool isType(const WebCore::Node& node) { return node.isHTMLElement(); }
+    static bool isType(const WebCore::EventTarget& target) { return is<WebCore::Node>(target) && isType(downcast<WebCore::Node>(target)); }
 SPECIALIZE_TYPE_TRAITS_END()
 
 #include "HTMLElementTypeHelpers.h"
index 498979c..ae800ab 100644 (file)
@@ -140,8 +140,7 @@ void HTMLFormElement::removedFromAncestor(RemovalType removalType, ContainerNode
 
 void HTMLFormElement::handleLocalEvents(Event& event)
 {
-    auto targetNode = event.target()->toNode();
-    if (event.eventPhase() != Event::CAPTURING_PHASE && targetNode && targetNode != this && (event.type() == eventNames().submitEvent || event.type() == eventNames().resetEvent)) {
+    if (event.eventPhase() != Event::CAPTURING_PHASE && is<Node>(event.target()) && event.target() != this && (event.type() == eventNames().submitEvent || event.type() == eventNames().resetEvent)) {
         event.stopPropagation();
         return;
     }
@@ -206,15 +205,6 @@ void HTMLFormElement::submitImplicitly(Event& event, bool fromImplicitSubmission
         prepareForSubmission(event);
 }
 
-static inline RefPtr<HTMLFormControlElement> submitElementFromEvent(const Event& event)
-{
-    for (RefPtr<Node> node = event.target()->toNode(); node; node = node->parentNode()) {
-        if (is<HTMLFormControlElement>(*node))
-            return downcast<HTMLFormControlElement>(node.get());
-    }
-    return nullptr;
-}
-
 bool HTMLFormElement::validateInteractively()
 {
     for (auto& associatedElement : m_associatedElements) {
@@ -269,9 +259,11 @@ void HTMLFormElement::prepareForSubmission(Event& event)
 
     bool shouldValidate = document().page() && document().page()->settings().interactiveFormValidationEnabled() && !noValidate();
 
-    auto submitElement = submitElementFromEvent(event);
-    if (submitElement && submitElement->formNoValidate())
-        shouldValidate = false;
+    if (shouldValidate) {
+        auto submitElement = findSubmitButton(&event);
+        if (submitElement && submitElement->formNoValidate())
+            shouldValidate = false;
+    }
 
     // Interactive validation must be done before dispatching the submit event.
     if (shouldValidate && !validateInteractively()) {
@@ -676,13 +668,11 @@ bool HTMLFormElement::wasUserSubmitted() const
 
 HTMLFormControlElement* HTMLFormElement::findSubmitButton(const Event* event) const
 {
-    if (event && event->target()) {
-        for (auto node = event->target()->toNode(); node; node = node->parentNode()) {
-            if (is<HTMLFormControlElement>(*node))
-                return downcast<HTMLFormControlElement>(node.get());
-        }
-    }
-    return nullptr;
+    if (!event || !is<Node>(event->target()))
+        return nullptr;
+    auto& node = downcast<Node>(*event->target());
+    auto* element = is<Element>(node) ? &downcast<Element>(node) : node.parentElement();
+    return element ? lineageOfType<HTMLFormControlElement>(*element).first() : nullptr;
 }
 
 HTMLFormControlElement* HTMLFormElement::defaultButton() const
index a795a5f..0d95c9b 100644 (file)
@@ -113,27 +113,28 @@ void HTMLLabelElement::defaultEventHandler(Event& event)
     static bool processingClick = false;
 
     if (event.type() == eventNames().clickEvent && !processingClick) {
-        RefPtr<LabelableElement> element = control();
+        auto control = this->control();
 
         // If we can't find a control or if the control received the click
         // event, then there's no need for us to do anything.
-        if (!element || (event.target() && element->containsIncludingShadowDOM(event.target()->toNode().get())))
+        if (!control || (is<Node>(event.target()) && control->containsIncludingShadowDOM(&downcast<Node>(*event.target())))) {
+            HTMLElement::defaultEventHandler(event);
             return;
+        }
 
         processingClick = true;
 
-        // Click the corresponding control.
-        element->dispatchSimulatedClick(&event);
+        control->dispatchSimulatedClick(&event);
 
         document().updateLayoutIgnorePendingStylesheets();
-        if (element->isMouseFocusable())
-            element->focus();
+        if (control->isMouseFocusable())
+            control->focus();
 
         processingClick = false;
-        
+
         event.setDefaultHandled();
     }
-    
+
     HTMLElement::defaultEventHandler(event);
 }
 
index 3bf3953..fb5e54f 100644 (file)
@@ -395,19 +395,19 @@ void HTMLPlugInImageElement::didAddUserAgentShadowRoot(ShadowRoot& root)
     scope.clearException();
 }
 
-bool HTMLPlugInImageElement::partOfSnapshotOverlay(const Node* node) const
+bool HTMLPlugInImageElement::partOfSnapshotOverlay(const EventTarget* target) const
 {
     static NeverDestroyed<AtomicString> selector(".snapshot-overlay", AtomicString::ConstructFromLiteral);
     auto shadow = userAgentShadowRoot();
     if (!shadow)
         return false;
-    if (!node)
+    if (!is<Node>(target))
         return false;
     auto queryResult = shadow->querySelector(selector.get());
     if (queryResult.hasException())
         return false;
     auto snapshotLabel = makeRefPtr(queryResult.releaseReturnValue());
-    return snapshotLabel && snapshotLabel->contains(node);
+    return snapshotLabel && snapshotLabel->contains(downcast<Node>(target));
 }
 
 void HTMLPlugInImageElement::removeSnapshotTimerFired()
index 377997a..a798b0f 100644 (file)
@@ -57,7 +57,7 @@ public:
     void subframeLoaderDidCreatePlugIn(const Widget&);
 
     WEBCORE_EXPORT void setIsPrimarySnapshottedPlugIn(bool);
-    bool partOfSnapshotOverlay(const Node*) const;
+    bool partOfSnapshotOverlay(const EventTarget*) const;
 
     bool needsCheckForSizeChange() const { return m_needsCheckForSizeChange; }
     void setNeedsCheckForSizeChange() { m_needsCheckForSizeChange = true; }
index 776cb21..2390e91 100644 (file)
@@ -91,16 +91,12 @@ bool HTMLSummaryElement::isActiveSummary() const
     return details->isActiveSummary(*this);
 }
 
-static bool isClickableControl(Node* node)
+static bool isClickableControl(EventTarget* target)
 {
-    ASSERT(node);
-    if (!is<Element>(*node))
+    if (!is<Element>(target))
         return false;
-    Element& element = downcast<Element>(*node);
-    if (is<HTMLFormControlElement>(element))
-        return true;
-    RefPtr<Element> host = element.shadowHost();
-    return host && is<HTMLFormControlElement>(host);
+    auto& element = downcast<Element>(*target);
+    return is<HTMLFormControlElement>(element) || is<HTMLFormControlElement>(element.shadowHost());
 }
 
 bool HTMLSummaryElement::supportsFocus() const
@@ -111,7 +107,7 @@ bool HTMLSummaryElement::supportsFocus() const
 void HTMLSummaryElement::defaultEventHandler(Event& event)
 {
     if (isActiveSummary() && renderer()) {
-        if (event.type() == eventNames().DOMActivateEvent && !isClickableControl(event.target()->toNode().get())) {
+        if (event.type() == eventNames().DOMActivateEvent && !isClickableControl(event.target())) {
             if (RefPtr<HTMLDetailsElement> details = detailsElement())
                 details->toggleOpen();
             event.setDefaultHandled();
index 85078a3..14c8e70 100644 (file)
@@ -171,4 +171,5 @@ HTMLTextFormControlElement* enclosingTextFormControl(const Position&);
 SPECIALIZE_TYPE_TRAITS_BEGIN(WebCore::HTMLTextFormControlElement)
     static bool isType(const WebCore::Element& element) { return element.isTextFormControl(); }
     static bool isType(const WebCore::Node& node) { return is<WebCore::Element>(node) && isType(downcast<WebCore::Element>(node)); }
+    static bool isType(const WebCore::EventTarget& target) { return is<WebCore::Node>(target) && isType(downcast<WebCore::Node>(target)); }
 SPECIALIZE_TYPE_TRAITS_END()
index aaa058c..0c8ee04 100644 (file)
@@ -185,11 +185,11 @@ void MediaDocument::defaultEventHandler(Event& event)
     
     // Match the default Quicktime plugin behavior to allow
     // clicking and double-clicking to pause and play the media.
-    auto targetNode = event.target()->toNode();
-    if (!targetNode)
+    if (!is<Node>(event.target()))
         return;
+    auto& targetNode = downcast<Node>(*event.target());
 
-    if (RefPtr<HTMLVideoElement> video = ancestorVideoElement(targetNode.get())) {
+    if (auto video = makeRefPtr(ancestorVideoElement(&targetNode))) {
         if (event.type() == eventNames().clickEvent) {
             if (!video->canPlay()) {
                 video->pause();
@@ -203,15 +203,16 @@ void MediaDocument::defaultEventHandler(Event& event)
         }
     }
 
-    if (!is<ContainerNode>(*targetNode))
+    if (!is<ContainerNode>(targetNode))
         return;
-    ContainerNode& targetContainer = downcast<ContainerNode>(*targetNode);
+    auto& targetContainer = downcast<ContainerNode>(targetNode);
+
     if (event.type() == eventNames().keydownEvent && is<KeyboardEvent>(event)) {
-        RefPtr<HTMLVideoElement> video = descendantVideoElement(targetContainer);
+        auto video = makeRefPtr(descendantVideoElement(targetContainer));
         if (!video)
             return;
 
-        KeyboardEvent& keyboardEvent = downcast<KeyboardEvent>(event);
+        auto& keyboardEvent = downcast<KeyboardEvent>(event);
         if (keyboardEvent.keyIdentifier() == "U+0020") { // space
             if (video->paused()) {
                 if (video->canPlay())
index 4eef285..7c5b819 100644 (file)
@@ -134,22 +134,24 @@ bool RangeInputType::isSteppable() const
 }
 
 #if !PLATFORM(IOS)
+
 void RangeInputType::handleMouseDownEvent(MouseEvent& event)
 {
     if (element().isDisabledFormControl())
         return;
 
-    auto targetNode = event.target()->toNode();
-    if (event.button() != LeftButton || !targetNode)
+    if (event.button() != LeftButton || !is<Node>(event.target()))
         return;
     ASSERT(element().shadowRoot());
-    if (targetNode != &element() && !targetNode->isDescendantOf(element().userAgentShadowRoot().get()))
+    auto& targetNode = downcast<Node>(*event.target());
+    if (&targetNode != &element() && !targetNode.isDescendantOf(element().userAgentShadowRoot().get()))
         return;
-    SliderThumbElement& thumb = typedSliderThumbElement();
-    if (targetNode == &thumb)
+    auto& thumb = typedSliderThumbElement();
+    if (&targetNode == &thumb)
         return;
     thumb.dragFrom(event.absoluteLocation());
 }
+
 #endif
 
 #if ENABLE(TOUCH_EVENTS)
index dc68bfd..4dbcad2 100644 (file)
@@ -337,16 +337,15 @@ RenderPtr<RenderElement> MediaControlVolumeSliderContainerElement::createElement
 
 void MediaControlVolumeSliderContainerElement::defaultEventHandler(Event& event)
 {
+    // Poor man's mouseleave event detection.
+
     if (!is<MouseEvent>(event) || event.type() != eventNames().mouseoutEvent)
         return;
 
-    // Poor man's mouseleave event detection.
-    MouseEvent& mouseEvent = downcast<MouseEvent>(event);
-    EventTarget* relatedTarget = mouseEvent.relatedTarget();
-    if (!relatedTarget || !relatedTarget->toNode())
+    if (!is<Node>(downcast<MouseEvent>(event).relatedTarget()))
         return;
 
-    if (this->containsIncludingShadowDOM(relatedTarget->toNode().get()))
+    if (containsIncludingShadowDOM(&downcast<Node>(*downcast<MouseEvent>(event).relatedTarget())))
         return;
 
     hide();
@@ -688,8 +687,7 @@ void MediaControlClosedCaptionsTrackListElement::defaultEventHandler(Event& even
 {
 #if ENABLE(VIDEO_TRACK)
     if (event.type() == eventNames().clickEvent) {
-        RefPtr<Node> target = event.target()->toNode();
-        if (!is<Element>(target))
+        if (!is<Element>(event.target()))
             return;
 
         // When we created the elements in the track list, we gave them a custom
@@ -697,10 +695,7 @@ void MediaControlClosedCaptionsTrackListElement::defaultEventHandler(Event& even
         // Check if the event target has such a custom element and, if so,
         // tell the HTMLMediaElement to enable that track.
 
-        RefPtr<TextTrack> textTrack;
-        MenuItemToTrackMap::iterator iter = m_menuToTrackMap.find(downcast<Element>(target.get()));
-        if (iter != m_menuToTrackMap.end())
-            textTrack = iter->value;
+        auto textTrack = makeRefPtr(m_menuToTrackMap.get(&downcast<Element>(*event.target())));
         m_menuToTrackMap.clear();
         m_controls->toggleClosedCaptionTrackList();
         if (!textTrack)
index bdee1bb..a0e1067 100644 (file)
@@ -360,10 +360,8 @@ bool MediaControls::containsRelatedTarget(Event& event)
 {
     if (!is<MouseEvent>(event))
         return false;
-    EventTarget* relatedTarget = downcast<MouseEvent>(event).relatedTarget();
-    if (!relatedTarget)
-        return false;
-    return contains(relatedTarget->toNode().get());
+    auto relatedTarget = downcast<MouseEvent>(event).relatedTarget();
+    return is<Node>(relatedTarget) && contains(&downcast<Node>(*relatedTarget));
 }
 
 #if ENABLE(VIDEO_TRACK)
index b345497..e816403 100644 (file)
@@ -407,7 +407,7 @@ void InspectorFrontendHost::dispatchEventAsContextMenuEvent(Event& event)
 
     auto& mouseEvent = downcast<MouseEvent>(event);
     IntPoint mousePoint { mouseEvent.clientX(), mouseEvent.clientY() };
-    auto& frame = *mouseEvent.target()->toNode()->document().frame();
+    auto& frame = *downcast<Node>(mouseEvent.target())->document().frame();
 
     m_frontendPage->contextMenuController().showContextMenuAt(frame, mousePoint);
 #else
index 167fda4..769bc6d 100644 (file)
@@ -2257,11 +2257,10 @@ void InspectorDOMAgent::pseudoElementDestroyed(PseudoElement& pseudoElement)
 
 void InspectorDOMAgent::didAddEventListener(EventTarget& target)
 {
-    auto node = target.toNode();
-    if (!node)
+    if (!is<Node>(target))
         return;
 
-    int nodeId = boundNodeId(node.get());
+    int nodeId = boundNodeId(&downcast<Node>(target));
     if (!nodeId)
         return;
 
@@ -2270,16 +2269,16 @@ void InspectorDOMAgent::didAddEventListener(EventTarget& target)
 
 void InspectorDOMAgent::willRemoveEventListener(EventTarget& target, const AtomicString& eventType, EventListener& listener, bool capture)
 {
-    auto node = target.toNode();
-    if (!node)
+    if (!is<Node>(target))
         return;
+    auto& node = downcast<Node>(target);
 
-    int nodeId = boundNodeId(node.get());
+    int nodeId = boundNodeId(&node);
     if (!nodeId)
         return;
 
     bool listenerExists = false;
-    for (const RefPtr<RegisteredEventListener>& item : node->eventListeners(eventType)) {
+    for (auto& item : node.eventListeners(eventType)) {
         if (item->callback() == listener && item->useCapture() == capture) {
             listenerExists = true;
             break;
index 66be80b..68be91e 100644 (file)
@@ -150,10 +150,10 @@ std::unique_ptr<ContextMenu> ContextMenuController::maybeCreateContextMenu(Event
         return nullptr;
 
     auto& mouseEvent = downcast<MouseEvent>(event);
-    auto node = mouseEvent.target()->toNode();
-    if (!node)
+    if (!is<Node>(mouseEvent.target()))
         return nullptr;
-    auto* frame = node->document().frame();
+    auto& node = downcast<Node>(*mouseEvent.target());
+    auto* frame = node.document().frame();
     if (!frame)
         return nullptr;
 
@@ -164,7 +164,7 @@ std::unique_ptr<ContextMenu> ContextMenuController::maybeCreateContextMenu(Event
     m_context = ContextMenuContext(result);
 
 #if ENABLE(SERVICE_CONTROLS)
-    if (node->isImageControlsButtonElement()) {
+    if (node.isImageControlsButtonElement()) {
         if (auto* image = imageFromImageElementNode(*result.innerNonSharedNode()))
             m_context.setControlledImage(image);
 
index 9e1e670..f0a45e3 100644 (file)
@@ -447,11 +447,6 @@ DOMWindow::~DOMWindow()
     removeLanguageChangeObserver(this);
 }
 
-DOMWindow* DOMWindow::toDOMWindow()
-{
-    return this;
-}
-
 RefPtr<MediaQueryList> DOMWindow::matchMedia(const String& media)
 {
     return document() ? document()->mediaQueryMatcher().matchMedia(media) : nullptr;
index 94c2f29..184b792 100644 (file)
@@ -341,8 +341,6 @@ private:
     EventTargetInterface eventTargetInterface() const final { return DOMWindowEventTargetInterfaceType; }
     ScriptExecutionContext* scriptExecutionContext() const final { return ContextDestructionObserver::scriptExecutionContext(); }
 
-    DOMWindow* toDOMWindow() final;
-
     Page* page();
     bool allowedToChangeWindowGeometry() const;
 
@@ -431,3 +429,7 @@ inline String DOMWindow::defaultStatus() const
 }
 
 } // namespace WebCore
+
+SPECIALIZE_TYPE_TRAITS_BEGIN(WebCore::DOMWindow)
+    static bool isType(const WebCore::EventTarget& target) { return target.eventTargetInterface() == WebCore::DOMWindowEventTargetInterfaceType; }
+SPECIALIZE_TYPE_TRAITS_END()
index 989ecbd..d82a96c 100644 (file)
@@ -4116,12 +4116,12 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
             // No hittest is performed on move or stationary, since the target is not allowed to change anyway.
             touchTarget = m_originatingTouchPointTargets.get(touchPointTargetKey);
 
-        if (!touchTarget.get())
+        if (!is<Node>(touchTarget))
             continue;
-        Document& doc = touchTarget->toNode()->document();
-        if (!doc.hasTouchEventHandlers())
+        auto& document = downcast<Node>(*touchTarget).document();
+        if (!document.hasTouchEventHandlers())
             continue;
-        Frame* targetFrame = doc.frame();
+        auto* targetFrame = document.frame();
         if (!targetFrame)
             continue;
 
@@ -4181,16 +4181,17 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
         RefPtr<TouchList>& effectiveTouches(isTouchCancelEvent ? emptyList : touches);
         const AtomicString& stateName(eventNameForTouchPointState(static_cast<PlatformTouchPoint::State>(state)));
 
-        for (auto& taget : changedTouches[state].m_targets) {
-            EventTarget* touchEventTarget = taget.get();
-            RefPtr<TouchList> targetTouches(isTouchCancelEvent ? emptyList : touchesByTarget.get(touchEventTarget));
+        for (auto& target : changedTouches[state].m_targets) {
+            ASSERT(is<Node>(target));
+
+            RefPtr<TouchList> targetTouches(isTouchCancelEvent ? emptyList : touchesByTarget.get(target.get()));
             ASSERT(targetTouches);
 
             Ref<TouchEvent> touchEvent =
                 TouchEvent::create(effectiveTouches.get(), targetTouches.get(), changedTouches[state].m_touches.get(),
-                    stateName, touchEventTarget->toNode()->document().defaultView(),
+                    stateName, downcast<Node>(*target).document().defaultView(),
                     0, 0, 0, 0, event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey());
-            touchEventTarget->dispatchEvent(touchEvent);
+            target->dispatchEvent(touchEvent);
             swallowedEvent = swallowedEvent || touchEvent->defaultPrevented() || touchEvent->defaultHandled();
         }
     }
index b5ad561..98f9403 100644 (file)
@@ -124,7 +124,7 @@ public:
         if (MemoryPressureHandler::singleton().isUnderMemoryPressure())
             return nullptr;
 
-        if (static_cast<unsigned>(text.length()) > SmallStringKey::capacity())
+        if (text.length() > SmallStringKey::capacity())
             return nullptr;
 
         if (m_countdown > 0) {
@@ -150,7 +150,7 @@ public:
         // If we allow tabs and a tab occurs inside a word, the width of the word varies based on its position on the line.
         if (run.allowTabs())
             return nullptr;
-        if (static_cast<unsigned>(run.length()) > SmallStringKey::capacity())
+        if (run.length() > SmallStringKey::capacity())
             return nullptr;
 
         if (m_countdown > 0) {
index 1fca9e1..dbba4dc 100644 (file)
@@ -178,7 +178,7 @@ void RenderSnapshottedPlugIn::handleEvent(Event& event)
 
     if (mouseEvent.type() == eventNames().clickEvent || (m_isPotentialMouseActivation && mouseEvent.type() == eventNames().mouseupEvent)) {
         m_isPotentialMouseActivation = false;
-        bool clickWasOnOverlay = plugInImageElement().partOfSnapshotOverlay(mouseEvent.target()->toNode().get());
+        bool clickWasOnOverlay = plugInImageElement().partOfSnapshotOverlay(mouseEvent.target());
         plugInImageElement().userDidClickSnapshot(mouseEvent, !clickWasOnOverlay);
         mouseEvent.setDefaultHandled();
     } else if (mouseEvent.type() == eventNames().mousedownEvent) {
index e1891a6..7d8b715 100644 (file)
@@ -1,3 +1,21 @@
+2017-11-12  Darin Adler  <darin@apple.com>
+
+        More is<> and downcast<>, less static_cast<>
+        https://bugs.webkit.org/show_bug.cgi?id=179600
+
+        Reviewed by Chris Dumez.
+
+        * WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMPrivate.cpp:
+        (WebKit::wrap): Use is/downcast.
+        * WebProcess/WebCoreSupport/gtk/WebEditorClientGtk.cpp:
+        (WebKit::WebEditorClient::handleKeyboardEvent): Ditto.
+        * WebProcess/WebCoreSupport/wpe/WebEditorClientWPE.cpp:
+        (WebKit::WebEditorClient::handleKeyboardEvent): Ditto.
+        * WebProcess/WebPage/WebPage.cpp:
+        (WebKit::WebPage::handleEditingKeyboardEvent): Ditto.
+        * WebProcess/WebPage/mac/WebPageMac.mm:
+        (WebKit::frameForEvent): Ditto.
+
 2017-11-12  Gabriel Ivascu  <givascu@igalia.com>
 
         [GTK] Add functionality to handle font sizes in points
index 8634fe4..e6618ae 100644 (file)
@@ -104,17 +104,14 @@ WebKitDOMEvent* wrap(Event* event)
 {
     ASSERT(event);
 
-    if (event->isUIEvent()) {
-        if (event->isMouseEvent())
-            return WEBKIT_DOM_EVENT(wrapMouseEvent(static_cast<MouseEvent*>(event)));
-
-        if (event->isKeyboardEvent())
-            return WEBKIT_DOM_EVENT(wrapKeyboardEvent(static_cast<KeyboardEvent*>(event)));
-
-        if (event->eventInterface() == WheelEventInterfaceType)
-            return WEBKIT_DOM_EVENT(wrapWheelEvent(static_cast<WheelEvent*>(event)));
-
-        return WEBKIT_DOM_EVENT(wrapUIEvent(static_cast<UIEvent*>(event)));
+    if (is<UIEvent>(*event)) {
+        if (is<MouseEvent>(*event))
+            return WEBKIT_DOM_EVENT(wrapMouseEvent(&downcast<MouseEvent>(*event)));
+        if (is<KeyboardEvent>(*event))
+            return WEBKIT_DOM_EVENT(wrapKeyboardEvent(&downcast<KeyboardEvent>(*event)));
+        if (is<WheelEvent>(*event))
+            return WEBKIT_DOM_EVENT(wrapWheelEvent(&downcast<WheelEvent>(*event)));
+        return WEBKIT_DOM_EVENT(wrapUIEvent(&downcast<UIEvent>(*event)));
     }
 
     return wrapEvent(event);
@@ -142,13 +139,11 @@ WebKitDOMEventTarget* wrap(EventTarget* eventTarget)
 {
     ASSERT(eventTarget);
 
-    if (auto node = eventTarget->toNode())
-        return WEBKIT_DOM_EVENT_TARGET(kit(node.get()));
-
-    if (DOMWindow* window = eventTarget->toDOMWindow())
-        return WEBKIT_DOM_EVENT_TARGET(kit(window));
-
-    return 0;
+    if (is<Node>(*eventTarget))
+        return WEBKIT_DOM_EVENT_TARGET(kit(&downcast<Node>(*eventTarget)));
+    if (is<DOMWindow>(*eventTarget))
+        return WEBKIT_DOM_EVENT_TARGET(kit(&downcast<DOMWindow>(*eventTarget)));
+    return nullptr;
 }
 
 WebKitDOMBlob* wrap(Blob* blob)
index a04b417..fb6c9e5 100644 (file)
@@ -63,9 +63,8 @@ void WebEditorClient::handleKeyboardEvent(KeyboardEvent* event)
     if (platformEvent->handledByInputMethod())
         return;
 
-    auto node = event->target()->toNode();
-    ASSERT(node);
-    Frame* frame = node->document().frame();
+    ASSERT(event->target());
+    auto* frame = downcast<Node>(event->target())->document().frame();
     ASSERT(frame);
 
     const Vector<String> pendingEditorCommands = platformEvent->commands();
index 1e9138e..5b45ba5 100644 (file)
@@ -208,9 +208,8 @@ static void handleKeyDown(Frame& frame, KeyboardEvent& event, const PlatformKeyb
 
 void WebEditorClient::handleKeyboardEvent(WebCore::KeyboardEvent* event)
 {
-    auto node = event->target()->toNode();
-    ASSERT(node);
-    Frame* frame = node->document().frame();
+    ASSERT(event->target());
+    auto* frame = downcast<Node>(event->target())->document().frame();
     ASSERT(frame);
 
     // FIXME: Reorder the checks in a more sensible way.
index 9711b90..9f44599 100644 (file)
@@ -3243,11 +3243,10 @@ NotificationPermissionRequestManager* WebPage::notificationPermissionRequestMana
 }
 
 #if !PLATFORM(GTK) && !PLATFORM(COCOA) && !PLATFORM(WPE)
+
 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
 {
-    auto node = evt->target()->toNode();
-    ASSERT(node);
-    Frame* frame = node->document().frame();
+    Frame* frame = downcast<Node>(*evt->target()).document().frame();
     ASSERT(frame);
 
     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
@@ -3276,6 +3275,7 @@ bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
 
     return frame->editor().insertText(evt->keyEvent()->text(), evt);
 }
+
 #endif
 
 #if ENABLE(DRAG_SUPPORT)
index b70d739..6c008f7 100644 (file)
@@ -224,9 +224,8 @@ static String commandNameForSelectorName(const String& selectorName)
 
 static Frame* frameForEvent(KeyboardEvent* event)
 {
-    auto node = event->target()->toNode();
-    ASSERT(node);
-    Frame* frame = node->document().frame();
+    ASSERT(event->target());
+    Frame* frame = downcast<Node>(event->target())->document().frame();
     ASSERT(frame);
     return frame;
 }
index fa09681..5bd2514 100644 (file)
@@ -1,3 +1,18 @@
+2017-11-12  Darin Adler  <darin@apple.com>
+
+        More is<> and downcast<>, less static_cast<>
+        https://bugs.webkit.org/show_bug.cgi?id=179600
+
+        Reviewed by Chris Dumez.
+
+        * DOM/DOM.mm:
+        (kit): Use is/downcast.
+        * WebCoreSupport/WebEditorClient.mm:
+        (WebEditorClient::handleKeyboardEvent): Ditto.
+        (WebEditorClient::handleInputMethodKeydown): Ditto.
+        * WebView/WebHTMLView.mm:
+        (-[WebHTMLView _interpretKeyEvent:savingCommands:]): Ditto.
+
 2017-11-10  Frederik Riedel  <frederik.riedel@frogg.io>
 
         [iOS] Use new class name from UIKit when checking UITextSuggestion type for WebKitLegacy
index 50afb19..59f1363 100644 (file)
@@ -301,17 +301,10 @@ Class kitClass(Node* impl)
     return nil;
 }
 
-id <DOMEventTarget> kit(EventTarget* eventTarget)
+id <DOMEventTarget> kit(EventTarget* target)
 {
-    if (!eventTarget)
-        return nil;
-
-    if (auto node = eventTarget->toNode())
-        return kit(node.get());
-
-    // We don't have an ObjC binding for XMLHttpRequest.
-
-    return nil;
+    // We don't have Objective-C bindings for XMLHttpRequest, DOMWindow, and other non-Node targets.
+    return is<Node>(target) ? kit(downcast<Node>(target)) : nil;
 }
 
 @implementation DOMNode (DOMNodeExtensions)
index 523d22e..7957e34 100644 (file)
@@ -746,7 +746,7 @@ void WebEditorClient::redo()
 
 void WebEditorClient::handleKeyboardEvent(KeyboardEvent* event)
 {
-    Frame* frame = event->target()->toNode()->document().frame();
+    auto* frame = downcast<Node>(event->target())->document().frame();
 #if !PLATFORM(IOS)
     WebHTMLView *webHTMLView = [[kit(frame) frameView] documentView];
     if ([webHTMLView _interpretKeyEvent:event savingCommands:NO])
@@ -762,7 +762,7 @@ void WebEditorClient::handleInputMethodKeydown(KeyboardEvent* event)
 {
 #if !PLATFORM(IOS)
     // FIXME: Switch to WebKit2 model, interpreting the event before it's sent down to WebCore.
-    Frame* frame = event->target()->toNode()->document().frame();
+    auto* frame = downcast<Node>(event->target())->document().frame();
     WebHTMLView *webHTMLView = [[kit(frame) frameView] documentView];
     if ([webHTMLView _interpretKeyEvent:event savingCommands:YES])
         event->setDefaultHandled();
index 689bef0..54a72be 100644 (file)
@@ -6146,7 +6146,7 @@ static BOOL writingDirectionKeyBindingsEnabled()
 
 - (BOOL)_interpretKeyEvent:(KeyboardEvent*)event savingCommands:(BOOL)savingCommands
 {
-    ASSERT(core([self _frame]) == event->target()->toNode()->document().frame());
+    ASSERT(core([self _frame]) == downcast<Node>(event->target())->document().frame());
     ASSERT(!savingCommands || event->keypressCommands().isEmpty()); // Save commands once for each event.
 
     WebHTMLViewInterpretKeyEventsParameters parameters;
index 012b87b..cfbc338 100644 (file)
@@ -1,3 +1,13 @@
+2017-11-12  Darin Adler  <darin@apple.com>
+
+        More is<> and downcast<>, less static_cast<>
+        https://bugs.webkit.org/show_bug.cgi?id=179600
+
+        Reviewed by Chris Dumez.
+
+        * WebView.cpp:
+        (WebView::handleEditingKeyboardEvent): Use downcast.
+
 2017-11-09  Christopher Reid  <chris.reid@sony.com>
 
         Use enum classes within FileSystem
index 31499aa..0ed3e33 100644 (file)
@@ -2342,9 +2342,7 @@ const char* WebView::interpretKeyEvent(const KeyboardEvent* evt)
 
 bool WebView::handleEditingKeyboardEvent(KeyboardEvent* evt)
 {
-    auto node = evt->target()->toNode();
-    ASSERT(node);
-    Frame* frame = node->document().frame();
+    auto* frame = downcast<Node>(evt->target())->document().frame();
     ASSERT(frame);
 
     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();