summaryrefslogtreecommitdiff
path: root/Source/WebCore/html/canvas/CanvasRenderingContext2D.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'Source/WebCore/html/canvas/CanvasRenderingContext2D.cpp')
-rw-r--r--[-rwxr-xr-x]Source/WebCore/html/canvas/CanvasRenderingContext2D.cpp2009
1 files changed, 1116 insertions, 893 deletions
diff --git a/Source/WebCore/html/canvas/CanvasRenderingContext2D.cpp b/Source/WebCore/html/canvas/CanvasRenderingContext2D.cpp
index dc55df0e3..5bd1c76f2 100755..100644
--- a/Source/WebCore/html/canvas/CanvasRenderingContext2D.cpp
+++ b/Source/WebCore/html/canvas/CanvasRenderingContext2D.cpp
@@ -1,12 +1,12 @@
/*
- * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2004-2017 Apple Inc. All rights reserved.
* Copyright (C) 2008, 2010 Nokia Corporation and/or its subsidiary(-ies)
* Copyright (C) 2007 Alp Toker <alp@atoker.com>
* Copyright (C) 2008 Eric Seidel <eric@webkit.org>
* Copyright (C) 2008 Dirk Schulze <krit@webkit.org>
* Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
* Copyright (C) 2012 Intel Corporation. All rights reserved.
- * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
+ * Copyright (C) 2013, 2014 Adobe Systems Incorporated. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -17,10 +17,10 @@
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
@@ -33,6 +33,7 @@
#include "config.h"
#include "CanvasRenderingContext2D.h"
+#include "BitmapImage.h"
#include "CSSFontSelector.h"
#include "CSSParser.h"
#include "CSSPropertyNames.h"
@@ -40,47 +41,68 @@
#include "CanvasGradient.h"
#include "CanvasPattern.h"
#include "DOMPath.h"
-#include "ExceptionCodePlaceholder.h"
+#include "DisplayListRecorder.h"
+#include "DisplayListReplayer.h"
#include "FloatQuad.h"
-#include "FontCache.h"
-#include "GraphicsContext.h"
#include "HTMLImageElement.h"
#include "HTMLVideoElement.h"
+#include "ImageBuffer.h"
#include "ImageData.h"
#include "RenderElement.h"
+#include "RenderImage.h"
+#include "RenderLayer.h"
+#include "RenderTheme.h"
#include "SecurityOrigin.h"
#include "StrokeStyleApplier.h"
#include "StyleProperties.h"
#include "StyleResolver.h"
#include "TextMetrics.h"
#include "TextRun.h"
-
-#if USE(ACCELERATED_COMPOSITING)
-#include "RenderLayer.h"
-#endif
-
+#include "TextStream.h"
#include <wtf/CheckedArithmetic.h>
#include <wtf/MathExtras.h>
+#include <wtf/NeverDestroyed.h>
#include <wtf/text/StringBuilder.h>
-#if USE(CG)
-#if !PLATFORM(IOS)
+#if USE(CG) && !PLATFORM(IOS)
#include <ApplicationServices/ApplicationServices.h>
-#endif // !PLATFORM(IOS)
-#endif
-
-#if PLATFORM(IOS)
-#include "Settings.h"
#endif
namespace WebCore {
using namespace HTMLNames;
+#if USE(CG)
+const CanvasRenderingContext2D::ImageSmoothingQuality defaultSmoothingQuality = CanvasRenderingContext2D::ImageSmoothingQuality::Low;
+#else
+const CanvasRenderingContext2D::ImageSmoothingQuality defaultSmoothingQuality = CanvasRenderingContext2D::ImageSmoothingQuality::Medium;
+#endif
+
static const int defaultFontSize = 10;
static const char* const defaultFontFamily = "sans-serif";
static const char* const defaultFont = "10px sans-serif";
+struct DisplayListDrawingContext {
+ WTF_MAKE_FAST_ALLOCATED;
+public:
+ GraphicsContext context;
+ DisplayList::Recorder recorder;
+ DisplayList::DisplayList displayList;
+
+ DisplayListDrawingContext(const FloatRect& clip)
+ : recorder(context, displayList, clip, AffineTransform())
+ {
+ }
+};
+
+typedef HashMap<const CanvasRenderingContext2D*, std::unique_ptr<DisplayList::DisplayList>> ContextDisplayListHashMap;
+
+static ContextDisplayListHashMap& contextDisplayListMap()
+{
+ static NeverDestroyed<ContextDisplayListHashMap> sharedHashMap;
+ return sharedHashMap;
+}
+
class CanvasStrokeStyleApplier : public StrokeStyleApplier {
public:
CanvasStrokeStyleApplier(CanvasRenderingContext2D* canvasContext)
@@ -88,7 +110,7 @@ public:
{
}
- virtual void strokeStyle(GraphicsContext* c) override
+ void strokeStyle(GraphicsContext* c) override
{
c->setStrokeThickness(m_canvasContext->lineWidth());
c->setLineCap(m_canvasContext->getLineCap());
@@ -105,10 +127,9 @@ private:
CanvasRenderingContext2D* m_canvasContext;
};
-CanvasRenderingContext2D::CanvasRenderingContext2D(HTMLCanvasElement* canvas, bool usesCSSCompatibilityParseMode, bool usesDashboardCompatibilityMode)
+CanvasRenderingContext2D::CanvasRenderingContext2D(HTMLCanvasElement& canvas, bool usesCSSCompatibilityParseMode, bool usesDashboardCompatibilityMode)
: CanvasRenderingContext(canvas)
, m_stateStack(1)
- , m_unrealizedSaveCount(0)
, m_usesCSSCompatibilityParseMode(usesCSSCompatibilityParseMode)
#if ENABLE(DASHBOARD_SUPPORT)
, m_usesDashboardCompatibilityMode(usesDashboardCompatibilityMode)
@@ -125,7 +146,7 @@ void CanvasRenderingContext2D::unwindStateStack()
// is cleared before destruction, to avoid assertions in the
// GraphicsContext dtor.
if (size_t stackSize = m_stateStack.size()) {
- if (GraphicsContext* context = canvas()->existingDrawingContext()) {
+ if (GraphicsContext* context = canvas().existingDrawingContext()) {
while (--stackSize)
context->restore();
}
@@ -137,14 +158,17 @@ CanvasRenderingContext2D::~CanvasRenderingContext2D()
#if !ASSERT_DISABLED
unwindStateStack();
#endif
+
+ if (UNLIKELY(tracksDisplayListReplay()))
+ contextDisplayListMap().remove(this);
}
bool CanvasRenderingContext2D::isAccelerated() const
{
#if USE(IOSURFACE_CANVAS_BACKING_STORE) || ENABLE(ACCELERATED_2D_CANVAS)
- if (!canvas()->hasCreatedImageBuffer())
+ if (!canvas().hasCreatedImageBuffer())
return false;
- GraphicsContext* context = drawingContext();
+ auto* context = drawingContext();
return context && context->isAcceleratedContext();
#else
return false;
@@ -158,58 +182,59 @@ void CanvasRenderingContext2D::reset()
m_stateStack.first() = State();
m_path.clear();
m_unrealizedSaveCount = 0;
+
+ m_recordingContext = nullptr;
}
CanvasRenderingContext2D::State::State()
- : m_strokeStyle(Color::black)
- , m_fillStyle(Color::black)
- , m_lineWidth(1)
- , m_lineCap(ButtCap)
- , m_lineJoin(MiterJoin)
- , m_miterLimit(10)
- , m_shadowBlur(0)
- , m_shadowColor(Color::transparent)
- , m_globalAlpha(1)
- , m_globalComposite(CompositeSourceOver)
- , m_globalBlend(BlendModeNormal)
- , m_hasInvertibleTransform(true)
- , m_lineDashOffset(0)
- , m_imageSmoothingEnabled(true)
- , m_textAlign(StartTextAlign)
- , m_textBaseline(AlphabeticTextBaseline)
- , m_unparsedFont(defaultFont)
- , m_realizedFont(false)
+ : strokeStyle(Color::black)
+ , fillStyle(Color::black)
+ , lineWidth(1)
+ , lineCap(ButtCap)
+ , lineJoin(MiterJoin)
+ , miterLimit(10)
+ , shadowBlur(0)
+ , shadowColor(Color::transparent)
+ , globalAlpha(1)
+ , globalComposite(CompositeSourceOver)
+ , globalBlend(BlendModeNormal)
+ , hasInvertibleTransform(true)
+ , lineDashOffset(0)
+ , imageSmoothingEnabled(true)
+ , imageSmoothingQuality(defaultSmoothingQuality)
+ , textAlign(StartTextAlign)
+ , textBaseline(AlphabeticTextBaseline)
+ , direction(Direction::Inherit)
+ , unparsedFont(defaultFont)
{
}
CanvasRenderingContext2D::State::State(const State& other)
- : FontSelectorClient()
- , m_unparsedStrokeColor(other.m_unparsedStrokeColor)
- , m_unparsedFillColor(other.m_unparsedFillColor)
- , m_strokeStyle(other.m_strokeStyle)
- , m_fillStyle(other.m_fillStyle)
- , m_lineWidth(other.m_lineWidth)
- , m_lineCap(other.m_lineCap)
- , m_lineJoin(other.m_lineJoin)
- , m_miterLimit(other.m_miterLimit)
- , m_shadowOffset(other.m_shadowOffset)
- , m_shadowBlur(other.m_shadowBlur)
- , m_shadowColor(other.m_shadowColor)
- , m_globalAlpha(other.m_globalAlpha)
- , m_globalComposite(other.m_globalComposite)
- , m_globalBlend(other.m_globalBlend)
- , m_transform(other.m_transform)
- , m_hasInvertibleTransform(other.m_hasInvertibleTransform)
- , m_lineDashOffset(other.m_lineDashOffset)
- , m_imageSmoothingEnabled(other.m_imageSmoothingEnabled)
- , m_textAlign(other.m_textAlign)
- , m_textBaseline(other.m_textBaseline)
- , m_unparsedFont(other.m_unparsedFont)
- , m_font(other.m_font)
- , m_realizedFont(other.m_realizedFont)
-{
- if (m_realizedFont)
- m_font.fontSelector()->registerForInvalidationCallbacks(this);
+ : unparsedStrokeColor(other.unparsedStrokeColor)
+ , unparsedFillColor(other.unparsedFillColor)
+ , strokeStyle(other.strokeStyle)
+ , fillStyle(other.fillStyle)
+ , lineWidth(other.lineWidth)
+ , lineCap(other.lineCap)
+ , lineJoin(other.lineJoin)
+ , miterLimit(other.miterLimit)
+ , shadowOffset(other.shadowOffset)
+ , shadowBlur(other.shadowBlur)
+ , shadowColor(other.shadowColor)
+ , globalAlpha(other.globalAlpha)
+ , globalComposite(other.globalComposite)
+ , globalBlend(other.globalBlend)
+ , transform(other.transform)
+ , hasInvertibleTransform(other.hasInvertibleTransform)
+ , lineDashOffset(other.lineDashOffset)
+ , imageSmoothingEnabled(other.imageSmoothingEnabled)
+ , imageSmoothingQuality(other.imageSmoothingQuality)
+ , textAlign(other.textAlign)
+ , textBaseline(other.textBaseline)
+ , direction(other.direction)
+ , unparsedFont(other.unparsedFont)
+ , font(other.font)
+{
}
CanvasRenderingContext2D::State& CanvasRenderingContext2D::State::operator=(const State& other)
@@ -217,50 +242,119 @@ CanvasRenderingContext2D::State& CanvasRenderingContext2D::State::operator=(cons
if (this == &other)
return *this;
- if (m_realizedFont)
- m_font.fontSelector()->unregisterForInvalidationCallbacks(this);
-
- m_unparsedStrokeColor = other.m_unparsedStrokeColor;
- m_unparsedFillColor = other.m_unparsedFillColor;
- m_strokeStyle = other.m_strokeStyle;
- m_fillStyle = other.m_fillStyle;
- m_lineWidth = other.m_lineWidth;
- m_lineCap = other.m_lineCap;
- m_lineJoin = other.m_lineJoin;
- m_miterLimit = other.m_miterLimit;
- m_shadowOffset = other.m_shadowOffset;
- m_shadowBlur = other.m_shadowBlur;
- m_shadowColor = other.m_shadowColor;
- m_globalAlpha = other.m_globalAlpha;
- m_globalComposite = other.m_globalComposite;
- m_globalBlend = other.m_globalBlend;
- m_transform = other.m_transform;
- m_hasInvertibleTransform = other.m_hasInvertibleTransform;
- m_imageSmoothingEnabled = other.m_imageSmoothingEnabled;
- m_textAlign = other.m_textAlign;
- m_textBaseline = other.m_textBaseline;
- m_unparsedFont = other.m_unparsedFont;
+ unparsedStrokeColor = other.unparsedStrokeColor;
+ unparsedFillColor = other.unparsedFillColor;
+ strokeStyle = other.strokeStyle;
+ fillStyle = other.fillStyle;
+ lineWidth = other.lineWidth;
+ lineCap = other.lineCap;
+ lineJoin = other.lineJoin;
+ miterLimit = other.miterLimit;
+ shadowOffset = other.shadowOffset;
+ shadowBlur = other.shadowBlur;
+ shadowColor = other.shadowColor;
+ globalAlpha = other.globalAlpha;
+ globalComposite = other.globalComposite;
+ globalBlend = other.globalBlend;
+ transform = other.transform;
+ hasInvertibleTransform = other.hasInvertibleTransform;
+ imageSmoothingEnabled = other.imageSmoothingEnabled;
+ imageSmoothingQuality = other.imageSmoothingQuality;
+ textAlign = other.textAlign;
+ textBaseline = other.textBaseline;
+ direction = other.direction;
+ unparsedFont = other.unparsedFont;
+ font = other.font;
+
+ return *this;
+}
+
+CanvasRenderingContext2D::FontProxy::~FontProxy()
+{
+ if (realized())
+ m_font.fontSelector()->unregisterForInvalidationCallbacks(*this);
+}
+
+CanvasRenderingContext2D::FontProxy::FontProxy(const FontProxy& other)
+ : m_font(other.m_font)
+{
+ if (realized())
+ m_font.fontSelector()->registerForInvalidationCallbacks(*this);
+}
+
+auto CanvasRenderingContext2D::FontProxy::operator=(const FontProxy& other) -> FontProxy&
+{
+ if (realized())
+ m_font.fontSelector()->unregisterForInvalidationCallbacks(*this);
+
m_font = other.m_font;
- m_realizedFont = other.m_realizedFont;
- if (m_realizedFont)
- m_font.fontSelector()->registerForInvalidationCallbacks(this);
+ if (realized())
+ m_font.fontSelector()->registerForInvalidationCallbacks(*this);
return *this;
}
-CanvasRenderingContext2D::State::~State()
+inline void CanvasRenderingContext2D::FontProxy::update(FontSelector& selector)
{
- if (m_realizedFont)
- m_font.fontSelector()->unregisterForInvalidationCallbacks(this);
+ ASSERT(&selector == m_font.fontSelector()); // This is an invariant. We should only ever be registered for callbacks on m_font.m_fonts.m_fontSelector.
+ if (realized())
+ m_font.fontSelector()->unregisterForInvalidationCallbacks(*this);
+ m_font.update(&selector);
+ if (realized())
+ m_font.fontSelector()->registerForInvalidationCallbacks(*this);
+ ASSERT(&selector == m_font.fontSelector());
}
-void CanvasRenderingContext2D::State::fontsNeedUpdate(FontSelector* fontSelector)
+void CanvasRenderingContext2D::FontProxy::fontsNeedUpdate(FontSelector& selector)
{
- ASSERT_ARG(fontSelector, fontSelector == m_font.fontSelector());
- ASSERT(m_realizedFont);
+ ASSERT_ARG(selector, &selector == m_font.fontSelector());
+ ASSERT(realized());
+
+ update(selector);
+}
- m_font.update(fontSelector);
+inline void CanvasRenderingContext2D::FontProxy::initialize(FontSelector& fontSelector, const RenderStyle& newStyle)
+{
+ // Beware! m_font.fontSelector() might not point to document.fontSelector()!
+ ASSERT(newStyle.fontCascade().fontSelector() == &fontSelector);
+ if (realized())
+ m_font.fontSelector()->unregisterForInvalidationCallbacks(*this);
+ m_font = newStyle.fontCascade();
+ m_font.update(&fontSelector);
+ ASSERT(&fontSelector == m_font.fontSelector());
+ m_font.fontSelector()->registerForInvalidationCallbacks(*this);
+}
+
+inline FontMetrics CanvasRenderingContext2D::FontProxy::fontMetrics() const
+{
+ return m_font.fontMetrics();
+}
+
+inline const FontCascadeDescription& CanvasRenderingContext2D::FontProxy::fontDescription() const
+{
+ return m_font.fontDescription();
+}
+
+inline float CanvasRenderingContext2D::FontProxy::width(const TextRun& textRun) const
+{
+ return m_font.width(textRun);
+}
+
+inline void CanvasRenderingContext2D::FontProxy::drawBidiText(GraphicsContext& context, const TextRun& run, const FloatPoint& point, FontCascade::CustomFontNotReadyAction action) const
+{
+ context.drawBidiText(m_font, run, point, action);
+}
+
+void CanvasRenderingContext2D::realizeSaves()
+{
+ if (m_unrealizedSaveCount)
+ realizeSavesLoop();
+
+ if (m_unrealizedSaveCount) {
+ static NeverDestroyed<String> consoleMessage(ASCIILiteral("CanvasRenderingContext2D.save() has been called without a matching restore() too many times. Ignoring save()."));
+ canvas().document().addConsoleMessage(MessageSource::Rendering, MessageLevel::Error, consoleMessage);
+ }
}
void CanvasRenderingContext2D::realizeSavesLoop()
@@ -269,6 +363,8 @@ void CanvasRenderingContext2D::realizeSavesLoop()
ASSERT(m_stateStack.size() >= 1);
GraphicsContext* context = drawingContext();
do {
+ if (m_stateStack.size() > MaxSaveCount)
+ break;
m_stateStack.append(state());
if (context)
context->save();
@@ -284,9 +380,10 @@ void CanvasRenderingContext2D::restore()
ASSERT(m_stateStack.size() >= 1);
if (m_stateStack.size() <= 1)
return;
- m_path.transform(state().m_transform);
+ m_path.transform(state().transform);
m_stateStack.removeLast();
- m_path.transform(state().m_transform.inverse());
+ if (std::optional<AffineTransform> inverse = state().transform.inverse())
+ m_path.transform(inverse.value());
GraphicsContext* c = drawingContext();
if (!c)
return;
@@ -298,25 +395,26 @@ void CanvasRenderingContext2D::setStrokeStyle(CanvasStyle style)
if (!style.isValid())
return;
- if (state().m_strokeStyle.isValid() && state().m_strokeStyle.isEquivalentColor(style))
+ if (state().strokeStyle.isValid() && state().strokeStyle.isEquivalentColor(style))
return;
if (style.isCurrentColor()) {
- if (style.hasOverrideAlpha())
- style = CanvasStyle(colorWithOverrideAlpha(currentColor(canvas()), style.overrideAlpha()));
- else
- style = CanvasStyle(currentColor(canvas()));
+ if (style.hasOverrideAlpha()) {
+ // FIXME: Should not use RGBA32 here.
+ style = CanvasStyle(colorWithOverrideAlpha(currentColor(&canvas()).rgb(), style.overrideAlpha()));
+ } else
+ style = CanvasStyle(currentColor(&canvas()));
} else
checkOrigin(style.canvasPattern());
realizeSaves();
State& state = modifiableState();
- state.m_strokeStyle = style;
+ state.strokeStyle = style;
GraphicsContext* c = drawingContext();
if (!c)
return;
- state.m_strokeStyle.applyStrokeColor(c);
- state.m_unparsedStrokeColor = String();
+ state.strokeStyle.applyStrokeColor(*c);
+ state.unparsedStrokeColor = String();
}
void CanvasRenderingContext2D::setFillStyle(CanvasStyle style)
@@ -324,40 +422,41 @@ void CanvasRenderingContext2D::setFillStyle(CanvasStyle style)
if (!style.isValid())
return;
- if (state().m_fillStyle.isValid() && state().m_fillStyle.isEquivalentColor(style))
+ if (state().fillStyle.isValid() && state().fillStyle.isEquivalentColor(style))
return;
if (style.isCurrentColor()) {
- if (style.hasOverrideAlpha())
- style = CanvasStyle(colorWithOverrideAlpha(currentColor(canvas()), style.overrideAlpha()));
- else
- style = CanvasStyle(currentColor(canvas()));
+ if (style.hasOverrideAlpha()) {
+ // FIXME: Should not use RGBA32 here.
+ style = CanvasStyle(colorWithOverrideAlpha(currentColor(&canvas()).rgb(), style.overrideAlpha()));
+ } else
+ style = CanvasStyle(currentColor(&canvas()));
} else
checkOrigin(style.canvasPattern());
realizeSaves();
State& state = modifiableState();
- state.m_fillStyle = style;
+ state.fillStyle = style;
GraphicsContext* c = drawingContext();
if (!c)
return;
- state.m_fillStyle.applyFillColor(c);
- state.m_unparsedFillColor = String();
+ state.fillStyle.applyFillColor(*c);
+ state.unparsedFillColor = String();
}
float CanvasRenderingContext2D::lineWidth() const
{
- return state().m_lineWidth;
+ return state().lineWidth;
}
void CanvasRenderingContext2D::setLineWidth(float width)
{
if (!(std::isfinite(width) && width > 0))
return;
- if (state().m_lineWidth == width)
+ if (state().lineWidth == width)
return;
realizeSaves();
- modifiableState().m_lineWidth = width;
+ modifiableState().lineWidth = width;
GraphicsContext* c = drawingContext();
if (!c)
return;
@@ -366,7 +465,7 @@ void CanvasRenderingContext2D::setLineWidth(float width)
String CanvasRenderingContext2D::lineCap() const
{
- return lineCapName(state().m_lineCap);
+ return lineCapName(state().lineCap);
}
void CanvasRenderingContext2D::setLineCap(const String& s)
@@ -374,10 +473,10 @@ void CanvasRenderingContext2D::setLineCap(const String& s)
LineCap cap;
if (!parseLineCap(s, cap))
return;
- if (state().m_lineCap == cap)
+ if (state().lineCap == cap)
return;
realizeSaves();
- modifiableState().m_lineCap = cap;
+ modifiableState().lineCap = cap;
GraphicsContext* c = drawingContext();
if (!c)
return;
@@ -386,7 +485,7 @@ void CanvasRenderingContext2D::setLineCap(const String& s)
String CanvasRenderingContext2D::lineJoin() const
{
- return lineJoinName(state().m_lineJoin);
+ return lineJoinName(state().lineJoin);
}
void CanvasRenderingContext2D::setLineJoin(const String& s)
@@ -394,10 +493,10 @@ void CanvasRenderingContext2D::setLineJoin(const String& s)
LineJoin join;
if (!parseLineJoin(s, join))
return;
- if (state().m_lineJoin == join)
+ if (state().lineJoin == join)
return;
realizeSaves();
- modifiableState().m_lineJoin = join;
+ modifiableState().lineJoin = join;
GraphicsContext* c = drawingContext();
if (!c)
return;
@@ -406,17 +505,17 @@ void CanvasRenderingContext2D::setLineJoin(const String& s)
float CanvasRenderingContext2D::miterLimit() const
{
- return state().m_miterLimit;
+ return state().miterLimit;
}
void CanvasRenderingContext2D::setMiterLimit(float limit)
{
if (!(std::isfinite(limit) && limit > 0))
return;
- if (state().m_miterLimit == limit)
+ if (state().miterLimit == limit)
return;
realizeSaves();
- modifiableState().m_miterLimit = limit;
+ modifiableState().miterLimit = limit;
GraphicsContext* c = drawingContext();
if (!c)
return;
@@ -425,72 +524,72 @@ void CanvasRenderingContext2D::setMiterLimit(float limit)
float CanvasRenderingContext2D::shadowOffsetX() const
{
- return state().m_shadowOffset.width();
+ return state().shadowOffset.width();
}
void CanvasRenderingContext2D::setShadowOffsetX(float x)
{
if (!std::isfinite(x))
return;
- if (state().m_shadowOffset.width() == x)
+ if (state().shadowOffset.width() == x)
return;
realizeSaves();
- modifiableState().m_shadowOffset.setWidth(x);
+ modifiableState().shadowOffset.setWidth(x);
applyShadow();
}
float CanvasRenderingContext2D::shadowOffsetY() const
{
- return state().m_shadowOffset.height();
+ return state().shadowOffset.height();
}
void CanvasRenderingContext2D::setShadowOffsetY(float y)
{
if (!std::isfinite(y))
return;
- if (state().m_shadowOffset.height() == y)
+ if (state().shadowOffset.height() == y)
return;
realizeSaves();
- modifiableState().m_shadowOffset.setHeight(y);
+ modifiableState().shadowOffset.setHeight(y);
applyShadow();
}
float CanvasRenderingContext2D::shadowBlur() const
{
- return state().m_shadowBlur;
+ return state().shadowBlur;
}
void CanvasRenderingContext2D::setShadowBlur(float blur)
{
if (!(std::isfinite(blur) && blur >= 0))
return;
- if (state().m_shadowBlur == blur)
+ if (state().shadowBlur == blur)
return;
realizeSaves();
- modifiableState().m_shadowBlur = blur;
+ modifiableState().shadowBlur = blur;
applyShadow();
}
String CanvasRenderingContext2D::shadowColor() const
{
- return Color(state().m_shadowColor).serialized();
+ return Color(state().shadowColor).serialized();
}
-void CanvasRenderingContext2D::setShadowColor(const String& color)
+void CanvasRenderingContext2D::setShadowColor(const String& colorString)
{
- RGBA32 rgba;
- if (!parseColorOrCurrentColor(rgba, color, canvas()))
+ Color color = parseColorOrCurrentColor(colorString, &canvas());
+ if (!color.isValid())
return;
- if (state().m_shadowColor == rgba)
+ if (state().shadowColor == color)
return;
realizeSaves();
- modifiableState().m_shadowColor = rgba;
+ modifiableState().shadowColor = color;
applyShadow();
}
const Vector<float>& CanvasRenderingContext2D::getLineDash() const
{
- return state().m_lineDash;
+ return state().lineDash;
}
static bool lineDashSequenceIsValid(const Vector<float>& dash)
@@ -508,11 +607,11 @@ void CanvasRenderingContext2D::setLineDash(const Vector<float>& dash)
return;
realizeSaves();
- modifiableState().m_lineDash = dash;
+ modifiableState().lineDash = dash;
// Spec requires the concatenation of two copies the dash list when the
// number of elements is odd
if (dash.size() % 2)
- modifiableState().m_lineDash.appendVector(dash);
+ modifiableState().lineDash.appendVector(dash);
applyLineDash();
}
@@ -523,60 +622,50 @@ void CanvasRenderingContext2D::setWebkitLineDash(const Vector<float>& dash)
return;
realizeSaves();
- modifiableState().m_lineDash = dash;
+ modifiableState().lineDash = dash;
applyLineDash();
}
float CanvasRenderingContext2D::lineDashOffset() const
{
- return state().m_lineDashOffset;
+ return state().lineDashOffset;
}
void CanvasRenderingContext2D::setLineDashOffset(float offset)
{
- if (!std::isfinite(offset) || state().m_lineDashOffset == offset)
+ if (!std::isfinite(offset) || state().lineDashOffset == offset)
return;
realizeSaves();
- modifiableState().m_lineDashOffset = offset;
+ modifiableState().lineDashOffset = offset;
applyLineDash();
}
-float CanvasRenderingContext2D::webkitLineDashOffset() const
-{
- return lineDashOffset();
-}
-
-void CanvasRenderingContext2D::setWebkitLineDashOffset(float offset)
-{
- setLineDashOffset(offset);
-}
-
void CanvasRenderingContext2D::applyLineDash() const
{
GraphicsContext* c = drawingContext();
if (!c)
return;
- DashArray convertedLineDash(state().m_lineDash.size());
- for (size_t i = 0; i < state().m_lineDash.size(); ++i)
- convertedLineDash[i] = static_cast<DashArrayElement>(state().m_lineDash[i]);
- c->setLineDash(convertedLineDash, state().m_lineDashOffset);
+ DashArray convertedLineDash(state().lineDash.size());
+ for (size_t i = 0; i < state().lineDash.size(); ++i)
+ convertedLineDash[i] = static_cast<DashArrayElement>(state().lineDash[i]);
+ c->setLineDash(convertedLineDash, state().lineDashOffset);
}
float CanvasRenderingContext2D::globalAlpha() const
{
- return state().m_globalAlpha;
+ return state().globalAlpha;
}
void CanvasRenderingContext2D::setGlobalAlpha(float alpha)
{
if (!(alpha >= 0 && alpha <= 1))
return;
- if (state().m_globalAlpha == alpha)
+ if (state().globalAlpha == alpha)
return;
realizeSaves();
- modifiableState().m_globalAlpha = alpha;
+ modifiableState().globalAlpha = alpha;
GraphicsContext* c = drawingContext();
if (!c)
return;
@@ -585,7 +674,7 @@ void CanvasRenderingContext2D::setGlobalAlpha(float alpha)
String CanvasRenderingContext2D::globalCompositeOperation() const
{
- return compositeOperatorName(state().m_globalComposite, state().m_globalBlend);
+ return compositeOperatorName(state().globalComposite, state().globalBlend);
}
void CanvasRenderingContext2D::setGlobalCompositeOperation(const String& operation)
@@ -594,11 +683,11 @@ void CanvasRenderingContext2D::setGlobalCompositeOperation(const String& operati
BlendMode blendMode = BlendModeNormal;
if (!parseCompositeAndBlendOperator(operation, op, blendMode))
return;
- if ((state().m_globalComposite == op) && (state().m_globalBlend == blendMode))
+ if ((state().globalComposite == op) && (state().globalBlend == blendMode))
return;
realizeSaves();
- modifiableState().m_globalComposite = op;
- modifiableState().m_globalBlend = blendMode;
+ modifiableState().globalComposite = op;
+ modifiableState().globalBlend = blendMode;
GraphicsContext* c = drawingContext();
if (!c)
return;
@@ -610,25 +699,25 @@ void CanvasRenderingContext2D::scale(float sx, float sy)
GraphicsContext* c = drawingContext();
if (!c)
return;
- if (!state().m_hasInvertibleTransform)
+ if (!state().hasInvertibleTransform)
return;
- if (!std::isfinite(sx) | !std::isfinite(sy))
+ if (!std::isfinite(sx) || !std::isfinite(sy))
return;
- AffineTransform newTransform = state().m_transform;
+ AffineTransform newTransform = state().transform;
newTransform.scaleNonUniform(sx, sy);
- if (state().m_transform == newTransform)
+ if (state().transform == newTransform)
return;
realizeSaves();
- if (!newTransform.isInvertible()) {
- modifiableState().m_hasInvertibleTransform = false;
+ if (!sx || !sy) {
+ modifiableState().hasInvertibleTransform = false;
return;
}
- modifiableState().m_transform = newTransform;
+ modifiableState().transform = newTransform;
c->scale(FloatSize(sx, sy));
m_path.transform(AffineTransform().scaleNonUniform(1.0 / sx, 1.0 / sy));
}
@@ -638,25 +727,20 @@ void CanvasRenderingContext2D::rotate(float angleInRadians)
GraphicsContext* c = drawingContext();
if (!c)
return;
- if (!state().m_hasInvertibleTransform)
+ if (!state().hasInvertibleTransform)
return;
if (!std::isfinite(angleInRadians))
return;
- AffineTransform newTransform = state().m_transform;
+ AffineTransform newTransform = state().transform;
newTransform.rotate(angleInRadians / piDouble * 180.0);
- if (state().m_transform == newTransform)
+ if (state().transform == newTransform)
return;
realizeSaves();
- if (!newTransform.isInvertible()) {
- modifiableState().m_hasInvertibleTransform = false;
- return;
- }
-
- modifiableState().m_transform = newTransform;
+ modifiableState().transform = newTransform;
c->rotate(angleInRadians);
m_path.transform(AffineTransform().rotate(-angleInRadians / piDouble * 180.0));
}
@@ -666,25 +750,20 @@ void CanvasRenderingContext2D::translate(float tx, float ty)
GraphicsContext* c = drawingContext();
if (!c)
return;
- if (!state().m_hasInvertibleTransform)
+ if (!state().hasInvertibleTransform)
return;
if (!std::isfinite(tx) | !std::isfinite(ty))
return;
- AffineTransform newTransform = state().m_transform;
+ AffineTransform newTransform = state().transform;
newTransform.translate(tx, ty);
- if (state().m_transform == newTransform)
+ if (state().transform == newTransform)
return;
realizeSaves();
- if (!newTransform.isInvertible()) {
- modifiableState().m_hasInvertibleTransform = false;
- return;
- }
-
- modifiableState().m_transform = newTransform;
+ modifiableState().transform = newTransform;
c->translate(tx, ty);
m_path.transform(AffineTransform().translate(-tx, -ty));
}
@@ -694,27 +773,26 @@ void CanvasRenderingContext2D::transform(float m11, float m12, float m21, float
GraphicsContext* c = drawingContext();
if (!c)
return;
- if (!state().m_hasInvertibleTransform)
+ if (!state().hasInvertibleTransform)
return;
if (!std::isfinite(m11) | !std::isfinite(m21) | !std::isfinite(dx) | !std::isfinite(m12) | !std::isfinite(m22) | !std::isfinite(dy))
return;
AffineTransform transform(m11, m12, m21, m22, dx, dy);
- AffineTransform newTransform = state().m_transform * transform;
- if (state().m_transform == newTransform)
+ AffineTransform newTransform = state().transform * transform;
+ if (state().transform == newTransform)
return;
realizeSaves();
- if (!newTransform.isInvertible()) {
- modifiableState().m_hasInvertibleTransform = false;
+ if (auto inverse = transform.inverse()) {
+ modifiableState().transform = newTransform;
+ c->concatCTM(transform);
+ m_path.transform(inverse.value());
return;
}
-
- modifiableState().m_transform = newTransform;
- c->concatCTM(transform);
- m_path.transform(transform.inverse());
+ modifiableState().hasInvertibleTransform = false;
}
void CanvasRenderingContext2D::setTransform(float m11, float m12, float m21, float m22, float dx, float dy)
@@ -726,100 +804,98 @@ void CanvasRenderingContext2D::setTransform(float m11, float m12, float m21, flo
if (!std::isfinite(m11) | !std::isfinite(m21) | !std::isfinite(dx) | !std::isfinite(m12) | !std::isfinite(m22) | !std::isfinite(dy))
return;
- AffineTransform ctm = state().m_transform;
- if (!ctm.isInvertible())
- return;
-
- realizeSaves();
-
- c->setCTM(canvas()->baseTransform());
- modifiableState().m_transform = AffineTransform();
- m_path.transform(ctm);
-
- modifiableState().m_hasInvertibleTransform = true;
+ resetTransform();
transform(m11, m12, m21, m22, dx, dy);
}
-void CanvasRenderingContext2D::setStrokeColor(const String& color)
+void CanvasRenderingContext2D::resetTransform()
{
- if (color == state().m_unparsedStrokeColor)
+ GraphicsContext* c = drawingContext();
+ if (!c)
return;
+
+ AffineTransform ctm = state().transform;
+ bool hasInvertibleTransform = state().hasInvertibleTransform;
+
realizeSaves();
- setStrokeStyle(CanvasStyle::createFromString(color, &canvas()->document()));
- modifiableState().m_unparsedStrokeColor = color;
+
+ c->setCTM(canvas().baseTransform());
+ modifiableState().transform = AffineTransform();
+
+ if (hasInvertibleTransform)
+ m_path.transform(ctm);
+
+ modifiableState().hasInvertibleTransform = true;
}
-void CanvasRenderingContext2D::setStrokeColor(float grayLevel)
+void CanvasRenderingContext2D::setStrokeColor(const String& color, std::optional<float> alpha)
{
- if (state().m_strokeStyle.isValid() && state().m_strokeStyle.isEquivalentRGBA(grayLevel, grayLevel, grayLevel, 1.0f))
+ if (alpha) {
+ setStrokeStyle(CanvasStyle::createFromStringWithOverrideAlpha(color, alpha.value()));
return;
- setStrokeStyle(CanvasStyle(grayLevel, 1.0f));
-}
+ }
-void CanvasRenderingContext2D::setStrokeColor(const String& color, float alpha)
-{
- setStrokeStyle(CanvasStyle::createFromStringWithOverrideAlpha(color, alpha));
+ if (color == state().unparsedStrokeColor)
+ return;
+
+ realizeSaves();
+ setStrokeStyle(CanvasStyle::createFromString(color, &canvas().document()));
+ modifiableState().unparsedStrokeColor = color;
}
void CanvasRenderingContext2D::setStrokeColor(float grayLevel, float alpha)
{
- if (state().m_strokeStyle.isValid() && state().m_strokeStyle.isEquivalentRGBA(grayLevel, grayLevel, grayLevel, alpha))
+ if (state().strokeStyle.isValid() && state().strokeStyle.isEquivalentRGBA(grayLevel, grayLevel, grayLevel, alpha))
return;
setStrokeStyle(CanvasStyle(grayLevel, alpha));
}
void CanvasRenderingContext2D::setStrokeColor(float r, float g, float b, float a)
{
- if (state().m_strokeStyle.isValid() && state().m_strokeStyle.isEquivalentRGBA(r, g, b, a))
+ if (state().strokeStyle.isValid() && state().strokeStyle.isEquivalentRGBA(r, g, b, a))
return;
setStrokeStyle(CanvasStyle(r, g, b, a));
}
void CanvasRenderingContext2D::setStrokeColor(float c, float m, float y, float k, float a)
{
- if (state().m_strokeStyle.isValid() && state().m_strokeStyle.isEquivalentCMYKA(c, m, y, k, a))
+ if (state().strokeStyle.isValid() && state().strokeStyle.isEquivalentCMYKA(c, m, y, k, a))
return;
setStrokeStyle(CanvasStyle(c, m, y, k, a));
}
-void CanvasRenderingContext2D::setFillColor(const String& color)
+void CanvasRenderingContext2D::setFillColor(const String& color, std::optional<float> alpha)
{
- if (color == state().m_unparsedFillColor)
+ if (alpha) {
+ setFillStyle(CanvasStyle::createFromStringWithOverrideAlpha(color, alpha.value()));
return;
- realizeSaves();
- setFillStyle(CanvasStyle::createFromString(color, &canvas()->document()));
- modifiableState().m_unparsedFillColor = color;
-}
+ }
-void CanvasRenderingContext2D::setFillColor(float grayLevel)
-{
- if (state().m_fillStyle.isValid() && state().m_fillStyle.isEquivalentRGBA(grayLevel, grayLevel, grayLevel, 1.0f))
+ if (color == state().unparsedFillColor)
return;
- setFillStyle(CanvasStyle(grayLevel, 1.0f));
-}
-void CanvasRenderingContext2D::setFillColor(const String& color, float alpha)
-{
- setFillStyle(CanvasStyle::createFromStringWithOverrideAlpha(color, alpha));
+ realizeSaves();
+ setFillStyle(CanvasStyle::createFromString(color, &canvas().document()));
+ modifiableState().unparsedFillColor = color;
}
void CanvasRenderingContext2D::setFillColor(float grayLevel, float alpha)
{
- if (state().m_fillStyle.isValid() && state().m_fillStyle.isEquivalentRGBA(grayLevel, grayLevel, grayLevel, alpha))
+ if (state().fillStyle.isValid() && state().fillStyle.isEquivalentRGBA(grayLevel, grayLevel, grayLevel, alpha))
return;
setFillStyle(CanvasStyle(grayLevel, alpha));
}
void CanvasRenderingContext2D::setFillColor(float r, float g, float b, float a)
{
- if (state().m_fillStyle.isValid() && state().m_fillStyle.isEquivalentRGBA(r, g, b, a))
+ if (state().fillStyle.isValid() && state().fillStyle.isEquivalentRGBA(r, g, b, a))
return;
setFillStyle(CanvasStyle(r, g, b, a));
}
void CanvasRenderingContext2D::setFillColor(float c, float m, float y, float k, float a)
{
- if (state().m_fillStyle.isValid() && state().m_fillStyle.isEquivalentCMYKA(c, m, y, k, a))
+ if (state().fillStyle.isValid() && state().fillStyle.isEquivalentCMYKA(c, m, y, k, a))
return;
setFillStyle(CanvasStyle(c, m, y, k, a));
}
@@ -829,22 +905,6 @@ void CanvasRenderingContext2D::beginPath()
m_path.clear();
}
-#if ENABLE(CANVAS_PATH)
-
-PassRefPtr<DOMPath> CanvasRenderingContext2D::currentPath()
-{
- return DOMPath::create(m_path);
-}
-
-void CanvasRenderingContext2D::setCurrentPath(DOMPath* path)
-{
- if (!path)
- return;
- m_path = path->path();
-}
-
-#endif
-
static bool validateRectForCanvas(float& x, float& y, float& width, float& height)
{
if (!std::isfinite(x) | !std::isfinite(y) | !std::isfinite(width) | !std::isfinite(height))
@@ -866,13 +926,13 @@ static bool validateRectForCanvas(float& x, float& y, float& width, float& heigh
return true;
}
-#if ENABLE(DASHBOARD_SUPPORT)
-void CanvasRenderingContext2D::clearPathForDashboardBackwardCompatibilityMode()
+inline void CanvasRenderingContext2D::clearPathForDashboardBackwardCompatibilityMode()
{
+#if ENABLE(DASHBOARD_SUPPORT)
if (m_usesDashboardCompatibilityMode)
m_path.clear();
-}
#endif
+}
static bool isFullCanvasCompositeMode(CompositeOperator op)
{
@@ -882,152 +942,197 @@ static bool isFullCanvasCompositeMode(CompositeOperator op)
return op == CompositeSourceIn || op == CompositeSourceOut || op == CompositeDestinationIn || op == CompositeDestinationAtop;
}
-static bool parseWinding(const String& windingRuleString, WindRule& windRule)
+static WindRule toWindRule(CanvasRenderingContext2D::WindingRule rule)
{
- if (windingRuleString == "nonzero")
- windRule = RULE_NONZERO;
- else if (windingRuleString == "evenodd")
- windRule = RULE_EVENODD;
- else
- return false;
-
- return true;
+ return rule == CanvasRenderingContext2D::WindingRule::Nonzero ? RULE_NONZERO : RULE_EVENODD;
}
-void CanvasRenderingContext2D::fill(const String& windingRuleString)
+void CanvasRenderingContext2D::fill(WindingRule windingRule)
{
- GraphicsContext* c = drawingContext();
+ fillInternal(m_path, windingRule);
+ clearPathForDashboardBackwardCompatibilityMode();
+}
+
+void CanvasRenderingContext2D::stroke()
+{
+ strokeInternal(m_path);
+ clearPathForDashboardBackwardCompatibilityMode();
+}
+
+void CanvasRenderingContext2D::clip(WindingRule windingRule)
+{
+ clipInternal(m_path, windingRule);
+ clearPathForDashboardBackwardCompatibilityMode();
+}
+
+void CanvasRenderingContext2D::fill(DOMPath& path, WindingRule windingRule)
+{
+ fillInternal(path.path(), windingRule);
+}
+
+void CanvasRenderingContext2D::stroke(DOMPath& path)
+{
+ strokeInternal(path.path());
+}
+
+void CanvasRenderingContext2D::clip(DOMPath& path, WindingRule windingRule)
+{
+ clipInternal(path.path(), windingRule);
+}
+
+void CanvasRenderingContext2D::fillInternal(const Path& path, WindingRule windingRule)
+{
+ auto* c = drawingContext();
if (!c)
return;
- if (!state().m_hasInvertibleTransform)
+ if (!state().hasInvertibleTransform)
return;
// If gradient size is zero, then paint nothing.
- Gradient* gradient = c->fillGradient();
+ auto* gradient = c->fillGradient();
if (gradient && gradient->isZeroSize())
return;
- if (!m_path.isEmpty()) {
- WindRule windRule = c->fillRule();
- WindRule newWindRule = RULE_NONZERO;
- if (!parseWinding(windingRuleString, newWindRule))
- return;
- c->setFillRule(newWindRule);
+ if (!path.isEmpty()) {
+ auto savedFillRule = c->fillRule();
+ c->setFillRule(toWindRule(windingRule));
- if (isFullCanvasCompositeMode(state().m_globalComposite)) {
- fullCanvasCompositedFill(m_path);
+ if (isFullCanvasCompositeMode(state().globalComposite)) {
+ beginCompositeLayer();
+ c->fillPath(path);
+ endCompositeLayer();
didDrawEntireCanvas();
- } else if (state().m_globalComposite == CompositeCopy) {
+ } else if (state().globalComposite == CompositeCopy) {
clearCanvas();
- c->fillPath(m_path);
+ c->fillPath(path);
didDrawEntireCanvas();
} else {
- c->fillPath(m_path);
- didDraw(m_path.fastBoundingRect());
+ c->fillPath(path);
+ didDraw(path.fastBoundingRect());
}
- c->setFillRule(windRule);
+ c->setFillRule(savedFillRule);
}
-
-#if ENABLE(DASHBOARD_SUPPORT)
- clearPathForDashboardBackwardCompatibilityMode();
-#endif
}
-void CanvasRenderingContext2D::stroke()
+void CanvasRenderingContext2D::strokeInternal(const Path& path)
{
- GraphicsContext* c = drawingContext();
+ auto* c = drawingContext();
if (!c)
return;
- if (!state().m_hasInvertibleTransform)
+ if (!state().hasInvertibleTransform)
return;
// If gradient size is zero, then paint nothing.
- Gradient* gradient = c->strokeGradient();
+ auto* gradient = c->strokeGradient();
if (gradient && gradient->isZeroSize())
return;
- if (!m_path.isEmpty()) {
- FloatRect dirtyRect = m_path.fastBoundingRect();
- inflateStrokeRect(dirtyRect);
-
- c->strokePath(m_path);
- didDraw(dirtyRect);
+ if (!path.isEmpty()) {
+ if (isFullCanvasCompositeMode(state().globalComposite)) {
+ beginCompositeLayer();
+ c->strokePath(path);
+ endCompositeLayer();
+ didDrawEntireCanvas();
+ } else if (state().globalComposite == CompositeCopy) {
+ clearCanvas();
+ c->strokePath(path);
+ didDrawEntireCanvas();
+ } else {
+ FloatRect dirtyRect = path.fastBoundingRect();
+ inflateStrokeRect(dirtyRect);
+ c->strokePath(path);
+ didDraw(dirtyRect);
+ }
}
-
-#if ENABLE(DASHBOARD_SUPPORT)
- clearPathForDashboardBackwardCompatibilityMode();
-#endif
}
-void CanvasRenderingContext2D::clip(const String& windingRuleString)
+void CanvasRenderingContext2D::clipInternal(const Path& path, WindingRule windingRule)
{
- GraphicsContext* c = drawingContext();
+ auto* c = drawingContext();
if (!c)
return;
- if (!state().m_hasInvertibleTransform)
- return;
-
- WindRule newWindRule = RULE_NONZERO;
- if (!parseWinding(windingRuleString, newWindRule))
+ if (!state().hasInvertibleTransform)
return;
realizeSaves();
- c->canvasClip(m_path, newWindRule);
-
-#if ENABLE(DASHBOARD_SUPPORT)
- clearPathForDashboardBackwardCompatibilityMode();
+ c->canvasClip(path, toWindRule(windingRule));
+}
+
+inline void CanvasRenderingContext2D::beginCompositeLayer()
+{
+#if !USE(CAIRO)
+ drawingContext()->beginTransparencyLayer(1);
#endif
}
-bool CanvasRenderingContext2D::isPointInPath(const float x, const float y, const String& windingRuleString)
+inline void CanvasRenderingContext2D::endCompositeLayer()
{
- GraphicsContext* c = drawingContext();
+#if !USE(CAIRO)
+ drawingContext()->endTransparencyLayer();
+#endif
+}
+
+bool CanvasRenderingContext2D::isPointInPath(float x, float y, WindingRule windingRule)
+{
+ return isPointInPathInternal(m_path, x, y, windingRule);
+}
+
+bool CanvasRenderingContext2D::isPointInStroke(float x, float y)
+{
+ return isPointInStrokeInternal(m_path, x, y);
+}
+
+bool CanvasRenderingContext2D::isPointInPath(DOMPath& path, float x, float y, WindingRule windingRule)
+{
+ return isPointInPathInternal(path.path(), x, y, windingRule);
+}
+
+bool CanvasRenderingContext2D::isPointInStroke(DOMPath& path, float x, float y)
+{
+ return isPointInStrokeInternal(path.path(), x, y);
+}
+
+bool CanvasRenderingContext2D::isPointInPathInternal(const Path& path, float x, float y, WindingRule windingRule)
+{
+ auto* c = drawingContext();
if (!c)
return false;
- if (!state().m_hasInvertibleTransform)
+ if (!state().hasInvertibleTransform)
return false;
- FloatPoint point(x, y);
- AffineTransform ctm = state().m_transform;
- FloatPoint transformedPoint = ctm.inverse().mapPoint(point);
+ auto transformedPoint = state().transform.inverse().value_or(AffineTransform()).mapPoint(FloatPoint(x, y));
+
if (!std::isfinite(transformedPoint.x()) || !std::isfinite(transformedPoint.y()))
return false;
- WindRule windRule = RULE_NONZERO;
- if (!parseWinding(windingRuleString, windRule))
- return false;
-
- return m_path.contains(transformedPoint, windRule);
+ return path.contains(transformedPoint, toWindRule(windingRule));
}
-
-bool CanvasRenderingContext2D::isPointInStroke(const float x, const float y)
+bool CanvasRenderingContext2D::isPointInStrokeInternal(const Path& path, float x, float y)
{
- GraphicsContext* c = drawingContext();
+ auto* c = drawingContext();
if (!c)
return false;
- if (!state().m_hasInvertibleTransform)
+ if (!state().hasInvertibleTransform)
return false;
- FloatPoint point(x, y);
- AffineTransform ctm = state().m_transform;
- FloatPoint transformedPoint = ctm.inverse().mapPoint(point);
+ auto transformedPoint = state().transform.inverse().value_or(AffineTransform()).mapPoint(FloatPoint(x, y));
if (!std::isfinite(transformedPoint.x()) || !std::isfinite(transformedPoint.y()))
return false;
CanvasStrokeStyleApplier applier(this);
- return m_path.strokeContains(&applier, transformedPoint);
+ return path.strokeContains(&applier, transformedPoint);
}
void CanvasRenderingContext2D::clearRect(float x, float y, float width, float height)
{
if (!validateRectForCanvas(x, y, width, height))
return;
- GraphicsContext* context = drawingContext();
+ auto* context = drawingContext();
if (!context)
return;
- if (!state().m_hasInvertibleTransform)
+ if (!state().hasInvertibleTransform)
return;
FloatRect rect(x, y, width, height);
@@ -1035,16 +1140,16 @@ void CanvasRenderingContext2D::clearRect(float x, float y, float width, float he
if (shouldDrawShadows()) {
context->save();
saved = true;
- context->setLegacyShadow(FloatSize(), 0, Color::transparent, ColorSpaceDeviceRGB);
+ context->setLegacyShadow(FloatSize(), 0, Color::transparent);
}
- if (state().m_globalAlpha != 1) {
+ if (state().globalAlpha != 1) {
if (!saved) {
context->save();
saved = true;
}
context->setAlpha(1);
}
- if (state().m_globalComposite != CompositeSourceOver) {
+ if (state().globalComposite != CompositeSourceOver) {
if (!saved) {
context->save();
saved = true;
@@ -1062,16 +1167,16 @@ void CanvasRenderingContext2D::fillRect(float x, float y, float width, float hei
if (!validateRectForCanvas(x, y, width, height))
return;
- GraphicsContext* c = drawingContext();
+ auto* c = drawingContext();
if (!c)
return;
- if (!state().m_hasInvertibleTransform)
+ if (!state().hasInvertibleTransform)
return;
// from the HTML5 Canvas spec:
// If x0 = x1 and y0 = y1, then the linear gradient must paint nothing
// If x0 = x1 and y0 = y1 and r0 = r1, then the radial gradient must paint nothing
- Gradient* gradient = c->fillGradient();
+ auto* gradient = c->fillGradient();
if (gradient && gradient->isZeroSize())
return;
@@ -1080,10 +1185,12 @@ void CanvasRenderingContext2D::fillRect(float x, float y, float width, float hei
if (rectContainsCanvas(rect)) {
c->fillRect(rect);
didDrawEntireCanvas();
- } else if (isFullCanvasCompositeMode(state().m_globalComposite)) {
- fullCanvasCompositedFill(rect);
+ } else if (isFullCanvasCompositeMode(state().globalComposite)) {
+ beginCompositeLayer();
+ c->fillRect(rect);
+ endCompositeLayer();
didDrawEntireCanvas();
- } else if (state().m_globalComposite == CompositeCopy) {
+ } else if (state().globalComposite == CompositeCopy) {
clearCanvas();
c->fillRect(rect);
didDrawEntireCanvas();
@@ -1098,67 +1205,62 @@ void CanvasRenderingContext2D::strokeRect(float x, float y, float width, float h
if (!validateRectForCanvas(x, y, width, height))
return;
- GraphicsContext* c = drawingContext();
+ auto* c = drawingContext();
if (!c)
return;
- if (!state().m_hasInvertibleTransform)
+ if (!state().hasInvertibleTransform)
return;
- if (!(state().m_lineWidth >= 0))
+ if (!(state().lineWidth >= 0))
return;
// If gradient size is zero, then paint nothing.
- Gradient* gradient = c->strokeGradient();
+ auto* gradient = c->strokeGradient();
if (gradient && gradient->isZeroSize())
return;
FloatRect rect(x, y, width, height);
-
- FloatRect boundingRect = rect;
- boundingRect.inflate(state().m_lineWidth / 2);
-
- c->strokeRect(rect, state().m_lineWidth);
- didDraw(boundingRect);
-}
-
-void CanvasRenderingContext2D::setShadow(float width, float height, float blur)
-{
- setShadow(FloatSize(width, height), blur, Color::transparent);
-}
-
-void CanvasRenderingContext2D::setShadow(float width, float height, float blur, const String& color)
-{
- RGBA32 rgba;
- if (!parseColorOrCurrentColor(rgba, color, canvas()))
- return;
- setShadow(FloatSize(width, height), blur, rgba);
-}
-
-void CanvasRenderingContext2D::setShadow(float width, float height, float blur, float grayLevel)
-{
- setShadow(FloatSize(width, height), blur, makeRGBA32FromFloats(grayLevel, grayLevel, grayLevel, 1));
+ if (isFullCanvasCompositeMode(state().globalComposite)) {
+ beginCompositeLayer();
+ c->strokeRect(rect, state().lineWidth);
+ endCompositeLayer();
+ didDrawEntireCanvas();
+ } else if (state().globalComposite == CompositeCopy) {
+ clearCanvas();
+ c->strokeRect(rect, state().lineWidth);
+ didDrawEntireCanvas();
+ } else {
+ FloatRect boundingRect = rect;
+ boundingRect.inflate(state().lineWidth / 2);
+ c->strokeRect(rect, state().lineWidth);
+ didDraw(boundingRect);
+ }
}
-void CanvasRenderingContext2D::setShadow(float width, float height, float blur, const String& color, float alpha)
+void CanvasRenderingContext2D::setShadow(float width, float height, float blur, const String& colorString, std::optional<float> alpha)
{
- RGBA32 rgba;
- if (!parseColorOrCurrentColor(rgba, color, canvas()))
- return;
- setShadow(FloatSize(width, height), blur, colorWithOverrideAlpha(rgba, alpha));
+ Color color = Color::transparent;
+ if (!colorString.isNull()) {
+ color = parseColorOrCurrentColor(colorString, &canvas());
+ if (!color.isValid())
+ return;
+ }
+ // FIXME: Should not use RGBA32 here.
+ setShadow(FloatSize(width, height), blur, colorWithOverrideAlpha(color.rgb(), alpha));
}
void CanvasRenderingContext2D::setShadow(float width, float height, float blur, float grayLevel, float alpha)
{
- setShadow(FloatSize(width, height), blur, makeRGBA32FromFloats(grayLevel, grayLevel, grayLevel, alpha));
+ setShadow(FloatSize(width, height), blur, Color(grayLevel, grayLevel, grayLevel, alpha));
}
void CanvasRenderingContext2D::setShadow(float width, float height, float blur, float r, float g, float b, float a)
{
- setShadow(FloatSize(width, height), blur, makeRGBA32FromFloats(r, g, b, a));
+ setShadow(FloatSize(width, height), blur, Color(r, g, b, a));
}
void CanvasRenderingContext2D::setShadow(float width, float height, float blur, float c, float m, float y, float k, float a)
{
- setShadow(FloatSize(width, height), blur, makeRGBAFromCMYKA(c, m, y, k, a));
+ setShadow(FloatSize(width, height), blur, Color(c, m, y, k, a));
}
void CanvasRenderingContext2D::clearShadow()
@@ -1166,15 +1268,15 @@ void CanvasRenderingContext2D::clearShadow()
setShadow(FloatSize(), 0, Color::transparent);
}
-void CanvasRenderingContext2D::setShadow(const FloatSize& offset, float blur, RGBA32 color)
+void CanvasRenderingContext2D::setShadow(const FloatSize& offset, float blur, const Color& color)
{
- if (state().m_shadowOffset == offset && state().m_shadowBlur == blur && state().m_shadowColor == color)
+ if (state().shadowOffset == offset && state().shadowBlur == blur && state().shadowColor == color)
return;
bool wasDrawingShadows = shouldDrawShadows();
realizeSaves();
- modifiableState().m_shadowOffset = offset;
- modifiableState().m_shadowBlur = blur;
- modifiableState().m_shadowColor = color;
+ modifiableState().shadowOffset = offset;
+ modifiableState().shadowBlur = blur;
+ modifiableState().shadowColor = color;
if (!wasDrawingShadows && !shouldDrawShadows())
return;
applyShadow();
@@ -1182,37 +1284,50 @@ void CanvasRenderingContext2D::setShadow(const FloatSize& offset, float blur, RG
void CanvasRenderingContext2D::applyShadow()
{
- GraphicsContext* c = drawingContext();
+ auto* c = drawingContext();
if (!c)
return;
if (shouldDrawShadows()) {
- float width = state().m_shadowOffset.width();
- float height = state().m_shadowOffset.height();
- c->setLegacyShadow(FloatSize(width, -height), state().m_shadowBlur, state().m_shadowColor, ColorSpaceDeviceRGB);
+ float width = state().shadowOffset.width();
+ float height = state().shadowOffset.height();
+ c->setLegacyShadow(FloatSize(width, -height), state().shadowBlur, state().shadowColor);
} else
- c->setLegacyShadow(FloatSize(), 0, Color::transparent, ColorSpaceDeviceRGB);
+ c->setLegacyShadow(FloatSize(), 0, Color::transparent);
}
bool CanvasRenderingContext2D::shouldDrawShadows() const
{
- return alphaChannel(state().m_shadowColor) && (state().m_shadowBlur || !state().m_shadowOffset.isZero());
+ return state().shadowColor.isVisible() && (state().shadowBlur || !state().shadowOffset.isZero());
+}
+
+enum class ImageSizeType { AfterDevicePixelRatio, BeforeDevicePixelRatio };
+static LayoutSize size(HTMLImageElement& element, ImageSizeType sizeType = ImageSizeType::BeforeDevicePixelRatio)
+{
+ LayoutSize size;
+ if (auto* cachedImage = element.cachedImage()) {
+ size = cachedImage->imageSizeForRenderer(element.renderer(), 1.0f); // FIXME: Not sure about this.
+ if (sizeType == ImageSizeType::AfterDevicePixelRatio && is<RenderImage>(element.renderer()) && cachedImage->image() && !cachedImage->image()->hasRelativeWidth())
+ size.scale(downcast<RenderImage>(*element.renderer()).imageDevicePixelRatio());
+ }
+ return size;
}
-static LayoutSize size(HTMLImageElement* image)
+static inline FloatSize size(HTMLCanvasElement& canvasElement)
{
- if (CachedImage* cachedImage = image->cachedImage())
- return cachedImage->imageSizeForRenderer(image->renderer(), 1.0f); // FIXME: Not sure about this.
- return IntSize();
+ return canvasElement.size();
}
#if ENABLE(VIDEO)
-static IntSize size(HTMLVideoElement* video)
+
+static inline FloatSize size(HTMLVideoElement& video)
{
- if (MediaPlayer* player = video->player())
- return player->naturalSize();
- return IntSize();
+ auto* player = video.player();
+ if (!player)
+ return { };
+ return player->naturalSize();
}
+
#endif
static inline FloatRect normalizeRect(const FloatRect& rect)
@@ -1223,248 +1338,208 @@ static inline FloatRect normalizeRect(const FloatRect& rect)
std::max(rect.height(), -rect.height()));
}
-void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, float x, float y, ExceptionCode& ec)
+ExceptionOr<void> CanvasRenderingContext2D::drawImage(CanvasImageSource&& image, float dx, float dy)
{
- if (!image) {
- ec = TYPE_MISMATCH_ERR;
- return;
- }
- LayoutSize s = size(image);
- drawImage(image, x, y, s.width(), s.height(), ec);
+ return WTF::switchOn(image,
+ [&] (RefPtr<HTMLImageElement>& imageElement) -> ExceptionOr<void> {
+ LayoutSize destRectSize = size(*imageElement, ImageSizeType::AfterDevicePixelRatio);
+ LayoutSize sourceRectSize = size(*imageElement, ImageSizeType::BeforeDevicePixelRatio);
+ return this->drawImage(*imageElement, FloatRect { 0, 0, sourceRectSize.width(), sourceRectSize.height() }, FloatRect { dx, dy, destRectSize.width(), destRectSize.height() });
+ },
+ [&] (auto& element) -> ExceptionOr<void> {
+ FloatSize elementSize = size(*element);
+ return this->drawImage(*element, FloatRect { 0, 0, elementSize.width(), elementSize.height() }, FloatRect { dx, dy, elementSize.width(), elementSize.height() });
+ }
+ );
}
-void CanvasRenderingContext2D::drawImage(HTMLImageElement* image,
- float x, float y, float width, float height, ExceptionCode& ec)
+ExceptionOr<void> CanvasRenderingContext2D::drawImage(CanvasImageSource&& image, float dx, float dy, float dw, float dh)
{
- if (!image) {
- ec = TYPE_MISMATCH_ERR;
- return;
- }
- LayoutSize s = size(image);
- drawImage(image, FloatRect(0, 0, s.width(), s.height()), FloatRect(x, y, width, height), ec);
+ return WTF::switchOn(image,
+ [&] (auto& element) -> ExceptionOr<void> {
+ FloatSize elementSize = size(*element);
+ return this->drawImage(*element, FloatRect { 0, 0, elementSize.width(), elementSize.height() }, FloatRect { dx, dy, dw, dh });
+ }
+ );
}
-void CanvasRenderingContext2D::drawImage(HTMLImageElement* image,
- float sx, float sy, float sw, float sh,
- float dx, float dy, float dw, float dh, ExceptionCode& ec)
+ExceptionOr<void> CanvasRenderingContext2D::drawImage(CanvasImageSource&& image, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh)
{
- drawImage(image, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), ec);
+ return WTF::switchOn(image,
+ [&] (auto& element) -> ExceptionOr<void> {
+ return this->drawImage(*element, FloatRect { sx, sy, sw, sh }, FloatRect { dx, dy, dw, dh });
+ }
+ );
}
-void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, const FloatRect& srcRect, const FloatRect& dstRect, ExceptionCode& ec)
+ExceptionOr<void> CanvasRenderingContext2D::drawImage(HTMLImageElement& imageElement, const FloatRect& srcRect, const FloatRect& dstRect)
{
- drawImage(image, srcRect, dstRect, state().m_globalComposite, state().m_globalBlend, ec);
+ return drawImage(imageElement, srcRect, dstRect, state().globalComposite, state().globalBlend);
}
-void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, const FloatRect& srcRect, const FloatRect& dstRect, const CompositeOperator& op, const BlendMode& blendMode, ExceptionCode& ec)
+ExceptionOr<void> CanvasRenderingContext2D::drawImage(HTMLImageElement& imageElement, const FloatRect& srcRect, const FloatRect& dstRect, const CompositeOperator& op, const BlendMode& blendMode)
{
- if (!image) {
- ec = TYPE_MISMATCH_ERR;
- return;
- }
-
- ec = 0;
-
if (!std::isfinite(dstRect.x()) || !std::isfinite(dstRect.y()) || !std::isfinite(dstRect.width()) || !std::isfinite(dstRect.height())
|| !std::isfinite(srcRect.x()) || !std::isfinite(srcRect.y()) || !std::isfinite(srcRect.width()) || !std::isfinite(srcRect.height()))
- return;
+ return { };
if (!dstRect.width() || !dstRect.height())
- return;
+ return { };
- if (!image->complete())
- return;
+ if (!imageElement.complete())
+ return { };
FloatRect normalizedSrcRect = normalizeRect(srcRect);
FloatRect normalizedDstRect = normalizeRect(dstRect);
- FloatRect imageRect = FloatRect(FloatPoint(), size(image));
- if (!srcRect.width() || !srcRect.height()) {
- ec = INDEX_SIZE_ERR;
- return;
+ FloatRect imageRect = FloatRect(FloatPoint(), size(imageElement, ImageSizeType::BeforeDevicePixelRatio));
+ if (!srcRect.width() || !srcRect.height())
+ return Exception { INDEX_SIZE_ERR };
+
+ // When the source rectangle is outside the source image, the source rectangle must be clipped
+ // to the source image and the destination rectangle must be clipped in the same proportion.
+ FloatRect originalNormalizedSrcRect = normalizedSrcRect;
+ normalizedSrcRect.intersect(imageRect);
+ if (normalizedSrcRect.isEmpty())
+ return { };
+
+ if (normalizedSrcRect != originalNormalizedSrcRect) {
+ normalizedDstRect.setWidth(normalizedDstRect.width() * normalizedSrcRect.width() / originalNormalizedSrcRect.width());
+ normalizedDstRect.setHeight(normalizedDstRect.height() * normalizedSrcRect.height() / originalNormalizedSrcRect.height());
+ if (normalizedDstRect.isEmpty())
+ return { };
}
- if (!imageRect.contains(normalizedSrcRect))
- return;
GraphicsContext* c = drawingContext();
if (!c)
- return;
- if (!state().m_hasInvertibleTransform)
- return;
+ return { };
+ if (!state().hasInvertibleTransform)
+ return { };
- CachedImage* cachedImage = image->cachedImage();
+ CachedImage* cachedImage = imageElement.cachedImage();
if (!cachedImage)
- return;
+ return { };
+
+ Image* image = cachedImage->imageForRenderer(imageElement.renderer());
+ if (!image)
+ return { };
+
+ ImageObserver* observer = image->imageObserver();
+
+ if (image->isSVGImage()) {
+ image->setImageObserver(nullptr);
+ image->setContainerSize(imageRect.size());
+ }
if (rectContainsCanvas(normalizedDstRect)) {
- c->drawImage(cachedImage->imageForRenderer(image->renderer()), ColorSpaceDeviceRGB, normalizedDstRect, normalizedSrcRect, op, blendMode, ImageOrientationDescription());
+ c->drawImage(*image, normalizedDstRect, normalizedSrcRect, ImagePaintingOptions(op, blendMode));
didDrawEntireCanvas();
} else if (isFullCanvasCompositeMode(op)) {
- fullCanvasCompositedDrawImage(cachedImage->imageForRenderer(image->renderer()), ColorSpaceDeviceRGB, normalizedDstRect, normalizedSrcRect, op);
+ fullCanvasCompositedDrawImage(*image, normalizedDstRect, normalizedSrcRect, op);
didDrawEntireCanvas();
} else if (op == CompositeCopy) {
clearCanvas();
- c->drawImage(cachedImage->imageForRenderer(image->renderer()), ColorSpaceDeviceRGB, normalizedDstRect, normalizedSrcRect, op, blendMode, ImageOrientationDescription());
+ c->drawImage(*image, normalizedDstRect, normalizedSrcRect, ImagePaintingOptions(op, blendMode));
didDrawEntireCanvas();
} else {
- c->drawImage(cachedImage->imageForRenderer(image->renderer()), ColorSpaceDeviceRGB, normalizedDstRect, normalizedSrcRect, op, blendMode, ImageOrientationDescription());
+ c->drawImage(*image, normalizedDstRect, normalizedSrcRect, ImagePaintingOptions(op, blendMode));
didDraw(normalizedDstRect);
}
+
+ if (image->isSVGImage())
+ image->setImageObserver(observer);
- checkOrigin(image);
-}
-
-void CanvasRenderingContext2D::drawImage(HTMLCanvasElement* sourceCanvas, float x, float y, ExceptionCode& ec)
-{
- drawImage(sourceCanvas, 0, 0, sourceCanvas->width(), sourceCanvas->height(), x, y, sourceCanvas->width(), sourceCanvas->height(), ec);
-}
+ checkOrigin(&imageElement);
-void CanvasRenderingContext2D::drawImage(HTMLCanvasElement* sourceCanvas,
- float x, float y, float width, float height, ExceptionCode& ec)
-{
- drawImage(sourceCanvas, FloatRect(0, 0, sourceCanvas->width(), sourceCanvas->height()), FloatRect(x, y, width, height), ec);
-}
-
-void CanvasRenderingContext2D::drawImage(HTMLCanvasElement* sourceCanvas,
- float sx, float sy, float sw, float sh,
- float dx, float dy, float dw, float dh, ExceptionCode& ec)
-{
- drawImage(sourceCanvas, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), ec);
+ return { };
}
-void CanvasRenderingContext2D::drawImage(HTMLCanvasElement* sourceCanvas, const FloatRect& srcRect,
- const FloatRect& dstRect, ExceptionCode& ec)
+ExceptionOr<void> CanvasRenderingContext2D::drawImage(HTMLCanvasElement& sourceCanvas, const FloatRect& srcRect, const FloatRect& dstRect)
{
- if (!sourceCanvas) {
- ec = TYPE_MISMATCH_ERR;
- return;
- }
+ FloatRect srcCanvasRect = FloatRect(FloatPoint(), sourceCanvas.size());
- FloatRect srcCanvasRect = FloatRect(FloatPoint(), sourceCanvas->size());
-
- if (!srcCanvasRect.width() || !srcCanvasRect.height()) {
- ec = INVALID_STATE_ERR;
- return;
- }
-
- if (!srcRect.width() || !srcRect.height()) {
- ec = INDEX_SIZE_ERR;
- return;
- }
+ if (!srcCanvasRect.width() || !srcCanvasRect.height())
+ return Exception { INVALID_STATE_ERR };
- ec = 0;
+ if (!srcRect.width() || !srcRect.height())
+ return Exception { INDEX_SIZE_ERR };
if (!srcCanvasRect.contains(normalizeRect(srcRect)) || !dstRect.width() || !dstRect.height())
- return;
+ return { };
GraphicsContext* c = drawingContext();
if (!c)
- return;
- if (!state().m_hasInvertibleTransform)
- return;
+ return { };
+ if (!state().hasInvertibleTransform)
+ return { };
// FIXME: Do this through platform-independent GraphicsContext API.
- ImageBuffer* buffer = sourceCanvas->buffer();
+ ImageBuffer* buffer = sourceCanvas.buffer();
if (!buffer)
- return;
+ return { };
- checkOrigin(sourceCanvas);
+ checkOrigin(&sourceCanvas);
#if ENABLE(ACCELERATED_2D_CANVAS)
- // If we're drawing from one accelerated canvas 2d to another, avoid calling sourceCanvas->makeRenderingResultsAvailable()
+ // If we're drawing from one accelerated canvas 2d to another, avoid calling sourceCanvas.makeRenderingResultsAvailable()
// as that will do a readback to software.
- CanvasRenderingContext* sourceContext = sourceCanvas->renderingContext();
+ CanvasRenderingContext* sourceContext = sourceCanvas.renderingContext();
// FIXME: Implement an accelerated path for drawing from a WebGL canvas to a 2d canvas when possible.
if (!isAccelerated() || !sourceContext || !sourceContext->isAccelerated() || !sourceContext->is2d())
- sourceCanvas->makeRenderingResultsAvailable();
+ sourceCanvas.makeRenderingResultsAvailable();
#else
- sourceCanvas->makeRenderingResultsAvailable();
+ sourceCanvas.makeRenderingResultsAvailable();
#endif
if (rectContainsCanvas(dstRect)) {
- c->drawImageBuffer(buffer, ColorSpaceDeviceRGB, dstRect, srcRect, state().m_globalComposite, state().m_globalBlend);
+ c->drawImageBuffer(*buffer, dstRect, srcRect, ImagePaintingOptions(state().globalComposite, state().globalBlend));
didDrawEntireCanvas();
- } else if (isFullCanvasCompositeMode(state().m_globalComposite)) {
- fullCanvasCompositedDrawImage(buffer, ColorSpaceDeviceRGB, dstRect, srcRect, state().m_globalComposite);
+ } else if (isFullCanvasCompositeMode(state().globalComposite)) {
+ fullCanvasCompositedDrawImage(*buffer, dstRect, srcRect, state().globalComposite);
didDrawEntireCanvas();
- } else if (state().m_globalComposite == CompositeCopy) {
+ } else if (state().globalComposite == CompositeCopy) {
clearCanvas();
- c->drawImageBuffer(buffer, ColorSpaceDeviceRGB, dstRect, srcRect, state().m_globalComposite, state().m_globalBlend);
+ c->drawImageBuffer(*buffer, dstRect, srcRect, ImagePaintingOptions(state().globalComposite, state().globalBlend));
didDrawEntireCanvas();
} else {
- c->drawImageBuffer(buffer, ColorSpaceDeviceRGB, dstRect, srcRect, state().m_globalComposite, state().m_globalBlend);
+ c->drawImageBuffer(*buffer, dstRect, srcRect, ImagePaintingOptions(state().globalComposite, state().globalBlend));
didDraw(dstRect);
}
-}
-#if ENABLE(VIDEO)
-void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video, float x, float y, ExceptionCode& ec)
-{
- if (!video) {
- ec = TYPE_MISMATCH_ERR;
- return;
- }
- IntSize s = size(video);
- drawImage(video, x, y, s.width(), s.height(), ec);
-}
-
-void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video,
- float x, float y, float width, float height, ExceptionCode& ec)
-{
- if (!video) {
- ec = TYPE_MISMATCH_ERR;
- return;
- }
- IntSize s = size(video);
- drawImage(video, FloatRect(0, 0, s.width(), s.height()), FloatRect(x, y, width, height), ec);
+ return { };
}
-void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video,
- float sx, float sy, float sw, float sh,
- float dx, float dy, float dw, float dh, ExceptionCode& ec)
-{
- drawImage(video, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), ec);
-}
+#if ENABLE(VIDEO)
-void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video, const FloatRect& srcRect, const FloatRect& dstRect,
- ExceptionCode& ec)
+ExceptionOr<void> CanvasRenderingContext2D::drawImage(HTMLVideoElement& video, const FloatRect& srcRect, const FloatRect& dstRect)
{
- if (!video) {
- ec = TYPE_MISMATCH_ERR;
- return;
- }
-
- ec = 0;
-
- if (video->readyState() == HTMLMediaElement::HAVE_NOTHING || video->readyState() == HTMLMediaElement::HAVE_METADATA)
- return;
+ if (video.readyState() == HTMLMediaElement::HAVE_NOTHING || video.readyState() == HTMLMediaElement::HAVE_METADATA)
+ return { };
FloatRect videoRect = FloatRect(FloatPoint(), size(video));
- if (!srcRect.width() || !srcRect.height()) {
- ec = INDEX_SIZE_ERR;
- return;
- }
+ if (!srcRect.width() || !srcRect.height())
+ return Exception { INDEX_SIZE_ERR };
if (!videoRect.contains(normalizeRect(srcRect)) || !dstRect.width() || !dstRect.height())
- return;
+ return { };
GraphicsContext* c = drawingContext();
if (!c)
- return;
- if (!state().m_hasInvertibleTransform)
- return;
+ return { };
+ if (!state().hasInvertibleTransform)
+ return { };
- checkOrigin(video);
+ checkOrigin(&video);
-#if USE(CG)
- if (PassNativeImagePtr image = video->nativeImageForCurrentTime()) {
- c->drawNativeImage(image, FloatSize(video->videoWidth(), video->videoHeight()), ColorSpaceDeviceRGB, dstRect, srcRect);
+#if USE(CG) || (ENABLE(ACCELERATED_2D_CANVAS) && USE(GSTREAMER_GL) && USE(CAIRO))
+ if (NativeImagePtr image = video.nativeImageForCurrentTime()) {
+ c->drawNativeImage(image, FloatSize(video.videoWidth(), video.videoHeight()), dstRect, srcRect);
if (rectContainsCanvas(dstRect))
didDrawEntireCanvas();
else
didDraw(dstRect);
- return;
+ return { };
}
#endif
@@ -1473,23 +1548,22 @@ void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video, const FloatRec
c->translate(dstRect.x(), dstRect.y());
c->scale(FloatSize(dstRect.width() / srcRect.width(), dstRect.height() / srcRect.height()));
c->translate(-srcRect.x(), -srcRect.y());
- video->paintCurrentFrameInContext(c, IntRect(IntPoint(), size(video)));
+ video.paintCurrentFrameInContext(*c, FloatRect(FloatPoint(), size(video)));
stateSaver.restore();
didDraw(dstRect);
+
+ return { };
}
+
#endif
-void CanvasRenderingContext2D::drawImageFromRect(HTMLImageElement* image,
- float sx, float sy, float sw, float sh,
- float dx, float dy, float dw, float dh,
- const String& compositeOperation)
+void CanvasRenderingContext2D::drawImageFromRect(HTMLImageElement& imageElement, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh, const String& compositeOperation)
{
CompositeOperator op;
- BlendMode blendOp = BlendModeNormal;
+ auto blendOp = BlendModeNormal;
if (!parseCompositeAndBlendOperator(compositeOperation, op, blendOp) || blendOp != BlendModeNormal)
op = CompositeSourceOver;
-
- drawImage(image, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), op, BlendModeNormal, IGNORE_EXCEPTION);
+ drawImage(imageElement, FloatRect { sx, sy, sw, sh }, FloatRect { dx, dy, dw, dh }, op, BlendModeNormal);
}
void CanvasRenderingContext2D::setAlpha(float alpha)
@@ -1504,22 +1578,21 @@ void CanvasRenderingContext2D::setCompositeOperation(const String& operation)
void CanvasRenderingContext2D::clearCanvas()
{
- FloatRect canvasRect(0, 0, canvas()->width(), canvas()->height());
- GraphicsContext* c = drawingContext();
+ auto* c = drawingContext();
if (!c)
return;
c->save();
- c->setCTM(canvas()->baseTransform());
- c->clearRect(canvasRect);
+ c->setCTM(canvas().baseTransform());
+ c->clearRect(FloatRect(0, 0, canvas().width(), canvas().height()));
c->restore();
}
Path CanvasRenderingContext2D::transformAreaToDevice(const Path& path) const
{
Path transformed(path);
- transformed.transform(state().m_transform);
- transformed.transform(canvas()->baseTransform());
+ transformed.transform(state().transform);
+ transformed.transform(canvas().baseTransform());
return transformed;
}
@@ -1533,14 +1606,14 @@ Path CanvasRenderingContext2D::transformAreaToDevice(const FloatRect& rect) cons
bool CanvasRenderingContext2D::rectContainsCanvas(const FloatRect& rect) const
{
FloatQuad quad(rect);
- FloatQuad canvasQuad(FloatRect(0, 0, canvas()->width(), canvas()->height()));
- return state().m_transform.mapQuad(quad).containsQuad(canvasQuad);
+ FloatQuad canvasQuad(FloatRect(0, 0, canvas().width(), canvas().height()));
+ return state().transform.mapQuad(quad).containsQuad(canvasQuad);
}
template<class T> IntRect CanvasRenderingContext2D::calculateCompositingBufferRect(const T& area, IntSize* croppedOffset)
{
- IntRect canvasRect(0, 0, canvas()->width(), canvas()->height());
- canvasRect = canvas()->baseTransform().mapRect(canvasRect);
+ IntRect canvasRect(0, 0, canvas().width(), canvas().height());
+ canvasRect = canvas().baseTransform().mapRect(canvasRect);
Path path = transformAreaToDevice(area);
IntRect bufferRect = enclosingIntRect(path.fastBoundingRect());
IntPoint originalLocation = bufferRect.location();
@@ -1552,16 +1625,15 @@ template<class T> IntRect CanvasRenderingContext2D::calculateCompositingBufferRe
std::unique_ptr<ImageBuffer> CanvasRenderingContext2D::createCompositingBuffer(const IntRect& bufferRect)
{
- RenderingMode renderMode = isAccelerated() ? Accelerated : Unaccelerated;
- return ImageBuffer::create(bufferRect.size(), 1, ColorSpaceDeviceRGB, renderMode);
+ return ImageBuffer::create(bufferRect.size(), isAccelerated() ? Accelerated : Unaccelerated);
}
-void CanvasRenderingContext2D::compositeBuffer(ImageBuffer* buffer, const IntRect& bufferRect, CompositeOperator op)
+void CanvasRenderingContext2D::compositeBuffer(ImageBuffer& buffer, const IntRect& bufferRect, CompositeOperator op)
{
- IntRect canvasRect(0, 0, canvas()->width(), canvas()->height());
- canvasRect = canvas()->baseTransform().mapRect(canvasRect);
+ IntRect canvasRect(0, 0, canvas().width(), canvas().height());
+ canvasRect = canvas().baseTransform().mapRect(canvasRect);
- GraphicsContext* c = drawingContext();
+ auto* c = drawingContext();
if (!c)
return;
@@ -1573,37 +1645,36 @@ void CanvasRenderingContext2D::compositeBuffer(ImageBuffer* buffer, const IntRec
c->clipOut(bufferRect);
c->clearRect(canvasRect);
c->restore();
-
- c->drawImageBuffer(buffer, ColorSpaceDeviceRGB, bufferRect.location(), state().m_globalComposite);
+ c->drawImageBuffer(buffer, bufferRect.location(), state().globalComposite);
c->restore();
}
-static void drawImageToContext(Image* image, GraphicsContext* context, ColorSpace styleColorSpace, const FloatRect& dest, const FloatRect& src, CompositeOperator op)
+static void drawImageToContext(Image& image, GraphicsContext& context, const FloatRect& dest, const FloatRect& src, CompositeOperator op)
{
- context->drawImage(image, styleColorSpace, dest, src, op, ImageOrientationDescription());
+ context.drawImage(image, dest, src, op);
}
-static void drawImageToContext(ImageBuffer* imageBuffer, GraphicsContext* context, ColorSpace styleColorSpace, const FloatRect& dest, const FloatRect& src, CompositeOperator op)
+static void drawImageToContext(ImageBuffer& imageBuffer, GraphicsContext& context, const FloatRect& dest, const FloatRect& src, CompositeOperator op)
{
- context->drawImageBuffer(imageBuffer, styleColorSpace, dest, src, op);
+ context.drawImageBuffer(imageBuffer, dest, src, op);
}
-template<class T> void CanvasRenderingContext2D::fullCanvasCompositedDrawImage(T* image, ColorSpace styleColorSpace, const FloatRect& dest, const FloatRect& src, CompositeOperator op)
+template<class T> void CanvasRenderingContext2D::fullCanvasCompositedDrawImage(T& image, const FloatRect& dest, const FloatRect& src, CompositeOperator op)
{
ASSERT(isFullCanvasCompositeMode(op));
IntSize croppedOffset;
- IntRect bufferRect = calculateCompositingBufferRect(dest, &croppedOffset);
+ auto bufferRect = calculateCompositingBufferRect(dest, &croppedOffset);
if (bufferRect.isEmpty()) {
clearCanvas();
return;
}
- std::unique_ptr<ImageBuffer> buffer = createCompositingBuffer(bufferRect);
+ auto buffer = createCompositingBuffer(bufferRect);
if (!buffer)
return;
- GraphicsContext* c = drawingContext();
+ auto* c = drawingContext();
if (!c)
return;
@@ -1611,142 +1682,172 @@ template<class T> void CanvasRenderingContext2D::fullCanvasCompositedDrawImage(
adjustedDest.setLocation(FloatPoint(0, 0));
AffineTransform effectiveTransform = c->getCTM();
IntRect transformedAdjustedRect = enclosingIntRect(effectiveTransform.mapRect(adjustedDest));
- buffer->context()->translate(-transformedAdjustedRect.location().x(), -transformedAdjustedRect.location().y());
- buffer->context()->translate(croppedOffset.width(), croppedOffset.height());
- buffer->context()->concatCTM(effectiveTransform);
- drawImageToContext(image, buffer->context(), styleColorSpace, adjustedDest, src, CompositeSourceOver);
+ buffer->context().translate(-transformedAdjustedRect.location().x(), -transformedAdjustedRect.location().y());
+ buffer->context().translate(croppedOffset.width(), croppedOffset.height());
+ buffer->context().concatCTM(effectiveTransform);
+ drawImageToContext(image, buffer->context(), adjustedDest, src, CompositeSourceOver);
- compositeBuffer(buffer.get(), bufferRect, op);
+ compositeBuffer(*buffer, bufferRect, op);
}
-template<class T> void CanvasRenderingContext2D::fullCanvasCompositedFill(const T& area)
+void CanvasRenderingContext2D::prepareGradientForDashboard(CanvasGradient& gradient) const
{
- ASSERT(isFullCanvasCompositeMode(state().m_globalComposite));
-
- IntRect bufferRect = calculateCompositingBufferRect(area, 0);
- if (bufferRect.isEmpty()) {
- clearCanvas();
- return;
- }
+#if ENABLE(DASHBOARD_SUPPORT)
+ if (m_usesDashboardCompatibilityMode)
+ gradient.setDashboardCompatibilityMode();
+#else
+ UNUSED_PARAM(gradient);
+#endif
+}
- std::unique_ptr<ImageBuffer> buffer = createCompositingBuffer(bufferRect);
- if (!buffer)
- return;
+static CanvasRenderingContext2D::Style toStyle(const CanvasStyle& style)
+{
+ if (auto* gradient = style.canvasGradient())
+ return RefPtr<CanvasGradient> { gradient };
+ if (auto* pattern = style.canvasPattern())
+ return RefPtr<CanvasPattern> { pattern };
+ return style.color();
+}
- Path path = transformAreaToDevice(area);
- path.translate(FloatSize(-bufferRect.x(), -bufferRect.y()));
+CanvasRenderingContext2D::Style CanvasRenderingContext2D::strokeStyle() const
+{
+ return toStyle(state().strokeStyle);
+}
- buffer->context()->setCompositeOperation(CompositeSourceOver);
- modifiableState().m_fillStyle.applyFillColor(buffer->context());
- buffer->context()->fillPath(path);
+void CanvasRenderingContext2D::setStrokeStyle(CanvasRenderingContext2D::Style&& style)
+{
+ WTF::switchOn(style,
+ [this] (const String& string) { this->setStrokeColor(string); },
+ [this] (const RefPtr<CanvasGradient>& gradient) { this->setStrokeStyle(CanvasStyle(*gradient)); },
+ [this] (const RefPtr<CanvasPattern>& pattern) { this->setStrokeStyle(CanvasStyle(*pattern)); }
+ );
+}
- compositeBuffer(buffer.get(), bufferRect, state().m_globalComposite);
+CanvasRenderingContext2D::Style CanvasRenderingContext2D::fillStyle() const
+{
+ return toStyle(state().fillStyle);
}
-void CanvasRenderingContext2D::prepareGradientForDashboard(CanvasGradient* gradient) const
+void CanvasRenderingContext2D::setFillStyle(CanvasRenderingContext2D::Style&& style)
{
-#if ENABLE(DASHBOARD_SUPPORT)
- if (m_usesDashboardCompatibilityMode)
- gradient->setDashboardCompatibilityMode();
-#else
- UNUSED_PARAM(gradient);
-#endif
+ WTF::switchOn(style,
+ [this] (const String& string) { this->setFillColor(string); },
+ [this] (const RefPtr<CanvasGradient>& gradient) { this->setFillStyle(CanvasStyle(*gradient)); },
+ [this] (const RefPtr<CanvasPattern>& pattern) { this->setFillStyle(CanvasStyle(*pattern)); }
+ );
}
-PassRefPtr<CanvasGradient> CanvasRenderingContext2D::createLinearGradient(float x0, float y0, float x1, float y1, ExceptionCode& ec)
+ExceptionOr<Ref<CanvasGradient>> CanvasRenderingContext2D::createLinearGradient(float x0, float y0, float x1, float y1)
{
- if (!std::isfinite(x0) || !std::isfinite(y0) || !std::isfinite(x1) || !std::isfinite(y1)) {
- ec = NOT_SUPPORTED_ERR;
- return 0;
- }
+ if (!std::isfinite(x0) || !std::isfinite(y0) || !std::isfinite(x1) || !std::isfinite(y1))
+ return Exception { NOT_SUPPORTED_ERR };
- RefPtr<CanvasGradient> gradient = CanvasGradient::create(FloatPoint(x0, y0), FloatPoint(x1, y1));
+ auto gradient = CanvasGradient::create(FloatPoint(x0, y0), FloatPoint(x1, y1));
prepareGradientForDashboard(gradient.get());
- return gradient.release();
+ return WTFMove(gradient);
}
-PassRefPtr<CanvasGradient> CanvasRenderingContext2D::createRadialGradient(float x0, float y0, float r0, float x1, float y1, float r1, ExceptionCode& ec)
+ExceptionOr<Ref<CanvasGradient>> CanvasRenderingContext2D::createRadialGradient(float x0, float y0, float r0, float x1, float y1, float r1)
{
- if (!std::isfinite(x0) || !std::isfinite(y0) || !std::isfinite(r0) || !std::isfinite(x1) || !std::isfinite(y1) || !std::isfinite(r1)) {
- ec = NOT_SUPPORTED_ERR;
- return 0;
- }
+ if (!std::isfinite(x0) || !std::isfinite(y0) || !std::isfinite(r0) || !std::isfinite(x1) || !std::isfinite(y1) || !std::isfinite(r1))
+ return Exception { NOT_SUPPORTED_ERR };
- if (r0 < 0 || r1 < 0) {
- ec = INDEX_SIZE_ERR;
- return 0;
- }
+ if (r0 < 0 || r1 < 0)
+ return Exception { INDEX_SIZE_ERR };
- RefPtr<CanvasGradient> gradient = CanvasGradient::create(FloatPoint(x0, y0), r0, FloatPoint(x1, y1), r1);
+ auto gradient = CanvasGradient::create(FloatPoint(x0, y0), r0, FloatPoint(x1, y1), r1);
prepareGradientForDashboard(gradient.get());
- return gradient.release();
+ return WTFMove(gradient);
}
-PassRefPtr<CanvasPattern> CanvasRenderingContext2D::createPattern(HTMLImageElement* image,
- const String& repetitionType, ExceptionCode& ec)
+ExceptionOr<RefPtr<CanvasPattern>> CanvasRenderingContext2D::createPattern(CanvasImageSource&& image, const String& repetition)
{
- if (!image) {
- ec = TYPE_MISMATCH_ERR;
- return 0;
- }
bool repeatX, repeatY;
- ec = 0;
- CanvasPattern::parseRepetitionType(repetitionType, repeatX, repeatY, ec);
- if (ec)
- return 0;
+ if (!CanvasPattern::parseRepetitionType(repetition, repeatX, repeatY))
+ return Exception { SYNTAX_ERR };
+
+ return WTF::switchOn(image,
+ [&] (auto& element) -> ExceptionOr<RefPtr<CanvasPattern>> { return this->createPattern(*element, repeatX, repeatY); }
+ );
+}
+
+ExceptionOr<RefPtr<CanvasPattern>> CanvasRenderingContext2D::createPattern(HTMLImageElement& imageElement, bool repeatX, bool repeatY)
+{
+ auto* cachedImage = imageElement.cachedImage();
- if (!image->complete())
- return 0;
+ // If the image loading hasn't started or the image is not complete, it is not fully decodable.
+ if (!cachedImage || !imageElement.complete())
+ return nullptr;
- CachedImage* cachedImage = image->cachedImage();
- if (!cachedImage || !image->cachedImage()->imageForRenderer(image->renderer()))
- return CanvasPattern::create(Image::nullImage(), repeatX, repeatY, true);
+ if (cachedImage->status() == CachedResource::LoadError)
+ return Exception { INVALID_STATE_ERR };
- bool originClean = cachedImage->isOriginClean(canvas()->securityOrigin());
- return CanvasPattern::create(cachedImage->imageForRenderer(image->renderer()), repeatX, repeatY, originClean);
+ bool originClean = cachedImage->isOriginClean(canvas().securityOrigin());
+
+ // FIXME: SVG images with animations can switch between clean and dirty (leaking cross-origin
+ // data). We should either:
+ // 1) Take a fixed snapshot of an SVG image when creating a pattern and determine then whether
+ // the origin is clean.
+ // 2) Dynamically verify the origin checks at draw time, and dirty the canvas accordingly.
+ // To be on the safe side, taint the origin for all patterns containing SVG images for now.
+ if (cachedImage->image()->isSVGImage())
+ originClean = false;
+
+ return RefPtr<CanvasPattern> { CanvasPattern::create(*cachedImage->imageForRenderer(imageElement.renderer()), repeatX, repeatY, originClean) };
}
-PassRefPtr<CanvasPattern> CanvasRenderingContext2D::createPattern(HTMLCanvasElement* canvas,
- const String& repetitionType, ExceptionCode& ec)
+ExceptionOr<RefPtr<CanvasPattern>> CanvasRenderingContext2D::createPattern(HTMLCanvasElement& canvas, bool repeatX, bool repeatY)
{
- if (!canvas) {
- ec = TYPE_MISMATCH_ERR;
- return 0;
- }
- if (!canvas->width() || !canvas->height()) {
- ec = INVALID_STATE_ERR;
- return 0;
- }
+ if (!canvas.width() || !canvas.height() || !canvas.buffer())
+ return Exception { INVALID_STATE_ERR };
- bool repeatX, repeatY;
- ec = 0;
- CanvasPattern::parseRepetitionType(repetitionType, repeatX, repeatY, ec);
- if (ec)
- return 0;
- return CanvasPattern::create(canvas->copiedImage(), repeatX, repeatY, canvas->originClean());
+ return RefPtr<CanvasPattern> { CanvasPattern::create(*canvas.copiedImage(), repeatX, repeatY, canvas.originClean()) };
+}
+
+#if ENABLE(VIDEO)
+
+ExceptionOr<RefPtr<CanvasPattern>> CanvasRenderingContext2D::createPattern(HTMLVideoElement& videoElement, bool repeatX, bool repeatY)
+{
+ if (videoElement.readyState() < HTMLMediaElement::HAVE_CURRENT_DATA)
+ return nullptr;
+
+ checkOrigin(&videoElement);
+ bool originClean = canvas().originClean();
+
+#if USE(CG) || (ENABLE(ACCELERATED_2D_CANVAS) && USE(GSTREAMER_GL) && USE(CAIRO))
+ if (auto nativeImage = videoElement.nativeImageForCurrentTime())
+ return RefPtr<CanvasPattern> { CanvasPattern::create(BitmapImage::create(WTFMove(nativeImage)), repeatX, repeatY, originClean) };
+#endif
+
+ auto imageBuffer = ImageBuffer::create(size(videoElement), drawingContext() ? drawingContext()->renderingMode() : Accelerated);
+ videoElement.paintCurrentFrameInContext(imageBuffer->context(), FloatRect(FloatPoint(), size(videoElement)));
+
+ return RefPtr<CanvasPattern> { CanvasPattern::create(ImageBuffer::sinkIntoImage(WTFMove(imageBuffer), Unscaled).releaseNonNull(), repeatX, repeatY, originClean) };
}
+#endif
+
void CanvasRenderingContext2D::didDrawEntireCanvas()
{
- didDraw(FloatRect(FloatPoint::zero(), canvas()->size()), CanvasDidDrawApplyClip);
+ didDraw(FloatRect(FloatPoint::zero(), canvas().size()), CanvasDidDrawApplyClip);
}
void CanvasRenderingContext2D::didDraw(const FloatRect& r, unsigned options)
{
- GraphicsContext* c = drawingContext();
+ auto* c = drawingContext();
if (!c)
return;
- if (!state().m_hasInvertibleTransform)
+ if (!state().hasInvertibleTransform)
return;
-#if ENABLE(ACCELERATED_2D_CANVAS) && USE(ACCELERATED_COMPOSITING)
+#if ENABLE(ACCELERATED_2D_CANVAS)
// If we are drawing to hardware and we have a composited layer, just call contentChanged().
if (isAccelerated()) {
- RenderBox* renderBox = canvas()->renderBox();
+ RenderBox* renderBox = canvas().renderBox();
if (renderBox && renderBox->hasAcceleratedCompositing()) {
renderBox->contentChanged(CanvasPixelsChanged);
- canvas()->clearCopiedImage();
- canvas()->notifyObserversCanvasChanged(r);
+ canvas().clearCopiedImage();
+ canvas().notifyObserversCanvasChanged(r);
return;
}
}
@@ -1754,15 +1855,15 @@ void CanvasRenderingContext2D::didDraw(const FloatRect& r, unsigned options)
FloatRect dirtyRect = r;
if (options & CanvasDidDrawApplyTransform) {
- AffineTransform ctm = state().m_transform;
+ AffineTransform ctm = state().transform;
dirtyRect = ctm.mapRect(r);
}
- if (options & CanvasDidDrawApplyShadow && alphaChannel(state().m_shadowColor)) {
+ if (options & CanvasDidDrawApplyShadow && state().shadowColor.isVisible()) {
// The shadow gets applied after transformation
FloatRect shadowRect(dirtyRect);
- shadowRect.move(state().m_shadowOffset);
- shadowRect.inflate(state().m_shadowBlur);
+ shadowRect.move(state().shadowOffset);
+ shadowRect.inflate(state().shadowBlur);
dirtyRect.unite(shadowRect);
}
@@ -1772,61 +1873,88 @@ void CanvasRenderingContext2D::didDraw(const FloatRect& r, unsigned options)
// we'd have to keep the clip path around.
}
- canvas()->didDraw(dirtyRect);
+ canvas().didDraw(dirtyRect);
}
-GraphicsContext* CanvasRenderingContext2D::drawingContext() const
+void CanvasRenderingContext2D::setTracksDisplayListReplay(bool tracksDisplayListReplay)
{
- return canvas()->drawingContext();
+ if (tracksDisplayListReplay == m_tracksDisplayListReplay)
+ return;
+
+ m_tracksDisplayListReplay = tracksDisplayListReplay;
+ if (!m_tracksDisplayListReplay)
+ contextDisplayListMap().remove(this);
}
-static PassRefPtr<ImageData> createEmptyImageData(const IntSize& size)
+String CanvasRenderingContext2D::displayListAsText(DisplayList::AsTextFlags flags) const
{
- Checked<int, RecordOverflow> dataSize = 4;
- dataSize *= size.width();
- dataSize *= size.height();
- if (dataSize.hasOverflowed())
- return 0;
+ if (!m_recordingContext)
+ return { };
+ return m_recordingContext->displayList.asText(flags);
+}
- RefPtr<ImageData> data = ImageData::create(size);
- data->data()->zeroFill();
- return data.release();
+String CanvasRenderingContext2D::replayDisplayListAsText(DisplayList::AsTextFlags flags) const
+{
+ auto* displayList = contextDisplayListMap().get(this);
+ if (!displayList)
+ return { };
+ return displayList->asText(flags);
}
-PassRefPtr<ImageData> CanvasRenderingContext2D::createImageData(PassRefPtr<ImageData> imageData, ExceptionCode& ec) const
+void CanvasRenderingContext2D::paintRenderingResultsToCanvas()
{
- if (!imageData) {
- ec = NOT_SUPPORTED_ERR;
- return 0;
- }
+ if (UNLIKELY(m_usesDisplayListDrawing)) {
+ if (!m_recordingContext)
+ return;
- return createEmptyImageData(imageData->size());
+ FloatRect clip(FloatPoint::zero(), canvas().size());
+ DisplayList::Replayer replayer(*canvas().drawingContext(), m_recordingContext->displayList);
+
+ if (UNLIKELY(m_tracksDisplayListReplay)) {
+ auto replayList = replayer.replay(clip, m_tracksDisplayListReplay);
+ contextDisplayListMap().add(this, WTFMove(replayList));
+ } else
+ replayer.replay(clip);
+
+ m_recordingContext->displayList.clear();
+ }
}
-PassRefPtr<ImageData> CanvasRenderingContext2D::createImageData(float sw, float sh, ExceptionCode& ec) const
+GraphicsContext* CanvasRenderingContext2D::drawingContext() const
{
- ec = 0;
- if (!sw || !sh) {
- ec = INDEX_SIZE_ERR;
- return 0;
- }
- if (!std::isfinite(sw) || !std::isfinite(sh)) {
- ec = NOT_SUPPORTED_ERR;
- return 0;
+ if (UNLIKELY(m_usesDisplayListDrawing)) {
+ if (!m_recordingContext)
+ m_recordingContext = std::make_unique<DisplayListDrawingContext>(FloatRect(FloatPoint::zero(), canvas().size()));
+ return &m_recordingContext->context;
}
-#if PLATFORM(IOS)
- // If the canvas element was created before Document had a Frame,
- // then no maximumDecodedImageSize was set.
- if (!canvas()->maximumDecodedImageSize()) {
- if (Settings* settings = canvas()->document().settings())
- canvas()->setMaximumDecodedImageSize(settings->maximumDecodedImageSize());
- }
-#endif
+ return canvas().drawingContext();
+}
+
+static RefPtr<ImageData> createEmptyImageData(const IntSize& size)
+{
+ auto data = ImageData::create(size);
+ if (data)
+ data->data()->zeroFill();
+ return data;
+}
+
+ExceptionOr<RefPtr<ImageData>> CanvasRenderingContext2D::createImageData(ImageData* imageData) const
+{
+ if (!imageData)
+ return Exception { NOT_SUPPORTED_ERR };
+
+ return createEmptyImageData(imageData->size());
+}
- FloatSize logicalSize(fabs(sw), fabs(sh));
+ExceptionOr<RefPtr<ImageData>> CanvasRenderingContext2D::createImageData(float sw, float sh) const
+{
+ if (!sw || !sh)
+ return Exception { INDEX_SIZE_ERR };
+
+ FloatSize logicalSize(std::abs(sw), std::abs(sh));
if (!logicalSize.isExpressibleAsIntSize())
- return 0;
+ return nullptr;
IntSize size = expandedIntSize(logicalSize);
if (size.width() < 1)
@@ -1837,33 +1965,26 @@ PassRefPtr<ImageData> CanvasRenderingContext2D::createImageData(float sw, float
return createEmptyImageData(size);
}
-PassRefPtr<ImageData> CanvasRenderingContext2D::getImageData(float sx, float sy, float sw, float sh, ExceptionCode& ec) const
+ExceptionOr<RefPtr<ImageData>> CanvasRenderingContext2D::getImageData(float sx, float sy, float sw, float sh) const
{
- return getImageData(ImageBuffer::LogicalCoordinateSystem, sx, sy, sw, sh, ec);
+ return getImageData(ImageBuffer::LogicalCoordinateSystem, sx, sy, sw, sh);
}
-PassRefPtr<ImageData> CanvasRenderingContext2D::webkitGetImageDataHD(float sx, float sy, float sw, float sh, ExceptionCode& ec) const
+ExceptionOr<RefPtr<ImageData>> CanvasRenderingContext2D::webkitGetImageDataHD(float sx, float sy, float sw, float sh) const
{
- return getImageData(ImageBuffer::BackingStoreCoordinateSystem, sx, sy, sw, sh, ec);
+ return getImageData(ImageBuffer::BackingStoreCoordinateSystem, sx, sy, sw, sh);
}
-PassRefPtr<ImageData> CanvasRenderingContext2D::getImageData(ImageBuffer::CoordinateSystem coordinateSystem, float sx, float sy, float sw, float sh, ExceptionCode& ec) const
+ExceptionOr<RefPtr<ImageData>> CanvasRenderingContext2D::getImageData(ImageBuffer::CoordinateSystem coordinateSystem, float sx, float sy, float sw, float sh) const
{
- if (!canvas()->originClean()) {
- DEFINE_STATIC_LOCAL(String, consoleMessage, (ASCIILiteral("Unable to get image data from canvas because the canvas has been tainted by cross-origin data.")));
- canvas()->document().addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, consoleMessage);
- ec = SECURITY_ERR;
- return 0;
+ if (!canvas().originClean()) {
+ static NeverDestroyed<String> consoleMessage(ASCIILiteral("Unable to get image data from canvas because the canvas has been tainted by cross-origin data."));
+ canvas().document().addConsoleMessage(MessageSource::Security, MessageLevel::Error, consoleMessage);
+ return Exception { SECURITY_ERR };
}
- if (!sw || !sh) {
- ec = INDEX_SIZE_ERR;
- return 0;
- }
- if (!std::isfinite(sx) || !std::isfinite(sy) || !std::isfinite(sw) || !std::isfinite(sh)) {
- ec = NOT_SUPPORTED_ERR;
- return 0;
- }
+ if (!sw || !sh)
+ return Exception { INDEX_SIZE_ERR };
if (sw < 0) {
sx += sw;
@@ -1874,77 +1995,75 @@ PassRefPtr<ImageData> CanvasRenderingContext2D::getImageData(ImageBuffer::Coordi
sh = -sh;
}
-#if PLATFORM(IOS)
- // If the canvas element was created before Document had a Frame,
- // then no maximumDecodedImageSize was set.
- if (!canvas()->maximumDecodedImageSize()) {
- if (Settings* settings = canvas()->document().settings())
- canvas()->setMaximumDecodedImageSize(settings->maximumDecodedImageSize());
- }
-#endif
-
FloatRect logicalRect(sx, sy, sw, sh);
if (logicalRect.width() < 1)
logicalRect.setWidth(1);
if (logicalRect.height() < 1)
logicalRect.setHeight(1);
if (!logicalRect.isExpressibleAsIntRect())
- return 0;
+ return nullptr;
IntRect imageDataRect = enclosingIntRect(logicalRect);
- ImageBuffer* buffer = canvas()->buffer();
+ ImageBuffer* buffer = canvas().buffer();
if (!buffer)
return createEmptyImageData(imageDataRect.size());
- RefPtr<Uint8ClampedArray> byteArray = buffer->getUnmultipliedImageData(imageDataRect, coordinateSystem);
- if (!byteArray)
- return 0;
+ auto byteArray = buffer->getUnmultipliedImageData(imageDataRect, coordinateSystem);
+ if (!byteArray) {
+ StringBuilder consoleMessage;
+ consoleMessage.appendLiteral("Unable to get image data from canvas. Requested size was ");
+ consoleMessage.appendNumber(imageDataRect.width());
+ consoleMessage.appendLiteral(" x ");
+ consoleMessage.appendNumber(imageDataRect.height());
- return ImageData::create(imageDataRect.size(), byteArray.release());
+ canvas().document().addConsoleMessage(MessageSource::Rendering, MessageLevel::Error, consoleMessage.toString());
+ return Exception { INVALID_STATE_ERR };
+ }
+
+ return ImageData::create(imageDataRect.size(), byteArray.releaseNonNull());
}
-void CanvasRenderingContext2D::putImageData(ImageData* data, float dx, float dy, ExceptionCode& ec)
+void CanvasRenderingContext2D::putImageData(ImageData& data, float dx, float dy)
{
- if (!data) {
- ec = TYPE_MISMATCH_ERR;
- return;
- }
- putImageData(data, dx, dy, 0, 0, data->width(), data->height(), ec);
+ putImageData(data, dx, dy, 0, 0, data.width(), data.height());
}
-void CanvasRenderingContext2D::webkitPutImageDataHD(ImageData* data, float dx, float dy, ExceptionCode& ec)
+void CanvasRenderingContext2D::webkitPutImageDataHD(ImageData& data, float dx, float dy)
{
- if (!data) {
- ec = TYPE_MISMATCH_ERR;
- return;
- }
- webkitPutImageDataHD(data, dx, dy, 0, 0, data->width(), data->height(), ec);
+ webkitPutImageDataHD(data, dx, dy, 0, 0, data.width(), data.height());
}
-void CanvasRenderingContext2D::putImageData(ImageData* data, float dx, float dy, float dirtyX, float dirtyY,
- float dirtyWidth, float dirtyHeight, ExceptionCode& ec)
+void CanvasRenderingContext2D::putImageData(ImageData& data, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight)
{
- putImageData(data, ImageBuffer::LogicalCoordinateSystem, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight, ec);
+ putImageData(data, ImageBuffer::LogicalCoordinateSystem, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight);
}
-void CanvasRenderingContext2D::webkitPutImageDataHD(ImageData* data, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight, ExceptionCode& ec)
+void CanvasRenderingContext2D::webkitPutImageDataHD(ImageData& data, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight)
{
- putImageData(data, ImageBuffer::BackingStoreCoordinateSystem, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight, ec);
+ putImageData(data, ImageBuffer::BackingStoreCoordinateSystem, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight);
}
-void CanvasRenderingContext2D::putImageData(ImageData* data, ImageBuffer::CoordinateSystem coordinateSystem, float dx, float dy, float dirtyX, float dirtyY,
- float dirtyWidth, float dirtyHeight, ExceptionCode& ec)
+void CanvasRenderingContext2D::drawFocusIfNeeded(Element& element)
{
- if (!data) {
- ec = TYPE_MISMATCH_ERR;
- return;
- }
- if (!std::isfinite(dx) || !std::isfinite(dy) || !std::isfinite(dirtyX) || !std::isfinite(dirtyY) || !std::isfinite(dirtyWidth) || !std::isfinite(dirtyHeight)) {
- ec = NOT_SUPPORTED_ERR;
+ drawFocusIfNeededInternal(m_path, element);
+}
+
+void CanvasRenderingContext2D::drawFocusIfNeeded(DOMPath& path, Element& element)
+{
+ drawFocusIfNeededInternal(path.path(), element);
+}
+
+void CanvasRenderingContext2D::drawFocusIfNeededInternal(const Path& path, Element& element)
+{
+ auto* context = drawingContext();
+ if (!element.focused() || !state().hasInvertibleTransform || path.isEmpty() || !element.isDescendantOf(canvas()) || !context)
return;
- }
+ context->drawFocusRing(path, 1, 1, RenderTheme::focusRingColor());
+}
- ImageBuffer* buffer = canvas()->buffer();
+void CanvasRenderingContext2D::putImageData(ImageData& data, ImageBuffer::CoordinateSystem coordinateSystem, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight)
+{
+ ImageBuffer* buffer = canvas().buffer();
if (!buffer)
return;
@@ -1959,7 +2078,7 @@ void CanvasRenderingContext2D::putImageData(ImageData* data, ImageBuffer::Coordi
}
FloatRect clipRect(dirtyX, dirtyY, dirtyWidth, dirtyHeight);
- clipRect.intersect(IntRect(0, 0, data->width(), data->height()));
+ clipRect.intersect(IntRect(0, 0, data.width(), data.height()));
IntSize destOffset(static_cast<int>(dx), static_cast<int>(dy));
IntRect destRect = enclosingIntRect(clipRect);
destRect.move(destOffset);
@@ -1968,38 +2087,35 @@ void CanvasRenderingContext2D::putImageData(ImageData* data, ImageBuffer::Coordi
return;
IntRect sourceRect(destRect);
sourceRect.move(-destOffset);
+ sourceRect.intersect(IntRect(0, 0, data.width(), data.height()));
- buffer->putByteArray(Unmultiplied, data->data(), IntSize(data->width(), data->height()), sourceRect, IntPoint(destOffset), coordinateSystem);
+ if (!sourceRect.isEmpty())
+ buffer->putByteArray(Unmultiplied, data.data(), IntSize(data.width(), data.height()), sourceRect, IntPoint(destOffset), coordinateSystem);
- if (coordinateSystem == ImageBuffer::BackingStoreCoordinateSystem) {
- FloatRect dirtyRect = destRect;
- dirtyRect.scale(1 / canvas()->deviceScaleFactor());
- destRect = enclosingIntRect(dirtyRect);
- }
didDraw(destRect, CanvasDidDrawApplyNone); // ignore transform, shadow and clip
}
String CanvasRenderingContext2D::font() const
{
- if (!state().m_realizedFont)
+ if (!state().font.realized())
return defaultFont;
StringBuilder serializedFont;
- const FontDescription& fontDescription = state().m_font.fontDescription();
+ const auto& fontDescription = state().font.fontDescription();
if (fontDescription.italic())
serializedFont.appendLiteral("italic ");
- if (fontDescription.smallCaps() == FontSmallCapsOn)
+ if (fontDescription.variantCaps() == FontVariantCaps::Small)
serializedFont.appendLiteral("small-caps ");
serializedFont.appendNumber(fontDescription.computedPixelSize());
serializedFont.appendLiteral("px");
- for (unsigned i = 0; i < state().m_font.familyCount(); ++i) {
+ for (unsigned i = 0; i < fontDescription.familyCount(); ++i) {
if (i)
serializedFont.append(',');
// FIXME: We should append family directly to serializedFont rather than building a temporary string.
- String family = state().m_font.familyAt(i);
+ String family = fontDescription.familyAt(i);
if (family.startsWith("-webkit-"))
family = family.substring(8);
if (family.contains(' '))
@@ -2014,11 +2130,11 @@ String CanvasRenderingContext2D::font() const
void CanvasRenderingContext2D::setFont(const String& newFont)
{
- if (newFont == state().m_unparsedFont && state().m_realizedFont)
+ if (newFont == state().unparsedFont && state().font.realized())
return;
- RefPtr<MutableStyleProperties> parsedStyle = MutableStyleProperties::create();
- CSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, newFont, true, strictToCSSParserMode(!m_usesCSSCompatibilityParseMode), 0);
+ auto parsedStyle = MutableStyleProperties::create();
+ CSSParser::parseValue(parsedStyle, CSSPropertyFont, newFont, true, strictToCSSParserMode(!m_usesCSSCompatibilityParseMode));
if (parsedStyle->isEmpty())
return;
@@ -2032,15 +2148,19 @@ void CanvasRenderingContext2D::setFont(const String& newFont)
// The parse succeeded.
String newFontSafeCopy(newFont); // Create a string copy since newFont can be deleted inside realizeSaves.
realizeSaves();
- modifiableState().m_unparsedFont = newFontSafeCopy;
+ modifiableState().unparsedFont = newFontSafeCopy;
// Map the <canvas> font into the text style. If the font uses keywords like larger/smaller, these will work
// relative to the canvas.
- RefPtr<RenderStyle> newStyle = RenderStyle::create();
- if (RenderStyle* computedStyle = canvas()->computedStyle())
+ auto newStyle = RenderStyle::createPtr();
+
+ Document& document = canvas().document();
+ document.updateStyleIfNeeded();
+
+ if (auto* computedStyle = canvas().computedStyle())
newStyle->setFontDescription(computedStyle->fontDescription());
else {
- FontDescription defaultFontDescription;
+ FontCascadeDescription defaultFontDescription;
defaultFontDescription.setOneFamily(defaultFontFamily);
defaultFontDescription.setSpecifiedSize(defaultFontSize);
defaultFontDescription.setComputedSize(defaultFontSize);
@@ -2048,13 +2168,13 @@ void CanvasRenderingContext2D::setFont(const String& newFont)
newStyle->setFontDescription(defaultFontDescription);
}
- newStyle->font().update(newStyle->font().fontSelector());
+ newStyle->fontCascade().update(&document.fontSelector());
// Now map the font property longhands into the style.
- StyleResolver& styleResolver = canvas()->document().ensureStyleResolver();
- styleResolver.applyPropertyToStyle(CSSPropertyFontFamily, parsedStyle->getPropertyCSSValue(CSSPropertyFontFamily).get(), newStyle.get());
+ StyleResolver& styleResolver = canvas().styleResolver();
+ styleResolver.applyPropertyToStyle(CSSPropertyFontFamily, parsedStyle->getPropertyCSSValue(CSSPropertyFontFamily).get(), WTFMove(newStyle));
styleResolver.applyPropertyToCurrentStyle(CSSPropertyFontStyle, parsedStyle->getPropertyCSSValue(CSSPropertyFontStyle).get());
- styleResolver.applyPropertyToCurrentStyle(CSSPropertyFontVariant, parsedStyle->getPropertyCSSValue(CSSPropertyFontVariant).get());
+ styleResolver.applyPropertyToCurrentStyle(CSSPropertyFontVariantCaps, parsedStyle->getPropertyCSSValue(CSSPropertyFontVariantCaps).get());
styleResolver.applyPropertyToCurrentStyle(CSSPropertyFontWeight, parsedStyle->getPropertyCSSValue(CSSPropertyFontWeight).get());
// As described in BUG66291, setting font-size and line-height on a font may entail a CSSPrimitiveValue::computeLengthDouble call,
@@ -2065,15 +2185,12 @@ void CanvasRenderingContext2D::setFont(const String& newFont)
styleResolver.updateFont();
styleResolver.applyPropertyToCurrentStyle(CSSPropertyLineHeight, parsedStyle->getPropertyCSSValue(CSSPropertyLineHeight).get());
- modifiableState().m_font = newStyle->font();
- modifiableState().m_font.update(styleResolver.fontSelector());
- modifiableState().m_realizedFont = true;
- styleResolver.fontSelector()->registerForInvalidationCallbacks(&modifiableState());
+ modifiableState().font.initialize(document.fontSelector(), *styleResolver.style());
}
String CanvasRenderingContext2D::textAlign() const
{
- return textAlignName(state().m_textAlign);
+ return textAlignName(state().textAlign);
}
void CanvasRenderingContext2D::setTextAlign(const String& s)
@@ -2081,15 +2198,15 @@ void CanvasRenderingContext2D::setTextAlign(const String& s)
TextAlign align;
if (!parseTextAlign(s, align))
return;
- if (state().m_textAlign == align)
+ if (state().textAlign == align)
return;
realizeSaves();
- modifiableState().m_textAlign = align;
+ modifiableState().textAlign = align;
}
String CanvasRenderingContext2D::textBaseline() const
{
- return textBaselineName(state().m_textBaseline);
+ return textBaselineName(state().textBaseline);
}
void CanvasRenderingContext2D::setTextBaseline(const String& s)
@@ -2097,30 +2214,63 @@ void CanvasRenderingContext2D::setTextBaseline(const String& s)
TextBaseline baseline;
if (!parseTextBaseline(s, baseline))
return;
- if (state().m_textBaseline == baseline)
+ if (state().textBaseline == baseline)
return;
realizeSaves();
- modifiableState().m_textBaseline = baseline;
+ modifiableState().textBaseline = baseline;
}
-void CanvasRenderingContext2D::fillText(const String& text, float x, float y)
+inline TextDirection CanvasRenderingContext2D::toTextDirection(Direction direction, const RenderStyle** computedStyle) const
{
- drawTextInternal(text, x, y, true);
+ auto* style = (computedStyle || direction == Direction::Inherit) ? canvas().computedStyle() : nullptr;
+ if (computedStyle)
+ *computedStyle = style;
+ switch (direction) {
+ case Direction::Inherit:
+ return style ? style->direction() : LTR;
+ case Direction::RTL:
+ return RTL;
+ case Direction::LTR:
+ return LTR;
+ }
+ ASSERT_NOT_REACHED();
+ return LTR;
}
-void CanvasRenderingContext2D::fillText(const String& text, float x, float y, float maxWidth)
+String CanvasRenderingContext2D::direction() const
{
- drawTextInternal(text, x, y, true, maxWidth, true);
+ if (state().direction == Direction::Inherit)
+ canvas().document().updateStyleIfNeeded();
+ return toTextDirection(state().direction) == RTL ? ASCIILiteral("rtl") : ASCIILiteral("ltr");
}
-void CanvasRenderingContext2D::strokeText(const String& text, float x, float y)
+void CanvasRenderingContext2D::setDirection(const String& directionString)
{
- drawTextInternal(text, x, y, false);
+ Direction direction;
+ if (directionString == "inherit")
+ direction = Direction::Inherit;
+ else if (directionString == "rtl")
+ direction = Direction::RTL;
+ else if (directionString == "ltr")
+ direction = Direction::LTR;
+ else
+ return;
+
+ if (state().direction == direction)
+ return;
+
+ realizeSaves();
+ modifiableState().direction = direction;
+}
+
+void CanvasRenderingContext2D::fillText(const String& text, float x, float y, std::optional<float> maxWidth)
+{
+ drawTextInternal(text, x, y, true, maxWidth);
}
-void CanvasRenderingContext2D::strokeText(const String& text, float x, float y, float maxWidth)
+void CanvasRenderingContext2D::strokeText(const String& text, float x, float y, std::optional<float> maxWidth)
{
- drawTextInternal(text, x, y, false, maxWidth, true);
+ drawTextInternal(text, x, y, false, maxWidth);
}
static inline bool isSpaceThatNeedsReplacing(UChar c)
@@ -2137,13 +2287,12 @@ static inline bool isSpaceThatNeedsReplacing(UChar c)
static void normalizeSpaces(String& text)
{
size_t i = text.find(isSpaceThatNeedsReplacing);
-
if (i == notFound)
return;
unsigned textLength = text.length();
Vector<UChar> charVector(textLength);
- memcpy(charVector.data(), text.deprecatedCharacters(), textLength * sizeof(UChar));
+ StringView(text).getCharactersWithUpconvert(charVector.data());
charVector[i++] = ' ';
@@ -2151,37 +2300,38 @@ static void normalizeSpaces(String& text)
if (isSpaceThatNeedsReplacing(charVector[i]))
charVector[i] = ' ';
}
- text = String::adopt(charVector);
+ text = String::adopt(WTFMove(charVector));
}
-PassRefPtr<TextMetrics> CanvasRenderingContext2D::measureText(const String& text)
+Ref<TextMetrics> CanvasRenderingContext2D::measureText(const String& text)
{
- FontCachePurgePreventer fontCachePurgePreventer;
-
- RefPtr<TextMetrics> metrics = TextMetrics::create();
+ Ref<TextMetrics> metrics = TextMetrics::create();
String normalizedText = text;
normalizeSpaces(normalizedText);
- metrics->setWidth(accessFont().width(TextRun(normalizedText)));
+ metrics->setWidth(fontProxy().width(TextRun(normalizedText)));
- return metrics.release();
+ return metrics;
}
-void CanvasRenderingContext2D::drawTextInternal(const String& text, float x, float y, bool fill, float maxWidth, bool useMaxWidth)
+void CanvasRenderingContext2D::drawTextInternal(const String& text, float x, float y, bool fill, std::optional<float> maxWidth)
{
- GraphicsContext* c = drawingContext();
+ auto& fontProxy = this->fontProxy();
+ const auto& fontMetrics = fontProxy.fontMetrics();
+
+ auto* c = drawingContext();
if (!c)
return;
- if (!state().m_hasInvertibleTransform)
+ if (!state().hasInvertibleTransform)
return;
if (!std::isfinite(x) | !std::isfinite(y))
return;
- if (useMaxWidth && (!std::isfinite(maxWidth) || maxWidth <= 0))
+ if (maxWidth && (!std::isfinite(maxWidth.value()) || maxWidth.value() <= 0))
return;
// If gradient size is zero, then paint nothing.
- Gradient* gradient = c->strokeGradient();
+ auto* gradient = c->strokeGradient();
if (!fill && gradient && gradient->isZeroSize())
return;
@@ -2189,25 +2339,20 @@ void CanvasRenderingContext2D::drawTextInternal(const String& text, float x, flo
if (fill && gradient && gradient->isZeroSize())
return;
- FontCachePurgePreventer fontCachePurgePreventer;
-
- const Font& font = accessFont();
- const FontMetrics& fontMetrics = font.fontMetrics();
-
String normalizedText = text;
normalizeSpaces(normalizedText);
// FIXME: Need to turn off font smoothing.
- RenderStyle* computedStyle = canvas()->computedStyle();
- TextDirection direction = computedStyle ? computedStyle->direction() : LTR;
+ const RenderStyle* computedStyle;
+ auto direction = toTextDirection(state().direction, &computedStyle);
bool isRTL = direction == RTL;
bool override = computedStyle ? isOverride(computedStyle->unicodeBidi()) : false;
- TextRun textRun(normalizedText, 0, 0, TextRun::AllowTrailingExpansion, direction, override, true, TextRun::NoRounding);
+ TextRun textRun(normalizedText, 0, 0, AllowTrailingExpansion, direction, override, true);
// Draw the item text at the correct point.
FloatPoint location(x, y);
- switch (state().m_textBaseline) {
+ switch (state().textBaseline) {
case TopTextBaseline:
case HangingTextBaseline:
location.setY(y + fontMetrics.ascent());
@@ -2225,12 +2370,12 @@ void CanvasRenderingContext2D::drawTextInternal(const String& text, float x, flo
break;
}
- float fontWidth = font.width(TextRun(normalizedText, 0, 0, TextRun::AllowTrailingExpansion, direction, override));
+ float fontWidth = fontProxy.width(TextRun(normalizedText, 0, 0, AllowTrailingExpansion, direction, override));
- useMaxWidth = (useMaxWidth && maxWidth < fontWidth);
- float width = useMaxWidth ? maxWidth : fontWidth;
+ bool useMaxWidth = maxWidth && maxWidth.value() < fontWidth;
+ float width = useMaxWidth ? maxWidth.value() : fontWidth;
- TextAlign align = state().m_textAlign;
+ auto align = state().textAlign;
if (align == StartTextAlign)
align = isRTL ? RightTextAlign : LeftTextAlign;
else if (align == EndTextAlign)
@@ -2249,41 +2394,73 @@ void CanvasRenderingContext2D::drawTextInternal(const String& text, float x, flo
// The slop built in to this mask rect matches the heuristic used in FontCGWin.cpp for GDI text.
FloatRect textRect = FloatRect(location.x() - fontMetrics.height() / 2, location.y() - fontMetrics.ascent() - fontMetrics.lineGap(),
- width + fontMetrics.height(), fontMetrics.lineSpacing());
+ width + fontMetrics.height(), fontMetrics.lineSpacing());
if (!fill)
inflateStrokeRect(textRect);
#if USE(CG)
- const CanvasStyle& drawStyle = fill ? state().m_fillStyle : state().m_strokeStyle;
+ const CanvasStyle& drawStyle = fill ? state().fillStyle : state().strokeStyle;
if (drawStyle.canvasGradient() || drawStyle.canvasPattern()) {
IntRect maskRect = enclosingIntRect(textRect);
- std::unique_ptr<ImageBuffer> maskImage = c->createCompatibleBuffer(maskRect.size());
+ // If we have a shadow, we need to draw it before the mask operation.
+ // Follow a procedure similar to paintTextWithShadows in TextPainter.
+
+ if (shouldDrawShadows()) {
+ GraphicsContextStateSaver stateSaver(*c);
- GraphicsContext* maskImageContext = maskImage->context();
+ FloatSize offset(0, 2 * maskRect.height());
+
+ FloatSize shadowOffset;
+ float shadowRadius;
+ Color shadowColor;
+ c->getShadow(shadowOffset, shadowRadius, shadowColor);
+
+ FloatRect shadowRect(maskRect);
+ shadowRect.inflate(shadowRadius * 1.4);
+ shadowRect.move(shadowOffset * -1);
+ c->clip(shadowRect);
+
+ shadowOffset += offset;
+
+ c->setLegacyShadow(shadowOffset, shadowRadius, shadowColor);
+
+ if (fill)
+ c->setFillColor(Color::black);
+ else
+ c->setStrokeColor(Color::black);
+
+ fontProxy.drawBidiText(*c, textRun, location + offset, FontCascade::UseFallbackIfFontNotReady);
+ }
+
+ auto maskImage = ImageBuffer::createCompatibleBuffer(maskRect.size(), ColorSpaceSRGB, *c);
+ if (!maskImage)
+ return;
+
+ auto& maskImageContext = maskImage->context();
if (fill)
- maskImageContext->setFillColor(Color::black, ColorSpaceDeviceRGB);
+ maskImageContext.setFillColor(Color::black);
else {
- maskImageContext->setStrokeColor(Color::black, ColorSpaceDeviceRGB);
- maskImageContext->setStrokeThickness(c->strokeThickness());
+ maskImageContext.setStrokeColor(Color::black);
+ maskImageContext.setStrokeThickness(c->strokeThickness());
}
- maskImageContext->setTextDrawingMode(fill ? TextModeFill : TextModeStroke);
+ maskImageContext.setTextDrawingMode(fill ? TextModeFill : TextModeStroke);
if (useMaxWidth) {
- maskImageContext->translate(location.x() - maskRect.x(), location.y() - maskRect.y());
+ maskImageContext.translate(location.x() - maskRect.x(), location.y() - maskRect.y());
// We draw when fontWidth is 0 so compositing operations (eg, a "copy" op) still work.
- maskImageContext->scale(FloatSize((fontWidth > 0 ? (width / fontWidth) : 0), 1));
- maskImageContext->drawBidiText(font, textRun, FloatPoint(0, 0), Font::UseFallbackIfFontNotReady);
+ maskImageContext.scale(FloatSize((fontWidth > 0 ? (width / fontWidth) : 0), 1));
+ fontProxy.drawBidiText(maskImageContext, textRun, FloatPoint(0, 0), FontCascade::UseFallbackIfFontNotReady);
} else {
- maskImageContext->translate(-maskRect.x(), -maskRect.y());
- maskImageContext->drawBidiText(font, textRun, location, Font::UseFallbackIfFontNotReady);
+ maskImageContext.translate(-maskRect.x(), -maskRect.y());
+ fontProxy.drawBidiText(maskImageContext, textRun, location, FontCascade::UseFallbackIfFontNotReady);
}
GraphicsContextStateSaver stateSaver(*c);
- c->clipToImageBuffer(maskImage.get(), maskRect);
- drawStyle.applyFillColor(c);
+ c->clipToImageBuffer(*maskImage, maskRect);
+ drawStyle.applyFillColor(*c);
c->fillRect(maskRect);
return;
}
@@ -2291,16 +2468,27 @@ void CanvasRenderingContext2D::drawTextInternal(const String& text, float x, flo
c->setTextDrawingMode(fill ? TextModeFill : TextModeStroke);
+ GraphicsContextStateSaver stateSaver(*c);
if (useMaxWidth) {
- GraphicsContextStateSaver stateSaver(*c);
c->translate(location.x(), location.y());
// We draw when fontWidth is 0 so compositing operations (eg, a "copy" op) still work.
c->scale(FloatSize((fontWidth > 0 ? (width / fontWidth) : 0), 1));
- c->drawBidiText(font, textRun, FloatPoint(0, 0), Font::UseFallbackIfFontNotReady);
- } else
- c->drawBidiText(font, textRun, location, Font::UseFallbackIfFontNotReady);
+ location = FloatPoint();
+ }
- didDraw(textRect);
+ if (isFullCanvasCompositeMode(state().globalComposite)) {
+ beginCompositeLayer();
+ fontProxy.drawBidiText(*c, textRun, location, FontCascade::UseFallbackIfFontNotReady);
+ endCompositeLayer();
+ didDrawEntireCanvas();
+ } else if (state().globalComposite == CompositeCopy) {
+ clearCanvas();
+ fontProxy.drawBidiText(*c, textRun, location, FontCascade::UseFallbackIfFontNotReady);
+ didDrawEntireCanvas();
+ } else {
+ fontProxy.drawBidiText(*c, textRun, location, FontCascade::UseFallbackIfFontNotReady);
+ didDraw(textRect);
+ }
}
void CanvasRenderingContext2D::inflateStrokeRect(FloatRect& rect) const
@@ -2309,46 +2497,81 @@ void CanvasRenderingContext2D::inflateStrokeRect(FloatRect& rect) const
// This yields a slightly oversized rect but is very fast
// compared to Path::strokeBoundingRect().
static const float root2 = sqrtf(2);
- float delta = state().m_lineWidth / 2;
- if (state().m_lineJoin == MiterJoin)
- delta *= state().m_miterLimit;
- else if (state().m_lineCap == SquareCap)
+ float delta = state().lineWidth / 2;
+ if (state().lineJoin == MiterJoin)
+ delta *= state().miterLimit;
+ else if (state().lineCap == SquareCap)
delta *= root2;
-
rect.inflate(delta);
}
-const Font& CanvasRenderingContext2D::accessFont()
+auto CanvasRenderingContext2D::fontProxy() -> const FontProxy&
{
- canvas()->document().updateStyleIfNeeded();
-
- if (!state().m_realizedFont)
- setFont(state().m_unparsedFont);
- return state().m_font;
+ canvas().document().updateStyleIfNeeded();
+ if (!state().font.realized())
+ setFont(state().unparsedFont);
+ return state().font;
}
-#if ENABLE(ACCELERATED_2D_CANVAS) && USE(ACCELERATED_COMPOSITING)
+#if ENABLE(ACCELERATED_2D_CANVAS)
+
PlatformLayer* CanvasRenderingContext2D::platformLayer() const
{
- return canvas()->buffer() ? canvas()->buffer()->platformLayer() : 0;
+ return canvas().buffer() ? canvas().buffer()->platformLayer() : nullptr;
}
+
#endif
-bool CanvasRenderingContext2D::webkitImageSmoothingEnabled() const
+static inline InterpolationQuality smoothingToInterpolationQuality(CanvasRenderingContext2D::ImageSmoothingQuality quality)
+{
+ switch (quality) {
+ case CanvasRenderingContext2D::ImageSmoothingQuality::Low:
+ return InterpolationLow;
+ case CanvasRenderingContext2D::ImageSmoothingQuality::Medium:
+ return InterpolationMedium;
+ case CanvasRenderingContext2D::ImageSmoothingQuality::High:
+ return InterpolationHigh;
+ }
+
+ ASSERT_NOT_REACHED();
+ return InterpolationLow;
+};
+
+auto CanvasRenderingContext2D::imageSmoothingQuality() const -> ImageSmoothingQuality
{
- return state().m_imageSmoothingEnabled;
+ return state().imageSmoothingQuality;
}
-void CanvasRenderingContext2D::setWebkitImageSmoothingEnabled(bool enabled)
+void CanvasRenderingContext2D::setImageSmoothingQuality(ImageSmoothingQuality quality)
{
- if (enabled == state().m_imageSmoothingEnabled)
+ if (quality == state().imageSmoothingQuality)
return;
realizeSaves();
- modifiableState().m_imageSmoothingEnabled = enabled;
- GraphicsContext* c = drawingContext();
+ modifiableState().imageSmoothingQuality = quality;
+
+ if (!state().imageSmoothingEnabled)
+ return;
+
+ if (auto* context = drawingContext())
+ context->setImageInterpolationQuality(smoothingToInterpolationQuality(quality));
+}
+
+bool CanvasRenderingContext2D::imageSmoothingEnabled() const
+{
+ return state().imageSmoothingEnabled;
+}
+
+void CanvasRenderingContext2D::setImageSmoothingEnabled(bool enabled)
+{
+ if (enabled == state().imageSmoothingEnabled)
+ return;
+
+ realizeSaves();
+ modifiableState().imageSmoothingEnabled = enabled;
+ auto* c = drawingContext();
if (c)
- c->setImageInterpolationQuality(enabled ? DefaultInterpolationQuality : InterpolationNone);
+ c->setImageInterpolationQuality(enabled ? smoothingToInterpolationQuality(state().imageSmoothingQuality) : InterpolationNone);
}
} // namespace WebCore