bool InputMethodContext::hasFocus() const
{
    LocalFrame* frame = m_element->document().frame();
    if (!frame)
        return false;

    const Element* element = frame->document()->focusedElement();
    return element && element->isHTMLElement() && m_element == toHTMLElement(element);
}
static float pageZoomFactor(const UIEvent* event)
{
    if (!event->view() || !event->view()->isLocalDOMWindow())
        return 1;
    LocalFrame* frame = toLocalDOMWindow(event->view())->frame();
    if (!frame)
        return 1;
    return frame->pageZoomFactor();
}
Example #3
0
void HTMLPlugInElement::registerAsRenderless(Widget* widget)
{
    if (!widget || !widget->isPluginView())
        return;

    LocalFrame* frame = toPluginView(widget)->pluginFrame();
    ASSERT(frame);
    frame->registerPluginElement(this);
}
int HTMLTextFormControlElement::computeSelectionEnd() const
{
    ASSERT(isTextFormControl());
    LocalFrame* frame = document().frame();
    if (!frame)
        return 0;

    return indexForVisiblePosition(VisiblePosition(frame->selection().end()));
}
int HTMLTextFormControlElement::computeSelectionStart() const
{
    ASSERT(isTextFormControl());
    LocalFrame* frame = document().frame();
    if (!frame)
        return 0;

    return indexForPosition(innerEditorElement(), frame->selection().start());
}
bool FocusController::advanceFocusInDocumentOrder(FocusType type, bool initialFocus)
{
    LocalFrame* frame = focusedOrMainFrame();
    ASSERT(frame);
    Document* document = frame->document();

    Node* currentNode = document->focusedElement();

    document->updateLayout();

    RefPtr<Node> node = findFocusableNodeAcrossFocusScope(type, FocusNavigationScope::focusNavigationScopeOf(currentNode ? currentNode : document), currentNode);

    if (!node) {
        // We didn't find a node to focus, so we should try to pass focus to Chrome.
        if (!initialFocus && m_page->canTakeFocus(type)) {
            document->setFocusedElement(nullptr);
            setFocusedFrame(nullptr);
            m_page->takeFocus(type);
            return true;
        }

        // Chrome doesn't want focus, so we should wrap focus.
        node = findFocusableNodeRecursively(type, FocusNavigationScope::focusNavigationScopeOf(m_page->mainFrame()->document()), 0);
        node = findFocusableNodeDecendingDownIntoFrameDocument(type, node.get());

        if (!node)
            return false;
    }

    ASSERT(node);

    if (node == document->focusedElement())
        // Focus wrapped around to the same node.
        return true;

    if (!node->isElementNode())
        // FIXME: May need a way to focus a document here.
        return false;

    Element* element = toElement(node);

    // FIXME: It would be nice to just be able to call setFocusedElement(node)
    // here, but we can't do that because some elements (e.g. HTMLInputElement
    // and HTMLTextAreaElement) do extra work in their focus() methods.
    Document& newDocument = element->document();

    if (&newDocument != document) {
        // Focus is going away from this document, so clear the focused node.
        document->setFocusedElement(nullptr);
    }

    setFocusedFrame(newDocument.frame());

    element->focus(false, type);
    return true;
}
Example #7
0
static void localToPageQuad(const RenderObject& renderer, const LayoutRect& rect, FloatQuad* quad)
{
    LocalFrame* frame = renderer.frame();
    FrameView* view = frame->view();
    FloatQuad absolute = renderer.localToAbsoluteQuad(FloatQuad(rect));
    quad->setP1(view->contentsToRootView(roundedIntPoint(absolute.p1())));
    quad->setP2(view->contentsToRootView(roundedIntPoint(absolute.p2())));
    quad->setP3(view->contentsToRootView(roundedIntPoint(absolute.p3())));
    quad->setP4(view->contentsToRootView(roundedIntPoint(absolute.p4())));
}
Example #8
0
bool HTMLPlugInElement::unregisterAsRenderlessIfNeeded()
{
    if (!m_persistedPluginWidget || !m_persistedPluginWidget->isPluginView())
        return false;

    LocalFrame* frame = toPluginView(m_persistedPluginWidget.get())->pluginFrame();
    ASSERT(frame);
    frame->unregisterPluginElement(this);
    return true;
}
Example #9
0
void BlockPainter::paintCarets(const PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
    LocalFrame* frame = m_layoutBlock.frame();

    if (m_layoutBlock.hasCursorCaret())
        frame->selection().paintCaret(paintInfo.context, paintOffset);

    if (m_layoutBlock.hasDragCaret())
        frame->page()->dragCaretController().paintDragCaret(frame, paintInfo.context, paintOffset);
}
void TextFinder::unmarkAllTextMatches()
{
    LocalFrame* frame = ownerFrame().frame();
    if (frame && frame->page() && frame->editor().markedTextMatchesAreHighlighted()) {
        if (ownerFrame().client() && ownerFrame().client()->shouldSearchSingleFrame())
            frame->document()->markers().removeMarkers(DocumentMarker::TextMatch);
        else
            frame->page()->unmarkAllTextMatches();
    }
}
Example #11
0
void Page::setTimerAlignmentInterval(double interval)
{
    if (interval == m_timerAlignmentInterval)
        return;

    m_timerAlignmentInterval = interval;
    LocalFrame* frame = mainFrame();
    if (frame->document())
        frame->document()->didChangeTimerAlignmentInterval();
}
Example #12
0
bool SVGImage::hasAnimations() const
{
    if (!m_page)
        return false;
    LocalFrame* frame = m_page->mainFrame();
    SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
    if (!rootElement)
        return false;
    return rootElement->timeContainer()->hasAnimations() || frame->document()->timeline().hasPendingUpdates();
}
Example #13
0
void SVGImage::stopAnimation()
{
    if (!m_page)
        return;
    LocalFrame* frame = m_page->mainFrame();
    SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
    if (!rootElement)
        return;
    rootElement->pauseAnimations();
}
Example #14
0
bool SVGImage::hasRelativeHeight() const
{
    if (!m_page)
        return false;
    LocalFrame* frame = m_page->mainFrame();
    SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
    if (!rootElement)
        return false;
    return rootElement->intrinsicHeight().isPercent();
}
Example #15
0
RenderBox* SVGImage::embeddedContentBox() const
{
    if (!m_page)
        return 0;
    LocalFrame* frame = m_page->mainFrame();
    SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
    if (!rootElement)
        return 0;
    return toRenderBox(rootElement->renderer());
}
TEST(MediaQueryEvaluatorTest, DynamicNoView) {
  std::unique_ptr<DummyPageHolder> pageHolder =
      DummyPageHolder::create(IntSize(500, 500));
  LocalFrame* frame = &pageHolder->frame();
  pageHolder.reset();
  ASSERT_EQ(nullptr, frame->view());
  MediaQueryEvaluator mediaQueryEvaluator(frame);
  MediaQuerySet* querySet = MediaQuerySet::create("foobar");
  EXPECT_FALSE(mediaQueryEvaluator.eval(querySet));
}
Example #17
0
static float pageZoomFactor(const UIEvent* event)
{
    DOMWindow* window = event->view();
    if (!window)
        return 1;
    LocalFrame* frame = window->frame();
    if (!frame)
        return 1;
    return frame->pageZoomFactor();
}
TextFieldSelectionDirection HTMLTextFormControlElement::computeSelectionDirection() const
{
    ASSERT(isTextFormControl());
    LocalFrame* frame = document().frame();
    if (!frame)
        return SelectionHasNoDirection;

    const VisibleSelection& selection = frame->selection().selection();
    return selection.isDirectional() ? (selection.isBaseFirst() ? SelectionHasForwardDirection : SelectionHasBackwardDirection) : SelectionHasNoDirection;
}
Example #19
0
IntSize PinchViewport::contentsSize() const
{
    LocalFrame* frame = mainFrame();

    if (!frame || !frame->view())
        return IntSize();

    ASSERT(frame->view()->visibleContentScaleFactor() == 1);
    return frame->view()->visibleContentRect(IncludeScrollbars).size();
}
Example #20
0
void SpellChecker::toggleContinuousSpellChecking()
{
    spellCheckerClient().toggleContinuousSpellChecking();
    if (isContinuousSpellCheckingEnabled())
        return;
    LocalFrame* frame = m_frame.page()->mainFrame();
    for (Node* node = &frame->document()->rootNode(); node; node = NodeTraversal::next(*node)) {
        node->setAlreadySpellChecked(false);
    }
}
Example #21
0
void TypingCommand::insertText(Document& document, const String& text, Options options, TextCompositionType composition)
{
    LocalFrame* frame = document.frame();
    ASSERT(frame);

    if (!text.isEmpty())
        document.frame()->spellChecker().updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0]));

    insertText(document, text, frame->selection().selection(), options, composition);
}
Example #22
0
// static
WebRange WebRange::fromDocumentRange(WebLocalFrame* frame, int start, int length)
{
    LocalFrame* webFrame = toWebLocalFrameImpl(frame)->frame();
    Element* selectionRoot = webFrame->selection().rootEditableElement();
    ContainerNode* scope = selectionRoot ? selectionRoot : webFrame->document()->documentElement();
    const EphemeralRange range = PlainTextRange(start, start + length).createRange(*scope);
    if (range.isNull())
        return WebRange();
    return Range::create(range.document(), range.startPosition(), range.endPosition());
}
Example #23
0
PassOwnPtrWillBeRawPtr<WebGLRenderingContext> WebGLRenderingContext::create(HTMLCanvasElement* canvas, WebGLContextAttributes* attrs)
{
    Document& document = canvas->document();
    LocalFrame* frame = document.frame();
    if (!frame) {
        canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, "Web page was not allowed to create a WebGL context."));
        return nullptr;
    }
    Settings* settings = frame->settings();

    // The FrameLoaderClient might block creation of a new WebGL context despite the page settings; in
    // particular, if WebGL contexts were lost one or more times via the GL_ARB_robustness extension.
    if (!frame->loader().client()->allowWebGL(settings && settings->webGLEnabled())) {
        canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, "Web page was not allowed to create a WebGL context."));
        return nullptr;
    }

    // The only situation that attrs is null is through Document::getCSSCanvasContext().
    RefPtrWillBeRawPtr<WebGLContextAttributes> defaultAttrs = nullptr;
    if (!attrs) {
        defaultAttrs = WebGLContextAttributes::create();
        attrs = defaultAttrs.get();
    }
    blink::WebGraphicsContext3D::Attributes attributes = attrs->attributes(document.topDocument().url().string(), settings, 1);
    blink::WebGLInfo glInfo;
    OwnPtr<blink::WebGraphicsContext3D> context = adoptPtr(blink::Platform::current()->createOffscreenGraphicsContext3D(attributes, 0, &glInfo));
    if (!context) {
        String statusMessage("Could not create a WebGL context for VendorInfo = ");
        statusMessage.append(glInfo.vendorInfo);
        statusMessage.append(", RendererInfo = ");
        statusMessage.append(glInfo.rendererInfo);
        statusMessage.append(", DriverInfo = ");
        statusMessage.append(glInfo.driverVersion);
        statusMessage.append(".");
        canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, statusMessage));
        return nullptr;
    }

    OwnPtr<Extensions3DUtil> extensionsUtil = Extensions3DUtil::create(context.get());
    if (!extensionsUtil)
        return nullptr;
    if (extensionsUtil->supportsExtension("GL_EXT_debug_marker"))
        context->pushGroupMarkerEXT("WebGLRenderingContext");

    OwnPtrWillBeRawPtr<WebGLRenderingContext> renderingContext = adoptPtrWillBeNoop(new WebGLRenderingContext(canvas, context.release(), attrs));
    renderingContext->registerContextExtensions();
    renderingContext->suspendIfNeeded();

    if (!renderingContext->drawingBuffer()) {
        canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, "Could not create a WebGL context."));
        return nullptr;
    }

    return renderingContext.release();
}
Example #24
0
void DocumentLoader::willSendRequest(ResourceRequest& newRequest, const ResourceResponse& redirectResponse)
{
    // Note that there are no asserts here as there are for the other callbacks. This is due to the
    // fact that this "callback" is sent when starting every load, and the state of callback
    // deferrals plays less of a part in this function in preventing the bad behavior deferring
    // callbacks is meant to prevent.
    ASSERT(!newRequest.isNull());
    if (isFormSubmission(m_triggeringAction.type()) && !m_frame->document()->contentSecurityPolicy()->allowFormAction(newRequest.url())) {
        cancelMainResourceLoad(ResourceError::cancelledError(newRequest.url()));
        return;
    }

    ASSERT(timing()->fetchStart());
    if (!redirectResponse.isNull()) {
        // If the redirecting url is not allowed to display content from the target origin,
        // then block the redirect.
        RefPtr<SecurityOrigin> redirectingOrigin = SecurityOrigin::create(redirectResponse.url());
        if (!redirectingOrigin->canDisplay(newRequest.url())) {
            FrameLoader::reportLocalLoadFailed(m_frame, newRequest.url().string());
            cancelMainResourceLoad(ResourceError::cancelledError(newRequest.url()));
            return;
        }
        timing()->addRedirect(redirectResponse.url(), newRequest.url());
    }

    // Update cookie policy base URL as URL changes, except for subframes, which use the
    // URL of the main frame which doesn't change when we redirect.
    if (frameLoader()->isLoadingMainFrame())
        newRequest.setFirstPartyForCookies(newRequest.url());

    // If we're fielding a redirect in response to a POST, force a load from origin, since
    // this is a common site technique to return to a page viewing some data that the POST
    // just modified.
    if (newRequest.cachePolicy() == UseProtocolCachePolicy && isRedirectAfterPost(newRequest, redirectResponse))
        newRequest.setCachePolicy(ReloadIgnoringCacheData);

    // If this is a sub-frame, check for mixed content blocking against the top frame.
    if (m_frame->tree().parent()) {
        LocalFrame* top = m_frame->tree().top();
        if (!top->loader().mixedContentChecker()->canRunInsecureContent(top->document()->securityOrigin(), newRequest.url())) {
            cancelMainResourceLoad(ResourceError::cancelledError(newRequest.url()));
            return;
        }
    }

    m_request = newRequest;

    if (redirectResponse.isNull())
        return;

    appendRedirect(newRequest.url());
    frameLoader()->client()->dispatchDidReceiveServerRedirectForProvisionalLoad();
    if (!shouldContinueForNavigationPolicy(newRequest))
        cancelMainResourceLoad(ResourceError::cancelledError(m_request.url()));
}
bool HTMLPlugInElement::loadPlugin(const KURL& url, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback, bool requireLayoutObject)
{
    LocalFrame* frame = document().frame();

    if (!frame->loader().allowPlugins(AboutToInstantiatePlugin))
        return false;

    LayoutEmbeddedObject* layoutObject = layoutEmbeddedObject();
    // FIXME: This code should not depend on layoutObject!
    if ((!layoutObject && requireLayoutObject) || useFallback)
        return false;

    WTF_LOG(Plugins, "%p Plugin URL: %s", this, m_url.utf8().data());
    WTF_LOG(Plugins, "   Loaded URL: %s", url.string().utf8().data());
    m_loadedUrl = url;

    OwnPtrWillBeRawPtr<PluginPlaceholder> placeholder = nullptr;
    RefPtrWillBeRawPtr<Widget> widget = m_persistedPluginWidget;
    if (!widget) {
        bool loadManually = document().isPluginDocument() && !document().containsPlugins();
        placeholder = frame->loader().client()->createPluginPlaceholder(document(), url, paramNames, paramValues, mimeType, loadManually);
        if (!placeholder) {
            FrameLoaderClient::DetachedPluginPolicy policy = requireLayoutObject ? FrameLoaderClient::FailOnDetachedPlugin : FrameLoaderClient::AllowDetachedPlugin;
            widget = frame->loader().client()->createPlugin(this, url, paramNames, paramValues, mimeType, loadManually, policy);
        }
    }

    if (!placeholder && !widget) {
        if (layoutObject && !layoutObject->showsUnavailablePluginIndicator())
            layoutObject->setPluginUnavailabilityReason(LayoutEmbeddedObject::PluginMissing);
        setPlaceholder(nullptr);
        return false;
    }

    if (placeholder) {
        setPlaceholder(placeholder.release());
        return true;
    }

    if (layoutObject) {
        setWidget(widget);
        setPersistedPluginWidget(nullptr);
    } else {
        setPersistedPluginWidget(widget.get());
    }
    setPlaceholder(nullptr);
    document().setContainsPlugins();
    scheduleSVGFilterLayerUpdateHack();
    // Make sure any input event handlers introduced by the plugin are taken into account.
    if (Page* page = document().frame()->page()) {
        if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
            scrollingCoordinator->notifyLayoutUpdated();
    }
    return true;
}
Example #26
0
void createWindowForRequest(const FrameLoadRequest& request, LocalFrame& openerFrame, NavigationPolicy policy, ShouldSendReferrer shouldSendReferrer)
{
    if (openerFrame.document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
        return;

    if (openerFrame.document() && openerFrame.document()->isSandboxed(SandboxPopups))
        return;

    if (!DOMWindow::allowPopUp(openerFrame))
        return;

    if (policy == NavigationPolicyCurrentTab)
        policy = NavigationPolicyNewForegroundTab;

    WindowFeatures features;
    bool created;
    LocalFrame* newFrame = createWindow(openerFrame, openerFrame, request, features, policy, shouldSendReferrer, created);
    if (!newFrame)
        return;
    newFrame->page()->setOpenedByDOM();
    if (shouldSendReferrer == MaybeSendReferrer) {
        newFrame->loader().setOpener(&openerFrame);
        newFrame->document()->setReferrerPolicy(openerFrame.document()->referrerPolicy());
    }
    FrameLoadRequest newRequest(0, request.resourceRequest());
    newRequest.setFormState(request.formState());
    newFrame->loader().load(newRequest);
}
Example #27
0
float GlossyMaterial::getDirectionSampleProbDensity(const Ray& inRay, const Ray& outRay) const
{
	if(!outRay.contactObject)
		return 0;
	LocalFrame lf;
	vec3f normal = outRay.getContactNormal();
	vec3f reflDir = -normal.dot(inRay.direction)*normal*2 + inRay.direction;
	lf.buildFromNormal(reflDir);
	vec3f coeff = coeffTex.getColor(outRay.contactObject->getTexCoord(outRay.contactObjectTriangleID, outRay.origin));
	return cosineSphericalSampler.getProbDensity(lf, outRay.direction, coeff.x);
}
Example #28
0
bool SelectorChecker::matchesFocusPseudoClass(const Element& element)
{
    if (!element.focused())
        return false;
    LocalFrame* frame = element.document().frame();
    if (!frame)
        return false;
    if (!frame->selection().isFocusedAndActive())
        return false;
    return true;
}
DOMWindow* createWindow(const String& urlString, const AtomicString& frameName, const WindowFeatures& windowFeatures,
    LocalDOMWindow& callingWindow, LocalFrame& firstFrame, LocalFrame& openerFrame)
{
    LocalFrame* activeFrame = callingWindow.frame();
    ASSERT(activeFrame);

    KURL completedURL = urlString.isEmpty() ? KURL(ParsedURLString, emptyString()) : firstFrame.document()->completeURL(urlString);
    if (!completedURL.isEmpty() && !completedURL.isValid()) {
        // Don't expose client code to invalid URLs.
        callingWindow.printErrorMessage("Unable to open a window with invalid URL '" + completedURL.getString() + "'.\n");
        return nullptr;
    }

    FrameLoadRequest frameRequest(callingWindow.document(), completedURL, frameName);
    frameRequest.setShouldSetOpener(windowFeatures.noopener ? NeverSetOpener : MaybeSetOpener);
    frameRequest.resourceRequest().setFrameType(WebURLRequest::FrameTypeAuxiliary);
    frameRequest.resourceRequest().setRequestorOrigin(SecurityOrigin::create(activeFrame->document()->url()));

    // Normally, FrameLoader would take care of setting the referrer for a navigation that is
    // triggered from javascript. However, creating a window goes through sufficient processing
    // that it eventually enters FrameLoader as an embedder-initiated navigation. FrameLoader
    // assumes no responsibility for generating an embedder-initiated navigation's referrer,
    // so we need to ensure the proper referrer is set now.
    frameRequest.resourceRequest().setHTTPReferrer(SecurityPolicy::generateReferrer(activeFrame->document()->getReferrerPolicy(), completedURL, activeFrame->document()->outgoingReferrer()));

    // Records HasUserGesture before the value is invalidated inside createWindow(LocalFrame& openerFrame, ...).
    // This value will be set in ResourceRequest loaded in a new LocalFrame.
    bool hasUserGesture = UserGestureIndicator::processingUserGesture();

    // We pass the opener frame for the lookupFrame in case the active frame is different from
    // the opener frame, and the name references a frame relative to the opener frame.
    bool created;
    Frame* newFrame = createWindowHelper(openerFrame, *activeFrame, openerFrame, frameRequest, windowFeatures, NavigationPolicyIgnore, created);
    if (!newFrame)
        return nullptr;
    if (newFrame->domWindow()->isInsecureScriptAccess(callingWindow, completedURL))
        return newFrame->domWindow();

    // TODO(dcheng): Special case for window.open("about:blank") to ensure it loads synchronously into
    // a new window. This is our historical behavior, and it's consistent with the creation of
    // a new iframe with src="about:blank". Perhaps we could get rid of this if we started reporting
    // the initial empty document's url as about:blank? See crbug.com/471239.
    // TODO(japhet): This special case is also necessary for behavior asserted by some extensions tests.
    // Using NavigationScheduler::scheduleNavigationChange causes the navigation to be flagged as a
    // client redirect, which is observable via the webNavigation extension api.
    if (created) {
        FrameLoadRequest request(callingWindow.document(), completedURL);
        request.resourceRequest().setHasUserGesture(hasUserGesture);
        newFrame->navigate(request);
    } else if (!urlString.isEmpty()) {
        newFrame->navigate(*callingWindow.document(), completedURL, false, hasUserGesture ? UserGestureStatus::Active : UserGestureStatus::None);
    }
    return newFrame->domWindow();
}
Example #30
0
bool MockPagePopup::initialize()
{
    const char scriptToSetUpPagePopupController[] = "<script>window.pagePopupController = parent.internals.pagePopupController;</script>";
    RefPtr<SharedBuffer> data = SharedBuffer::create(scriptToSetUpPagePopupController, sizeof(scriptToSetUpPagePopupController));
    m_popupClient->writeDocument(data.get());
    LocalFrame* localFrame = toLocalFrame(m_iframe->contentFrame());
    if (!localFrame)
        return false;
    localFrame->loader().load(FrameLoadRequest(0, blankURL(), SubstituteData(data, "text/html", "UTF-8", KURL(), ForceSynchronousLoad)));
    return true;
}