2 * Copyright (C) 2003, 2004, 2005, 2006, 2009 Apple Inc. All rights reserved.
3 * Copyright (C) 2013 Google Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
15 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
16 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
18 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
24 * THE POSSIBILITY OF SUCH DAMAGE.
28 #include "platform/graphics/GraphicsContext.h"
30 #include "platform/geometry/IntRect.h"
31 #include "platform/geometry/RoundedRect.h"
32 #include "platform/graphics/BitmapImage.h"
33 #include "platform/graphics/DisplayList.h"
34 #include "platform/graphics/Gradient.h"
35 #include "platform/graphics/ImageBuffer.h"
36 #include "platform/text/BidiResolver.h"
37 #include "platform/text/TextRunIterator.h"
38 #include "platform/weborigin/KURL.h"
39 #include "third_party/skia/include/core/SkAnnotation.h"
40 #include "third_party/skia/include/core/SkColorFilter.h"
41 #include "third_party/skia/include/core/SkData.h"
42 #include "third_party/skia/include/core/SkDevice.h"
43 #include "third_party/skia/include/core/SkPicture.h"
44 #include "third_party/skia/include/core/SkRRect.h"
45 #include "third_party/skia/include/core/SkRefCnt.h"
46 #include "third_party/skia/include/effects/SkBlurMaskFilter.h"
47 #include "third_party/skia/include/effects/SkCornerPathEffect.h"
48 #include "third_party/skia/include/effects/SkLumaColorFilter.h"
49 #include "third_party/skia/include/gpu/GrRenderTarget.h"
50 #include "third_party/skia/include/gpu/GrTexture.h"
51 #include "wtf/Assertions.h"
52 #include "wtf/MathExtras.h"
55 #include <ApplicationServices/ApplicationServices.h>
59 using blink::WebBlendMode;
65 class CompatibleImageBufferSurface : public ImageBufferSurface {
66 WTF_MAKE_NONCOPYABLE(CompatibleImageBufferSurface); WTF_MAKE_FAST_ALLOCATED;
68 CompatibleImageBufferSurface(PassRefPtr<SkBaseDevice> device, const IntSize& size, OpacityMode opacityMode)
69 : ImageBufferSurface(size, opacityMode)
71 m_canvas = adoptPtr(new SkCanvas(device.get())); // Takes a ref on device
73 virtual ~CompatibleImageBufferSurface() { }
75 virtual SkCanvas* canvas() const OVERRIDE { return m_canvas.get(); }
76 virtual bool isValid() const OVERRIDE { return m_canvas; }
77 virtual bool isAccelerated() const OVERRIDE { return isValid() && m_canvas->getTopDevice()->accessRenderTarget(); }
78 virtual Platform3DObject getBackingTexture() const OVERRIDE
80 ASSERT(isAccelerated());
81 GrRenderTarget* renderTarget = m_canvas->getTopDevice()->accessRenderTarget();
83 return renderTarget->asTexture()->getTextureHandle();
89 OwnPtr<SkCanvas> m_canvas;
92 } // unnamed namespace
94 struct GraphicsContext::DeferredSaveState {
95 DeferredSaveState(unsigned mask, int count) : m_flags(mask), m_restoreCount(count) { }
101 struct GraphicsContext::RecordingState {
102 RecordingState(SkCanvas* currentCanvas, const SkMatrix& currentMatrix, PassRefPtr<DisplayList> displayList)
103 : m_savedCanvas(currentCanvas)
104 , m_displayList(displayList)
105 , m_savedMatrix(currentMatrix)
109 SkCanvas* m_savedCanvas;
110 RefPtr<DisplayList> m_displayList;
111 const SkMatrix m_savedMatrix;
114 GraphicsContext::GraphicsContext(SkCanvas* canvas)
116 , m_deferredSaveFlags(0)
117 , m_annotationMode(0)
119 , m_annotationCount(0)
122 , m_trackOpaqueRegion(false)
123 , m_trackTextRegion(false)
124 , m_useHighResMarker(false)
125 , m_updatingControlTints(false)
126 , m_accelerated(false)
127 , m_isCertainlyOpaque(true)
130 m_stateStack.append(adoptPtr(new GraphicsContextState()));
131 m_state = m_stateStack.last().get();
134 GraphicsContext::~GraphicsContext()
136 ASSERT(m_stateStack.size() == 1);
137 ASSERT(!m_annotationCount);
138 ASSERT(!m_layerCount);
139 ASSERT(m_recordingStateStack.isEmpty());
142 const SkBitmap* GraphicsContext::bitmap() const
144 TRACE_EVENT0("skia", "GraphicsContext::bitmap");
145 return &m_canvas->getDevice()->accessBitmap(false);
148 const SkBitmap& GraphicsContext::layerBitmap(AccessMode access) const
150 return m_canvas->getTopDevice()->accessBitmap(access == ReadWrite);
153 void GraphicsContext::save()
155 if (paintingDisabled())
158 m_stateStack.append(m_state->clone());
159 m_state = m_stateStack.last().get();
161 m_saveStateStack.append(DeferredSaveState(m_deferredSaveFlags, m_canvas->getSaveCount()));
162 m_deferredSaveFlags |= SkCanvas::kMatrixClip_SaveFlag;
165 void GraphicsContext::restore()
167 if (paintingDisabled())
170 if (m_stateStack.size() == 1) {
171 WTF_LOG_ERROR("ERROR void GraphicsContext::restore() stack is empty");
175 m_stateStack.removeLast();
176 m_state = m_stateStack.last().get();
178 DeferredSaveState savedState = m_saveStateStack.last();
179 m_saveStateStack.removeLast();
180 m_deferredSaveFlags = savedState.m_flags;
181 m_canvas->restoreToCount(savedState.m_restoreCount);
184 void GraphicsContext::saveLayer(const SkRect* bounds, const SkPaint* paint, SkCanvas::SaveFlags saveFlags)
186 if (paintingDisabled())
189 realizeSave(SkCanvas::kMatrixClip_SaveFlag);
191 m_canvas->saveLayer(bounds, paint, saveFlags);
193 m_canvas->clipRect(*bounds);
194 if (m_trackOpaqueRegion)
195 m_opaqueRegion.pushCanvasLayer(paint);
198 void GraphicsContext::restoreLayer()
200 if (paintingDisabled())
204 if (m_trackOpaqueRegion)
205 m_opaqueRegion.popCanvasLayer(this);
208 void GraphicsContext::beginAnnotation(const char* rendererName, const char* paintPhase,
209 const String& elementId, const String& elementClass, const String& elementTag)
211 if (paintingDisabled())
214 canvas()->beginCommentGroup("GraphicsContextAnnotation");
216 GraphicsContextAnnotation annotation(rendererName, paintPhase, elementId, elementClass, elementTag);
217 AnnotationList annotations;
218 annotation.asAnnotationList(annotations);
220 AnnotationList::const_iterator end = annotations.end();
221 for (AnnotationList::const_iterator it = annotations.begin(); it != end; ++it)
222 canvas()->addComment(it->first, it->second.ascii().data());
229 void GraphicsContext::endAnnotation()
231 if (paintingDisabled())
234 canvas()->endCommentGroup();
236 ASSERT(m_annotationCount > 0);
242 void GraphicsContext::setStrokeColor(const Color& color)
244 m_state->m_strokeData.setColor(color);
245 m_state->m_strokeData.clearGradient();
246 m_state->m_strokeData.clearPattern();
249 void GraphicsContext::setStrokePattern(PassRefPtr<Pattern> pattern)
251 if (paintingDisabled())
256 setStrokeColor(Color::black);
259 m_state->m_strokeData.clearGradient();
260 m_state->m_strokeData.setPattern(pattern);
263 void GraphicsContext::setStrokeGradient(PassRefPtr<Gradient> gradient)
265 if (paintingDisabled())
270 setStrokeColor(Color::black);
273 m_state->m_strokeData.setGradient(gradient);
274 m_state->m_strokeData.clearPattern();
277 void GraphicsContext::setFillColor(const Color& color)
279 m_state->m_fillColor = color;
280 m_state->m_fillGradient.clear();
281 m_state->m_fillPattern.clear();
284 void GraphicsContext::setFillPattern(PassRefPtr<Pattern> pattern)
286 if (paintingDisabled())
291 setFillColor(Color::black);
294 m_state->m_fillGradient.clear();
295 m_state->m_fillPattern = pattern;
298 void GraphicsContext::setFillGradient(PassRefPtr<Gradient> gradient)
300 if (paintingDisabled())
305 setFillColor(Color::black);
308 m_state->m_fillGradient = gradient;
309 m_state->m_fillPattern.clear();
312 void GraphicsContext::setShadow(const FloatSize& offset, float blur, const Color& color,
313 DrawLooper::ShadowTransformMode shadowTransformMode,
314 DrawLooper::ShadowAlphaMode shadowAlphaMode)
316 if (paintingDisabled())
319 if (!color.alpha() || (!offset.width() && !offset.height() && !blur)) {
324 DrawLooper drawLooper;
325 drawLooper.addShadow(offset, blur, color, shadowTransformMode, shadowAlphaMode);
326 drawLooper.addUnmodifiedContent();
327 setDrawLooper(drawLooper);
330 void GraphicsContext::setDrawLooper(const DrawLooper& drawLooper)
332 if (paintingDisabled())
335 m_state->m_looper = drawLooper.skDrawLooper();
338 void GraphicsContext::clearDrawLooper()
340 if (paintingDisabled())
343 m_state->m_looper.clear();
346 bool GraphicsContext::hasShadow() const
348 return !!m_state->m_looper;
351 int GraphicsContext::getNormalizedAlpha() const
353 int alpha = roundf(m_state->m_alpha * 256);
361 FloatRect GraphicsContext::getClipBounds() const
363 if (paintingDisabled())
366 if (!m_canvas->getClipBounds(&rect))
368 return FloatRect(rect);
371 bool GraphicsContext::getTransformedClipBounds(FloatRect* bounds) const
373 if (paintingDisabled())
376 if (!m_canvas->getClipDeviceBounds(&skIBounds))
378 SkRect skBounds = SkRect::MakeFromIRect(skIBounds);
379 *bounds = FloatRect(skBounds);
383 SkMatrix GraphicsContext::getTotalMatrix() const
385 if (paintingDisabled())
386 return SkMatrix::I();
389 return m_canvas->getTotalMatrix();
391 const RecordingState& recordingState = m_recordingStateStack.last();
392 SkMatrix totalMatrix = recordingState.m_savedMatrix;
393 totalMatrix.preConcat(m_canvas->getTotalMatrix());
398 bool GraphicsContext::isPrintingDevice() const
400 if (paintingDisabled())
402 return m_canvas->getTopDevice()->getDeviceCapabilities() & SkBaseDevice::kVector_Capability;
405 void GraphicsContext::adjustTextRenderMode(SkPaint* paint)
407 if (paintingDisabled())
410 if (!paint->isLCDRenderText())
413 paint->setLCDRenderText(couldUseLCDRenderedText());
416 bool GraphicsContext::couldUseLCDRenderedText()
418 // Our layers only have a single alpha channel. This means that subpixel
419 // rendered text cannot be composited correctly when the layer is
420 // collapsed. Therefore, subpixel text is disabled when we are drawing
422 if (paintingDisabled() || isDrawingToLayer() || !isCertainlyOpaque())
425 return shouldSmoothFonts();
428 void GraphicsContext::setCompositeOperation(CompositeOperator compositeOperation, WebBlendMode blendMode)
430 m_state->m_compositeOperator = compositeOperation;
431 m_state->m_blendMode = blendMode;
432 m_state->m_xferMode = WebCoreCompositeToSkiaComposite(compositeOperation, blendMode);
435 SkColorFilter* GraphicsContext::colorFilter()
437 return m_state->m_colorFilter.get();
440 void GraphicsContext::setColorFilter(ColorFilter colorFilter)
442 // We only support one active color filter at the moment. If (when) this becomes a problem,
443 // we should switch to using color filter chains (Skia work in progress).
444 ASSERT(!m_state->m_colorFilter);
445 m_state->m_colorFilter = WebCoreColorFilterToSkiaColorFilter(colorFilter);
448 bool GraphicsContext::readPixels(SkBitmap* bitmap, int x, int y, SkCanvas::Config8888 config8888)
450 if (paintingDisabled())
453 return m_canvas->readPixels(bitmap, x, y, config8888);
456 void GraphicsContext::setMatrix(const SkMatrix& matrix)
458 if (paintingDisabled())
461 realizeSave(SkCanvas::kMatrix_SaveFlag);
463 m_canvas->setMatrix(matrix);
466 bool GraphicsContext::concat(const SkMatrix& matrix)
468 if (paintingDisabled())
471 if (matrix.isIdentity())
474 realizeSave(SkCanvas::kMatrix_SaveFlag);
476 return m_canvas->concat(matrix);
479 void GraphicsContext::beginTransparencyLayer(float opacity, const FloatRect* bounds)
481 beginLayer(opacity, m_state->m_compositeOperator, bounds);
484 void GraphicsContext::beginLayer(float opacity, CompositeOperator op, const FloatRect* bounds, ColorFilter colorFilter, ImageFilter* imageFilter)
486 if (paintingDisabled())
489 // We need the "alpha" layer flag here because the base layer is opaque
490 // (the surface of the page) but layers on top may have transparent parts.
491 // Without explicitly setting the alpha flag, the layer will inherit the
492 // opaque setting of the base and some things won't work properly.
493 SkCanvas::SaveFlags saveFlags = static_cast<SkCanvas::SaveFlags>(SkCanvas::kHasAlphaLayer_SaveFlag | SkCanvas::kFullColorLayer_SaveFlag);
496 layerPaint.setAlpha(static_cast<unsigned char>(opacity * 255));
497 layerPaint.setXfermode(WebCoreCompositeToSkiaComposite(op, m_state->m_blendMode).get());
498 layerPaint.setColorFilter(WebCoreColorFilterToSkiaColorFilter(colorFilter).get());
499 layerPaint.setImageFilter(imageFilter);
502 SkRect skBounds = WebCoreFloatRectToSKRect(*bounds);
503 saveLayer(&skBounds, &layerPaint, saveFlags);
505 saveLayer(0, &layerPaint, saveFlags);
513 void GraphicsContext::endLayer()
515 if (paintingDisabled())
520 ASSERT(m_layerCount > 0);
526 void GraphicsContext::beginRecording(const FloatRect& bounds)
528 RefPtr<DisplayList> displayList = adoptRef(new DisplayList(bounds));
530 SkCanvas* savedCanvas = m_canvas;
531 SkMatrix savedMatrix = getTotalMatrix();
533 IntRect recordingRect = enclosingIntRect(bounds);
534 m_canvas = displayList->picture()->beginRecording(recordingRect.width(), recordingRect.height(),
535 SkPicture::kUsePathBoundsForClip_RecordingFlag);
537 // We want the bounds offset mapped to (0, 0), such that the display list content
538 // is fully contained within the SkPictureRecord's bounds.
539 if (!toFloatSize(bounds.location()).isZero()) {
540 m_canvas->translate(-bounds.x(), -bounds.y());
541 // To avoid applying the offset repeatedly in getTotalMatrix(), we pre-apply it here.
542 savedMatrix.preTranslate(bounds.x(), bounds.y());
545 m_recordingStateStack.append(RecordingState(savedCanvas, savedMatrix, displayList));
548 PassRefPtr<DisplayList> GraphicsContext::endRecording()
550 ASSERT(!m_recordingStateStack.isEmpty());
552 RecordingState recording = m_recordingStateStack.last();
553 ASSERT(recording.m_displayList->picture()->getRecordingCanvas());
554 recording.m_displayList->picture()->endRecording();
556 m_recordingStateStack.removeLast();
557 m_canvas = recording.m_savedCanvas;
559 return recording.m_displayList.release();
562 bool GraphicsContext::isRecording() const
564 return !m_recordingStateStack.isEmpty();
567 void GraphicsContext::drawDisplayList(DisplayList* displayList)
570 ASSERT(!displayList->picture()->getRecordingCanvas());
572 if (paintingDisabled() || displayList->bounds().isEmpty())
575 realizeSave(SkCanvas::kMatrixClip_SaveFlag);
577 const FloatRect& bounds = displayList->bounds();
578 if (bounds.x() || bounds.y())
579 m_canvas->translate(bounds.x(), bounds.y());
581 m_canvas->drawPicture(*displayList->picture());
583 if (bounds.x() || bounds.y())
584 m_canvas->translate(-bounds.x(), -bounds.y());
587 void GraphicsContext::setupPaintForFilling(SkPaint* paint) const
589 if (paintingDisabled())
592 setupPaintCommon(paint);
594 setupShader(paint, m_state->m_fillGradient.get(), m_state->m_fillPattern.get(), m_state->m_fillColor.rgb());
597 float GraphicsContext::setupPaintForStroking(SkPaint* paint, int length) const
599 if (paintingDisabled())
602 setupPaintCommon(paint);
604 setupShader(paint, m_state->m_strokeData.gradient(), m_state->m_strokeData.pattern(),
605 m_state->m_strokeData.color().rgb());
607 return m_state->m_strokeData.setupPaint(paint, length);
610 void GraphicsContext::drawConvexPolygon(size_t numPoints, const FloatPoint* points, bool shouldAntialias)
612 if (paintingDisabled())
619 setPathFromConvexPoints(&path, numPoints, points);
622 setupPaintForFilling(&paint);
623 paint.setAntiAlias(shouldAntialias);
624 drawPath(path, paint);
626 if (strokeStyle() != NoStroke) {
628 setupPaintForStroking(&paint);
629 drawPath(path, paint);
633 // This method is only used to draw the little circles used in lists.
634 void GraphicsContext::drawEllipse(const IntRect& elipseRect)
636 if (paintingDisabled())
639 SkRect rect = elipseRect;
641 setupPaintForFilling(&paint);
642 drawOval(rect, paint);
644 if (strokeStyle() != NoStroke) {
646 setupPaintForStroking(&paint);
647 drawOval(rect, paint);
651 void GraphicsContext::drawFocusRing(const Path& focusRingPath, int width, int offset, const Color& color)
653 // FIXME: Implement support for offset.
654 if (paintingDisabled())
658 paint.setAntiAlias(true);
659 paint.setStyle(SkPaint::kStroke_Style);
660 paint.setColor(color.rgb());
662 drawOuterPath(focusRingPath.skPath(), paint, width);
663 drawInnerPath(focusRingPath.skPath(), paint, width);
666 void GraphicsContext::drawFocusRing(const Vector<IntRect>& rects, int width, int offset, const Color& color)
668 if (paintingDisabled())
671 unsigned rectCount = rects.size();
675 SkRegion focusRingRegion;
676 const int focusRingOutset = getFocusRingOutset(offset);
677 for (unsigned i = 0; i < rectCount; i++) {
678 SkIRect r = rects[i];
679 r.inset(-focusRingOutset, -focusRingOutset);
680 focusRingRegion.op(r, SkRegion::kUnion_Op);
685 paint.setAntiAlias(true);
686 paint.setStyle(SkPaint::kStroke_Style);
688 paint.setColor(color.rgb());
689 focusRingRegion.getBoundaryPath(&path);
690 drawOuterPath(path, paint, width);
691 drawInnerPath(path, paint, width);
694 static inline IntRect areaCastingShadowInHole(const IntRect& holeRect, int shadowBlur, int shadowSpread, const IntSize& shadowOffset)
696 IntRect bounds(holeRect);
698 bounds.inflate(shadowBlur);
700 if (shadowSpread < 0)
701 bounds.inflate(-shadowSpread);
703 IntRect offsetBounds = bounds;
704 offsetBounds.move(-shadowOffset);
705 return unionRect(bounds, offsetBounds);
708 void GraphicsContext::drawInnerShadow(const RoundedRect& rect, const Color& shadowColor, const IntSize shadowOffset, int shadowBlur, int shadowSpread, Edges clippedEdges)
710 IntRect holeRect(rect.rect());
711 holeRect.inflate(-shadowSpread);
713 if (holeRect.isEmpty()) {
714 if (rect.isRounded())
715 fillRoundedRect(rect, shadowColor);
717 fillRect(rect.rect(), shadowColor);
721 if (clippedEdges & LeftEdge) {
722 holeRect.move(-max(shadowOffset.width(), 0) - shadowBlur, 0);
723 holeRect.setWidth(holeRect.width() + max(shadowOffset.width(), 0) + shadowBlur);
725 if (clippedEdges & TopEdge) {
726 holeRect.move(0, -max(shadowOffset.height(), 0) - shadowBlur);
727 holeRect.setHeight(holeRect.height() + max(shadowOffset.height(), 0) + shadowBlur);
729 if (clippedEdges & RightEdge)
730 holeRect.setWidth(holeRect.width() - min(shadowOffset.width(), 0) + shadowBlur);
731 if (clippedEdges & BottomEdge)
732 holeRect.setHeight(holeRect.height() - min(shadowOffset.height(), 0) + shadowBlur);
734 Color fillColor(shadowColor.red(), shadowColor.green(), shadowColor.blue(), 255);
736 IntRect outerRect = areaCastingShadowInHole(rect.rect(), shadowBlur, shadowSpread, shadowOffset);
737 RoundedRect roundedHole(holeRect, rect.radii());
740 if (rect.isRounded()) {
742 path.addRoundedRect(rect);
744 roundedHole.shrinkRadii(shadowSpread);
749 DrawLooper drawLooper;
750 drawLooper.addShadow(shadowOffset, shadowBlur, shadowColor,
751 DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
752 setDrawLooper(drawLooper);
753 fillRectWithRoundedHole(outerRect, roundedHole, fillColor);
758 // This is only used to draw borders.
759 void GraphicsContext::drawLine(const IntPoint& point1, const IntPoint& point2)
761 if (paintingDisabled())
764 StrokeStyle penStyle = strokeStyle();
765 if (penStyle == NoStroke)
769 FloatPoint p1 = point1;
770 FloatPoint p2 = point2;
771 bool isVerticalLine = (p1.x() == p2.x());
772 int width = roundf(strokeThickness());
774 // We know these are vertical or horizontal lines, so the length will just
775 // be the sum of the displacement component vectors give or take 1 -
776 // probably worth the speed up of no square root, which also won't be exact.
777 FloatSize disp = p2 - p1;
778 int length = SkScalarRoundToInt(disp.width() + disp.height());
779 setupPaintForStroking(&paint, length);
781 if (strokeStyle() == DottedStroke || strokeStyle() == DashedStroke) {
782 // Do a rect fill of our endpoints. This ensures we always have the
783 // appearance of being a border. We then draw the actual dotted/dashed line.
786 r1.set(p1.x(), p1.y(), p1.x() + width, p1.y() + width);
787 r2.set(p2.x(), p2.y(), p2.x() + width, p2.y() + width);
789 if (isVerticalLine) {
790 r1.offset(-width / 2, 0);
791 r2.offset(-width / 2, -width);
793 r1.offset(0, -width / 2);
794 r2.offset(-width, -width / 2);
797 fillPaint.setColor(paint.getColor());
798 drawRect(r1, fillPaint);
799 drawRect(r2, fillPaint);
802 adjustLineToPixelBoundaries(p1, p2, width, penStyle);
803 SkPoint pts[2] = { (SkPoint)p1, (SkPoint)p2 };
805 m_canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, paint);
807 if (m_trackOpaqueRegion)
808 m_opaqueRegion.didDrawPoints(this, SkCanvas::kLines_PointMode, 2, pts, paint);
811 void GraphicsContext::drawLineForDocumentMarker(const FloatPoint& pt, float width, DocumentMarkerLineStyle style)
813 if (paintingDisabled())
816 int deviceScaleFactor = m_useHighResMarker ? 2 : 1;
818 // Create the pattern we'll use to draw the underline.
819 int index = style == DocumentMarkerGrammarLineStyle ? 1 : 0;
820 static SkBitmap* misspellBitmap1x[2] = { 0, 0 };
821 static SkBitmap* misspellBitmap2x[2] = { 0, 0 };
822 SkBitmap** misspellBitmap = deviceScaleFactor == 2 ? misspellBitmap2x : misspellBitmap1x;
823 if (!misspellBitmap[index]) {
825 // Match the artwork used by the Mac.
826 const int rowPixels = 4 * deviceScaleFactor;
827 const int colPixels = 3 * deviceScaleFactor;
828 misspellBitmap[index] = new SkBitmap;
829 misspellBitmap[index]->setConfig(SkBitmap::kARGB_8888_Config,
830 rowPixels, colPixels);
831 misspellBitmap[index]->allocPixels();
833 misspellBitmap[index]->eraseARGB(0, 0, 0, 0);
834 const uint32_t transparentColor = 0x00000000;
836 if (deviceScaleFactor == 1) {
837 const uint32_t colors[2][6] = {
838 { 0x2a2a0600, 0x57571000, 0xa8a81b00, 0xbfbf1f00, 0x70701200, 0xe0e02400 },
839 { 0x2a0f0f0f, 0x571e1e1e, 0xa83d3d3d, 0xbf454545, 0x70282828, 0xe0515151 }
842 // Pattern: a b a a b a
845 for (int x = 0; x < colPixels; ++x) {
846 uint32_t* row = misspellBitmap[index]->getAddr32(0, x);
847 row[0] = colors[index][x * 2];
848 row[1] = colors[index][x * 2 + 1];
849 row[2] = colors[index][x * 2];
850 row[3] = transparentColor;
852 } else if (deviceScaleFactor == 2) {
853 const uint32_t colors[2][18] = {
854 { 0x0a090101, 0x33320806, 0x55540f0a, 0x37360906, 0x6e6c120c, 0x6e6c120c, 0x7674140d, 0x8d8b1810, 0x8d8b1810,
855 0x96941a11, 0xb3b01f15, 0xb3b01f15, 0x6d6b130c, 0xd9d62619, 0xd9d62619, 0x19180402, 0x7c7a150e, 0xcecb2418 },
856 { 0x0a020202, 0x33141414, 0x55232323, 0x37161616, 0x6e2e2e2e, 0x6e2e2e2e, 0x76313131, 0x8d3a3a3a, 0x8d3a3a3a,
857 0x963e3e3e, 0xb34b4b4b, 0xb34b4b4b, 0x6d2d2d2d, 0xd95b5b5b, 0xd95b5b5b, 0x19090909, 0x7c343434, 0xce575757 }
860 // Pattern: a b c c b a
866 for (int x = 0; x < colPixels; ++x) {
867 uint32_t* row = misspellBitmap[index]->getAddr32(0, x);
868 row[0] = colors[index][x * 3];
869 row[1] = colors[index][x * 3 + 1];
870 row[2] = colors[index][x * 3 + 2];
871 row[3] = colors[index][x * 3 + 2];
872 row[4] = colors[index][x * 3 + 1];
873 row[5] = colors[index][x * 3];
874 row[6] = transparentColor;
875 row[7] = transparentColor;
878 ASSERT_NOT_REACHED();
880 // We use a 2-pixel-high misspelling indicator because that seems to be
881 // what WebKit is designed for, and how much room there is in a typical
883 const int rowPixels = 32 * deviceScaleFactor; // Must be multiple of 4 for pattern below.
884 const int colPixels = 2 * deviceScaleFactor;
885 misspellBitmap[index] = new SkBitmap;
886 misspellBitmap[index]->setConfig(SkBitmap::kARGB_8888_Config, rowPixels, colPixels);
887 misspellBitmap[index]->allocPixels();
889 misspellBitmap[index]->eraseARGB(0, 0, 0, 0);
890 if (deviceScaleFactor == 1)
891 draw1xMarker(misspellBitmap[index], index);
892 else if (deviceScaleFactor == 2)
893 draw2xMarker(misspellBitmap[index], index);
895 ASSERT_NOT_REACHED();
900 SkScalar originX = WebCoreFloatToSkScalar(pt.x()) * deviceScaleFactor;
901 SkScalar originY = WebCoreFloatToSkScalar(pt.y()) * deviceScaleFactor;
903 // Make sure to draw only complete dots.
904 int rowPixels = misspellBitmap[index]->width();
905 float widthMod = fmodf(width * deviceScaleFactor, rowPixels);
906 if (rowPixels - widthMod > deviceScaleFactor)
907 width -= widthMod / deviceScaleFactor;
909 SkScalar originX = WebCoreFloatToSkScalar(pt.x());
911 // Offset it vertically by 1 so that there's some space under the text.
912 SkScalar originY = WebCoreFloatToSkScalar(pt.y()) + 1;
913 originX *= deviceScaleFactor;
914 originY *= deviceScaleFactor;
917 RefPtr<SkShader> shader = adoptRef(SkShader::CreateBitmapShader(
918 *misspellBitmap[index], SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode));
920 matrix.setTranslate(originX, originY);
921 shader->setLocalMatrix(matrix);
924 paint.setShader(shader.get());
927 rect.set(originX, originY, originX + WebCoreFloatToSkScalar(width) * deviceScaleFactor, originY + SkIntToScalar(misspellBitmap[index]->height()));
929 if (deviceScaleFactor == 2) {
931 scale(FloatSize(0.5, 0.5));
933 drawRect(rect, paint);
934 if (deviceScaleFactor == 2)
938 void GraphicsContext::drawLineForText(const FloatPoint& pt, float width, bool printing)
940 if (paintingDisabled())
946 int thickness = SkMax32(static_cast<int>(strokeThickness()), 1);
948 r.fLeft = WebCoreFloatToSkScalar(pt.x());
949 // Avoid anti-aliasing lines. Currently, these are always horizontal.
950 // Round to nearest pixel to match text and other content.
951 r.fTop = WebCoreFloatToSkScalar(floorf(pt.y() + 0.5f));
952 r.fRight = r.fLeft + WebCoreFloatToSkScalar(width);
953 r.fBottom = r.fTop + SkIntToScalar(thickness);
956 switch (strokeStyle()) {
961 setupPaintForFilling(&paint);
965 setupPaintForStroking(&paint);
969 // Text lines are drawn using the stroke color.
970 paint.setColor(effectiveStrokeColor());
974 // Draws a filled rectangle with a stroked border.
975 void GraphicsContext::drawRect(const IntRect& rect)
977 if (paintingDisabled())
980 ASSERT(!rect.isEmpty());
984 SkRect skRect = rect;
986 int fillcolorNotTransparent = m_state->m_fillColor.rgb() & 0xFF000000;
987 if (fillcolorNotTransparent) {
988 setupPaintForFilling(&paint);
989 drawRect(skRect, paint);
992 if (m_state->m_strokeData.style() != NoStroke && (m_state->m_strokeData.color().rgb() & 0xFF000000)) {
993 // We do a fill of four rects to simulate the stroke of a border.
995 setupPaintForFilling(&paint);
996 // need to jam in the strokeColor
997 paint.setColor(this->effectiveStrokeColor());
999 SkRect topBorder = { skRect.fLeft, skRect.fTop, skRect.fRight, skRect.fTop + 1 };
1000 drawRect(topBorder, paint);
1001 SkRect bottomBorder = { skRect.fLeft, skRect.fBottom - 1, skRect.fRight, skRect.fBottom };
1002 drawRect(bottomBorder, paint);
1003 SkRect leftBorder = { skRect.fLeft, skRect.fTop + 1, skRect.fLeft + 1, skRect.fBottom - 1 };
1004 drawRect(leftBorder, paint);
1005 SkRect rightBorder = { skRect.fRight - 1, skRect.fTop + 1, skRect.fRight, skRect.fBottom - 1 };
1006 drawRect(rightBorder, paint);
1010 void GraphicsContext::drawText(const Font& font, const TextRunPaintInfo& runInfo, const FloatPoint& point)
1012 if (paintingDisabled())
1015 font.drawText(this, runInfo, point);
1018 void GraphicsContext::drawEmphasisMarks(const Font& font, const TextRunPaintInfo& runInfo, const AtomicString& mark, const FloatPoint& point)
1020 if (paintingDisabled())
1023 font.drawEmphasisMarks(this, runInfo, mark, point);
1026 void GraphicsContext::drawBidiText(const Font& font, const TextRunPaintInfo& runInfo, const FloatPoint& point, Font::CustomFontNotReadyAction customFontNotReadyAction)
1028 if (paintingDisabled())
1031 // sub-run painting is not supported for Bidi text.
1032 const TextRun& run = runInfo.run;
1033 ASSERT((runInfo.from == 0) && (runInfo.to == run.length()));
1034 BidiResolver<TextRunIterator, BidiCharacterRun> bidiResolver;
1035 bidiResolver.setStatus(BidiStatus(run.direction(), run.directionalOverride()));
1036 bidiResolver.setPositionIgnoringNestedIsolates(TextRunIterator(&run, 0));
1038 // FIXME: This ownership should be reversed. We should pass BidiRunList
1039 // to BidiResolver in createBidiRunsForLine.
1040 BidiRunList<BidiCharacterRun>& bidiRuns = bidiResolver.runs();
1041 bidiResolver.createBidiRunsForLine(TextRunIterator(&run, run.length()));
1042 if (!bidiRuns.runCount())
1045 FloatPoint currPoint = point;
1046 BidiCharacterRun* bidiRun = bidiRuns.firstRun();
1048 TextRun subrun = run.subRun(bidiRun->start(), bidiRun->stop() - bidiRun->start());
1049 bool isRTL = bidiRun->level() % 2;
1050 subrun.setDirection(isRTL ? RTL : LTR);
1051 subrun.setDirectionalOverride(bidiRun->dirOverride(false));
1053 TextRunPaintInfo subrunInfo(subrun);
1054 subrunInfo.bounds = runInfo.bounds;
1055 font.drawText(this, subrunInfo, currPoint, customFontNotReadyAction);
1057 bidiRun = bidiRun->next();
1058 // FIXME: Have Font::drawText return the width of what it drew so that we don't have to re-measure here.
1060 currPoint.move(font.width(subrun), 0);
1063 bidiRuns.deleteRuns();
1066 void GraphicsContext::drawHighlightForText(const Font& font, const TextRun& run, const FloatPoint& point, int h, const Color& backgroundColor, int from, int to)
1068 if (paintingDisabled())
1071 fillRect(font.selectionRectForText(run, point, h, from, to), backgroundColor);
1074 void GraphicsContext::drawImage(Image* image, const IntPoint& p, CompositeOperator op, RespectImageOrientationEnum shouldRespectImageOrientation)
1078 drawImage(image, FloatRect(IntRect(p, image->size())), FloatRect(FloatPoint(), FloatSize(image->size())), op, shouldRespectImageOrientation);
1081 void GraphicsContext::drawImage(Image* image, const IntRect& r, CompositeOperator op, RespectImageOrientationEnum shouldRespectImageOrientation, bool useLowQualityScale)
1085 drawImage(image, FloatRect(r), FloatRect(FloatPoint(), FloatSize(image->size())), op, shouldRespectImageOrientation, useLowQualityScale);
1088 void GraphicsContext::drawImage(Image* image, const IntPoint& dest, const IntRect& srcRect, CompositeOperator op, RespectImageOrientationEnum shouldRespectImageOrientation)
1090 drawImage(image, FloatRect(IntRect(dest, srcRect.size())), FloatRect(srcRect), op, shouldRespectImageOrientation);
1093 void GraphicsContext::drawImage(Image* image, const FloatRect& dest, const FloatRect& src, CompositeOperator op, RespectImageOrientationEnum shouldRespectImageOrientation, bool useLowQualityScale)
1095 drawImage(image, dest, src, op, blink::WebBlendModeNormal, shouldRespectImageOrientation, useLowQualityScale);
1098 void GraphicsContext::drawImage(Image* image, const FloatRect& dest)
1102 drawImage(image, dest, FloatRect(IntRect(IntPoint(), image->size())));
1105 void GraphicsContext::drawImage(Image* image, const FloatRect& dest, const FloatRect& src, CompositeOperator op, WebBlendMode blendMode, RespectImageOrientationEnum shouldRespectImageOrientation, bool useLowQualityScale)
1106 { if (paintingDisabled() || !image)
1109 InterpolationQuality previousInterpolationQuality = InterpolationDefault;
1111 if (useLowQualityScale) {
1112 previousInterpolationQuality = imageInterpolationQuality();
1113 setImageInterpolationQuality(InterpolationLow);
1116 image->draw(this, dest, src, op, blendMode, shouldRespectImageOrientation);
1118 if (useLowQualityScale)
1119 setImageInterpolationQuality(previousInterpolationQuality);
1122 void GraphicsContext::drawTiledImage(Image* image, const IntRect& destRect, const IntPoint& srcPoint, const IntSize& tileSize, CompositeOperator op, bool useLowQualityScale, WebBlendMode blendMode, const IntSize& repeatSpacing)
1124 if (paintingDisabled() || !image)
1127 if (useLowQualityScale) {
1128 InterpolationQuality previousInterpolationQuality = imageInterpolationQuality();
1129 setImageInterpolationQuality(InterpolationLow);
1130 image->drawTiled(this, destRect, srcPoint, tileSize, op, blendMode, repeatSpacing);
1131 setImageInterpolationQuality(previousInterpolationQuality);
1133 image->drawTiled(this, destRect, srcPoint, tileSize, op, blendMode, repeatSpacing);
1137 void GraphicsContext::drawTiledImage(Image* image, const IntRect& dest, const IntRect& srcRect,
1138 const FloatSize& tileScaleFactor, Image::TileRule hRule, Image::TileRule vRule, CompositeOperator op, bool useLowQualityScale)
1140 if (paintingDisabled() || !image)
1143 if (hRule == Image::StretchTile && vRule == Image::StretchTile) {
1145 drawImage(image, dest, srcRect, op);
1149 if (useLowQualityScale) {
1150 InterpolationQuality previousInterpolationQuality = imageInterpolationQuality();
1151 setImageInterpolationQuality(InterpolationLow);
1152 image->drawTiled(this, dest, srcRect, tileScaleFactor, hRule, vRule, op);
1153 setImageInterpolationQuality(previousInterpolationQuality);
1155 image->drawTiled(this, dest, srcRect, tileScaleFactor, hRule, vRule, op);
1159 void GraphicsContext::drawImageBuffer(ImageBuffer* image, const IntPoint& p, CompositeOperator op, WebBlendMode blendMode)
1163 drawImageBuffer(image, FloatRect(IntRect(p, image->size())), FloatRect(FloatPoint(), FloatSize(image->size())), op, blendMode);
1166 void GraphicsContext::drawImageBuffer(ImageBuffer* image, const IntRect& r, CompositeOperator op, WebBlendMode blendMode, bool useLowQualityScale)
1170 drawImageBuffer(image, FloatRect(r), FloatRect(FloatPoint(), FloatSize(image->size())), op, blendMode, useLowQualityScale);
1173 void GraphicsContext::drawImageBuffer(ImageBuffer* image, const IntPoint& dest, const IntRect& srcRect, CompositeOperator op, WebBlendMode blendMode)
1175 drawImageBuffer(image, FloatRect(IntRect(dest, srcRect.size())), FloatRect(srcRect), op, blendMode);
1178 void GraphicsContext::drawImageBuffer(ImageBuffer* image, const IntRect& dest, const IntRect& srcRect, CompositeOperator op, WebBlendMode blendMode, bool useLowQualityScale)
1180 drawImageBuffer(image, FloatRect(dest), FloatRect(srcRect), op, blendMode, useLowQualityScale);
1183 void GraphicsContext::drawImageBuffer(ImageBuffer* image, const FloatRect& dest)
1187 drawImageBuffer(image, dest, FloatRect(IntRect(IntPoint(), image->size())));
1190 void GraphicsContext::drawImageBuffer(ImageBuffer* image, const FloatRect& dest, const FloatRect& src, CompositeOperator op, WebBlendMode blendMode, bool useLowQualityScale)
1192 if (paintingDisabled() || !image)
1195 if (useLowQualityScale) {
1196 InterpolationQuality previousInterpolationQuality = imageInterpolationQuality();
1197 setImageInterpolationQuality(InterpolationLow);
1198 image->draw(this, dest, src, op, blendMode, useLowQualityScale);
1199 setImageInterpolationQuality(previousInterpolationQuality);
1201 image->draw(this, dest, src, op, blendMode, useLowQualityScale);
1205 void GraphicsContext::writePixels(const SkBitmap& bitmap, int x, int y, SkCanvas::Config8888 config8888)
1207 if (paintingDisabled())
1210 m_canvas->writePixels(bitmap, x, y, config8888);
1212 if (m_trackOpaqueRegion) {
1213 SkRect rect = SkRect::MakeXYWH(x, y, bitmap.width(), bitmap.height());
1216 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
1217 m_opaqueRegion.didDrawRect(this, rect, paint, &bitmap);
1221 void GraphicsContext::drawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top, const SkPaint* paint)
1223 if (paintingDisabled())
1226 m_canvas->drawBitmap(bitmap, left, top, paint);
1228 if (m_trackOpaqueRegion) {
1229 SkRect rect = SkRect::MakeXYWH(left, top, bitmap.width(), bitmap.height());
1230 m_opaqueRegion.didDrawRect(this, rect, *paint, &bitmap);
1234 void GraphicsContext::drawBitmapRect(const SkBitmap& bitmap, const SkRect* src,
1235 const SkRect& dst, const SkPaint* paint)
1237 if (paintingDisabled())
1240 SkCanvas::DrawBitmapRectFlags flags = m_state->m_shouldClampToSourceRect ? SkCanvas::kNone_DrawBitmapRectFlag : SkCanvas::kBleed_DrawBitmapRectFlag;
1242 m_canvas->drawBitmapRectToRect(bitmap, src, dst, paint, flags);
1244 if (m_trackOpaqueRegion)
1245 m_opaqueRegion.didDrawRect(this, dst, *paint, &bitmap);
1248 void GraphicsContext::drawOval(const SkRect& oval, const SkPaint& paint)
1250 if (paintingDisabled())
1253 m_canvas->drawOval(oval, paint);
1255 if (m_trackOpaqueRegion)
1256 m_opaqueRegion.didDrawBounded(this, oval, paint);
1259 void GraphicsContext::drawPath(const SkPath& path, const SkPaint& paint)
1261 if (paintingDisabled())
1264 m_canvas->drawPath(path, paint);
1266 if (m_trackOpaqueRegion)
1267 m_opaqueRegion.didDrawPath(this, path, paint);
1270 void GraphicsContext::drawRect(const SkRect& rect, const SkPaint& paint)
1272 if (paintingDisabled())
1275 m_canvas->drawRect(rect, paint);
1277 if (m_trackOpaqueRegion)
1278 m_opaqueRegion.didDrawRect(this, rect, paint, 0);
1281 void GraphicsContext::didDrawRect(const SkRect& rect, const SkPaint& paint, const SkBitmap* bitmap)
1283 if (m_trackOpaqueRegion)
1284 m_opaqueRegion.didDrawRect(this, rect, paint, bitmap);
1287 void GraphicsContext::drawPosText(const void* text, size_t byteLength,
1288 const SkPoint pos[], const SkRect& textRect, const SkPaint& paint)
1290 if (paintingDisabled())
1293 m_canvas->drawPosText(text, byteLength, pos, paint);
1294 didDrawTextInRect(textRect);
1296 // FIXME: compute bounds for positioned text.
1297 if (m_trackOpaqueRegion)
1298 m_opaqueRegion.didDrawUnbounded(this, paint, OpaqueRegionSkia::FillOrStroke);
1301 void GraphicsContext::drawPosTextH(const void* text, size_t byteLength,
1302 const SkScalar xpos[], SkScalar constY, const SkRect& textRect, const SkPaint& paint)
1304 if (paintingDisabled())
1307 m_canvas->drawPosTextH(text, byteLength, xpos, constY, paint);
1308 didDrawTextInRect(textRect);
1310 // FIXME: compute bounds for positioned text.
1311 if (m_trackOpaqueRegion)
1312 m_opaqueRegion.didDrawUnbounded(this, paint, OpaqueRegionSkia::FillOrStroke);
1315 void GraphicsContext::drawTextOnPath(const void* text, size_t byteLength,
1316 const SkPath& path, const SkRect& textRect, const SkMatrix* matrix, const SkPaint& paint)
1318 if (paintingDisabled())
1321 m_canvas->drawTextOnPath(text, byteLength, path, matrix, paint);
1322 didDrawTextInRect(textRect);
1324 // FIXME: compute bounds for positioned text.
1325 if (m_trackOpaqueRegion)
1326 m_opaqueRegion.didDrawUnbounded(this, paint, OpaqueRegionSkia::FillOrStroke);
1329 void GraphicsContext::fillPath(const Path& pathToFill)
1331 if (paintingDisabled() || pathToFill.isEmpty())
1334 // Use const_cast and temporarily modify the fill type instead of copying the path.
1335 SkPath& path = const_cast<SkPath&>(pathToFill.skPath());
1336 SkPath::FillType previousFillType = path.getFillType();
1338 SkPath::FillType temporaryFillType = m_state->m_fillRule == RULE_EVENODD ? SkPath::kEvenOdd_FillType : SkPath::kWinding_FillType;
1339 path.setFillType(temporaryFillType);
1342 setupPaintForFilling(&paint);
1343 drawPath(path, paint);
1345 path.setFillType(previousFillType);
1348 void GraphicsContext::fillRect(const FloatRect& rect)
1350 if (paintingDisabled())
1356 setupPaintForFilling(&paint);
1360 void GraphicsContext::fillRect(const FloatRect& rect, const Color& color)
1362 if (paintingDisabled())
1367 setupPaintCommon(&paint);
1368 paint.setColor(color.rgb());
1372 void GraphicsContext::fillRoundedRect(const IntRect& rect, const IntSize& topLeft, const IntSize& topRight,
1373 const IntSize& bottomLeft, const IntSize& bottomRight, const Color& color)
1375 if (paintingDisabled())
1378 if (topLeft.width() + topRight.width() > rect.width()
1379 || bottomLeft.width() + bottomRight.width() > rect.width()
1380 || topLeft.height() + bottomLeft.height() > rect.height()
1381 || topRight.height() + bottomRight.height() > rect.height()) {
1382 // Not all the radii fit, return a rect. This matches the behavior of
1383 // Path::createRoundedRectangle. Without this we attempt to draw a round
1384 // shadow for a square box.
1385 fillRect(rect, color);
1390 setRadii(radii, topLeft, topRight, bottomRight, bottomLeft);
1393 rr.setRectRadii(rect, radii);
1396 setupPaintForFilling(&paint);
1397 paint.setColor(color.rgb());
1399 m_canvas->drawRRect(rr, paint);
1401 if (m_trackOpaqueRegion)
1402 m_opaqueRegion.didDrawBounded(this, rr.getBounds(), paint);
1405 void GraphicsContext::fillEllipse(const FloatRect& ellipse)
1407 if (paintingDisabled())
1410 SkRect rect = ellipse;
1412 setupPaintForFilling(&paint);
1413 drawOval(rect, paint);
1416 void GraphicsContext::strokePath(const Path& pathToStroke)
1418 if (paintingDisabled() || pathToStroke.isEmpty())
1421 const SkPath& path = pathToStroke.skPath();
1423 setupPaintForStroking(&paint);
1424 drawPath(path, paint);
1427 void GraphicsContext::strokeRect(const FloatRect& rect, float lineWidth)
1429 if (paintingDisabled())
1433 setupPaintForStroking(&paint);
1434 paint.setStrokeWidth(WebCoreFloatToSkScalar(lineWidth));
1435 // strokerect has special rules for CSS when the rect is degenerate:
1436 // if width==0 && height==0, do nothing
1437 // if width==0 || height==0, then just draw line for the other dimension
1439 bool validW = r.width() > 0;
1440 bool validH = r.height() > 0;
1441 if (validW && validH) {
1443 } else if (validW || validH) {
1444 // we are expected to respect the lineJoin, so we can't just call
1445 // drawLine -- we have to create a path that doubles back on itself.
1447 path.moveTo(r.fLeft, r.fTop);
1448 path.lineTo(r.fRight, r.fBottom);
1450 drawPath(path, paint);
1454 void GraphicsContext::strokeEllipse(const FloatRect& ellipse)
1456 if (paintingDisabled())
1459 SkRect rect(ellipse);
1461 setupPaintForStroking(&paint);
1462 drawOval(rect, paint);
1465 void GraphicsContext::clipRoundedRect(const RoundedRect& rect)
1467 if (paintingDisabled())
1471 RoundedRect::Radii wkRadii = rect.radii();
1472 setRadii(radii, wkRadii.topLeft(), wkRadii.topRight(), wkRadii.bottomRight(), wkRadii.bottomLeft());
1475 r.setRectRadii(rect.rect(), radii);
1477 clipRRect(r, AntiAliased);
1480 void GraphicsContext::clipOut(const Path& pathToClip)
1482 if (paintingDisabled())
1485 // Use const_cast and temporarily toggle the inverse fill type instead of copying the path.
1486 SkPath& path = const_cast<SkPath&>(pathToClip.skPath());
1487 path.toggleInverseFillType();
1488 clipPath(path, AntiAliased);
1489 path.toggleInverseFillType();
1492 void GraphicsContext::clipPath(const Path& pathToClip, WindRule clipRule)
1494 if (paintingDisabled() || pathToClip.isEmpty())
1497 // Use const_cast and temporarily modify the fill type instead of copying the path.
1498 SkPath& path = const_cast<SkPath&>(pathToClip.skPath());
1499 SkPath::FillType previousFillType = path.getFillType();
1501 SkPath::FillType temporaryFillType = clipRule == RULE_EVENODD ? SkPath::kEvenOdd_FillType : SkPath::kWinding_FillType;
1502 path.setFillType(temporaryFillType);
1503 clipPath(path, AntiAliased);
1505 path.setFillType(previousFillType);
1508 void GraphicsContext::clipConvexPolygon(size_t numPoints, const FloatPoint* points, bool antialiased)
1510 if (paintingDisabled())
1517 setPathFromConvexPoints(&path, numPoints, points);
1518 clipPath(path, antialiased ? AntiAliased : NotAntiAliased);
1521 void GraphicsContext::clipOutRoundedRect(const RoundedRect& rect)
1523 if (paintingDisabled())
1526 if (!rect.isRounded()) {
1527 clipOut(rect.rect());
1532 path.addRoundedRect(rect);
1536 void GraphicsContext::canvasClip(const Path& pathToClip, WindRule clipRule)
1538 if (paintingDisabled())
1541 // Use const_cast and temporarily modify the fill type instead of copying the path.
1542 SkPath& path = const_cast<SkPath&>(pathToClip.skPath());
1543 SkPath::FillType previousFillType = path.getFillType();
1545 SkPath::FillType temporaryFillType = clipRule == RULE_EVENODD ? SkPath::kEvenOdd_FillType : SkPath::kWinding_FillType;
1546 path.setFillType(temporaryFillType);
1549 path.setFillType(previousFillType);
1552 bool GraphicsContext::clipRect(const SkRect& rect, AntiAliasingMode aa, SkRegion::Op op)
1554 if (paintingDisabled())
1557 realizeSave(SkCanvas::kClip_SaveFlag);
1559 return m_canvas->clipRect(rect, op, aa == AntiAliased);
1562 bool GraphicsContext::clipPath(const SkPath& path, AntiAliasingMode aa, SkRegion::Op op)
1564 if (paintingDisabled())
1567 realizeSave(SkCanvas::kClip_SaveFlag);
1569 return m_canvas->clipPath(path, op, aa == AntiAliased);
1572 bool GraphicsContext::clipRRect(const SkRRect& rect, AntiAliasingMode aa, SkRegion::Op op)
1574 if (paintingDisabled())
1577 realizeSave(SkCanvas::kClip_SaveFlag);
1579 return m_canvas->clipRRect(rect, op, aa == AntiAliased);
1582 void GraphicsContext::rotate(float angleInRadians)
1584 if (paintingDisabled())
1587 realizeSave(SkCanvas::kMatrix_SaveFlag);
1589 m_canvas->rotate(WebCoreFloatToSkScalar(angleInRadians * (180.0f / 3.14159265f)));
1592 void GraphicsContext::translate(float w, float h)
1594 if (paintingDisabled())
1600 realizeSave(SkCanvas::kMatrix_SaveFlag);
1602 m_canvas->translate(WebCoreFloatToSkScalar(w), WebCoreFloatToSkScalar(h));
1605 void GraphicsContext::scale(const FloatSize& size)
1607 if (paintingDisabled())
1610 if (size.width() == 1.0f && size.height() == 1.0f)
1613 realizeSave(SkCanvas::kMatrix_SaveFlag);
1615 m_canvas->scale(WebCoreFloatToSkScalar(size.width()), WebCoreFloatToSkScalar(size.height()));
1618 void GraphicsContext::setURLForRect(const KURL& link, const IntRect& destRect)
1620 if (paintingDisabled())
1623 SkAutoDataUnref url(SkData::NewWithCString(link.string().utf8().data()));
1624 SkAnnotateRectWithURL(m_canvas, destRect, url.get());
1627 void GraphicsContext::setURLFragmentForRect(const String& destName, const IntRect& rect)
1629 if (paintingDisabled())
1632 SkAutoDataUnref skDestName(SkData::NewWithCString(destName.utf8().data()));
1633 SkAnnotateLinkToDestination(m_canvas, rect, skDestName.get());
1636 void GraphicsContext::addURLTargetAtPoint(const String& name, const IntPoint& pos)
1638 if (paintingDisabled())
1641 SkAutoDataUnref nameData(SkData::NewWithCString(name.utf8().data()));
1642 SkAnnotateNamedDestination(m_canvas, SkPoint::Make(pos.x(), pos.y()), nameData);
1645 AffineTransform GraphicsContext::getCTM(IncludeDeviceScale) const
1647 if (paintingDisabled())
1648 return AffineTransform();
1650 SkMatrix m = getTotalMatrix();
1651 return AffineTransform(SkScalarToDouble(m.getScaleX()),
1652 SkScalarToDouble(m.getSkewY()),
1653 SkScalarToDouble(m.getSkewX()),
1654 SkScalarToDouble(m.getScaleY()),
1655 SkScalarToDouble(m.getTranslateX()),
1656 SkScalarToDouble(m.getTranslateY()));
1659 void GraphicsContext::fillRect(const FloatRect& rect, const Color& color, CompositeOperator op)
1661 if (paintingDisabled())
1664 CompositeOperator previousOperator = compositeOperation();
1665 setCompositeOperation(op);
1666 fillRect(rect, color);
1667 setCompositeOperation(previousOperator);
1670 void GraphicsContext::fillRoundedRect(const RoundedRect& rect, const Color& color)
1672 if (rect.isRounded())
1673 fillRoundedRect(rect.rect(), rect.radii().topLeft(), rect.radii().topRight(), rect.radii().bottomLeft(), rect.radii().bottomRight(), color);
1675 fillRect(rect.rect(), color);
1678 void GraphicsContext::fillRectWithRoundedHole(const IntRect& rect, const RoundedRect& roundedHoleRect, const Color& color)
1680 if (paintingDisabled())
1686 if (!roundedHoleRect.radii().isZero())
1687 path.addRoundedRect(roundedHoleRect);
1689 path.addRect(roundedHoleRect.rect());
1691 WindRule oldFillRule = fillRule();
1692 Color oldFillColor = fillColor();
1694 setFillRule(RULE_EVENODD);
1695 setFillColor(color);
1699 setFillRule(oldFillRule);
1700 setFillColor(oldFillColor);
1703 void GraphicsContext::clearRect(const FloatRect& rect)
1705 if (paintingDisabled())
1710 setupPaintForFilling(&paint);
1711 paint.setXfermodeMode(SkXfermode::kClear_Mode);
1715 void GraphicsContext::adjustLineToPixelBoundaries(FloatPoint& p1, FloatPoint& p2, float strokeWidth, StrokeStyle penStyle)
1717 // For odd widths, we add in 0.5 to the appropriate x/y so that the float arithmetic
1718 // works out. For example, with a border width of 3, WebKit will pass us (y1+y2)/2, e.g.,
1719 // (50+53)/2 = 103/2 = 51 when we want 51.5. It is always true that an even width gave
1720 // us a perfect position, but an odd width gave us a position that is off by exactly 0.5.
1721 if (penStyle == DottedStroke || penStyle == DashedStroke) {
1722 if (p1.x() == p2.x()) {
1723 p1.setY(p1.y() + strokeWidth);
1724 p2.setY(p2.y() - strokeWidth);
1726 p1.setX(p1.x() + strokeWidth);
1727 p2.setX(p2.x() - strokeWidth);
1731 if (static_cast<int>(strokeWidth) % 2) { //odd
1732 if (p1.x() == p2.x()) {
1733 // We're a vertical line. Adjust our x.
1734 p1.setX(p1.x() + 0.5f);
1735 p2.setX(p2.x() + 0.5f);
1737 // We're a horizontal line. Adjust our y.
1738 p1.setY(p1.y() + 0.5f);
1739 p2.setY(p2.y() + 0.5f);
1744 PassOwnPtr<ImageBuffer> GraphicsContext::createCompatibleBuffer(const IntSize& size, OpacityMode opacityMode) const
1746 // Make the buffer larger if the context's transform is scaling it so we need a higher
1747 // resolution than one pixel per unit. Also set up a corresponding scale factor on the
1748 // graphics context.
1750 AffineTransform transform = getCTM(DefinitelyIncludeDeviceScale);
1751 IntSize scaledSize(static_cast<int>(ceil(size.width() * transform.xScale())), static_cast<int>(ceil(size.height() * transform.yScale())));
1753 RefPtr<SkBaseDevice> device = adoptRef(m_canvas->getTopDevice()->createCompatibleDevice(SkBitmap::kARGB_8888_Config, size.width(), size.height(), opacityMode == Opaque));
1756 OwnPtr<ImageBufferSurface> surface = adoptPtr(new CompatibleImageBufferSurface(device.release(), scaledSize, opacityMode));
1757 ASSERT(surface->isValid());
1758 OwnPtr<ImageBuffer> buffer = adoptPtr(new ImageBuffer(surface.release()));
1760 buffer->context()->scale(FloatSize(static_cast<float>(scaledSize.width()) / size.width(),
1761 static_cast<float>(scaledSize.height()) / size.height()));
1763 return buffer.release();
1766 void GraphicsContext::addCornerArc(SkPath* path, const SkRect& rect, const IntSize& size, int startAngle)
1769 int rx = SkMin32(SkScalarRoundToInt(rect.width()), size.width());
1770 int ry = SkMin32(SkScalarRoundToInt(rect.height()), size.height());
1772 ir.set(-rx, -ry, rx, ry);
1773 switch (startAngle) {
1775 ir.offset(rect.fRight - ir.fRight, rect.fBottom - ir.fBottom);
1778 ir.offset(rect.fLeft - ir.fLeft, rect.fBottom - ir.fBottom);
1781 ir.offset(rect.fLeft - ir.fLeft, rect.fTop - ir.fTop);
1784 ir.offset(rect.fRight - ir.fRight, rect.fTop - ir.fTop);
1792 path->arcTo(r, SkIntToScalar(startAngle), SkIntToScalar(90), false);
1795 void GraphicsContext::setPathFromConvexPoints(SkPath* path, size_t numPoints, const FloatPoint* points)
1797 path->incReserve(numPoints);
1798 path->moveTo(WebCoreFloatToSkScalar(points[0].x()),
1799 WebCoreFloatToSkScalar(points[0].y()));
1800 for (size_t i = 1; i < numPoints; ++i) {
1801 path->lineTo(WebCoreFloatToSkScalar(points[i].x()),
1802 WebCoreFloatToSkScalar(points[i].y()));
1805 /* The code used to just blindly call this
1806 path->setIsConvex(true);
1807 But webkit can sometimes send us non-convex 4-point values, so we mark the path's
1808 convexity as unknown, so it will get computed by skia at draw time.
1809 See crbug.com 108605
1811 SkPath::Convexity convexity = SkPath::kConvex_Convexity;
1813 convexity = SkPath::kUnknown_Convexity;
1814 path->setConvexity(convexity);
1817 void GraphicsContext::setupPaintCommon(SkPaint* paint) const
1819 #if defined(SK_DEBUG)
1821 SkPaint defaultPaint;
1822 SkASSERT(*paint == defaultPaint);
1826 paint->setAntiAlias(m_state->m_shouldAntialias);
1828 if (!SkXfermode::IsMode(m_state->m_xferMode.get(), SkXfermode::kSrcOver_Mode))
1829 paint->setXfermode(m_state->m_xferMode.get());
1831 if (m_state->m_looper)
1832 paint->setLooper(m_state->m_looper.get());
1834 paint->setColorFilter(m_state->m_colorFilter.get());
1837 void GraphicsContext::drawOuterPath(const SkPath& path, SkPaint& paint, int width)
1841 paint.setStrokeWidth(width);
1842 paint.setPathEffect(new SkCornerPathEffect((width - 1) * 0.5f))->unref();
1844 paint.setStrokeWidth(1);
1845 paint.setPathEffect(new SkCornerPathEffect(1))->unref();
1847 drawPath(path, paint);
1850 void GraphicsContext::drawInnerPath(const SkPath& path, SkPaint& paint, int width)
1853 paint.setAlpha(128);
1854 paint.setStrokeWidth(width * 0.5f);
1855 drawPath(path, paint);
1859 void GraphicsContext::setRadii(SkVector* radii, IntSize topLeft, IntSize topRight, IntSize bottomRight, IntSize bottomLeft)
1861 radii[SkRRect::kUpperLeft_Corner].set(SkIntToScalar(topLeft.width()),
1862 SkIntToScalar(topLeft.height()));
1863 radii[SkRRect::kUpperRight_Corner].set(SkIntToScalar(topRight.width()),
1864 SkIntToScalar(topRight.height()));
1865 radii[SkRRect::kLowerRight_Corner].set(SkIntToScalar(bottomRight.width()),
1866 SkIntToScalar(bottomRight.height()));
1867 radii[SkRRect::kLowerLeft_Corner].set(SkIntToScalar(bottomLeft.width()),
1868 SkIntToScalar(bottomLeft.height()));
1871 PassRefPtr<SkColorFilter> GraphicsContext::WebCoreColorFilterToSkiaColorFilter(ColorFilter colorFilter)
1873 switch (colorFilter) {
1874 case ColorFilterLuminanceToAlpha:
1875 return adoptRef(SkLumaColorFilter::Create());
1876 case ColorFilterLinearRGBToSRGB:
1877 return ImageBuffer::createColorSpaceFilter(ColorSpaceLinearRGB, ColorSpaceDeviceRGB);
1878 case ColorFilterSRGBToLinearRGB:
1879 return ImageBuffer::createColorSpaceFilter(ColorSpaceDeviceRGB, ColorSpaceLinearRGB);
1880 case ColorFilterNone:
1883 ASSERT_NOT_REACHED();
1891 CGColorSpaceRef PLATFORM_EXPORT deviceRGBColorSpaceRef()
1893 static CGColorSpaceRef deviceSpace = CGColorSpaceCreateDeviceRGB();
1897 void GraphicsContext::draw2xMarker(SkBitmap* bitmap, int index)
1899 const SkPMColor lineColor = lineColors(index);
1900 const SkPMColor antiColor1 = antiColors1(index);
1901 const SkPMColor antiColor2 = antiColors2(index);
1903 uint32_t* row1 = bitmap->getAddr32(0, 0);
1904 uint32_t* row2 = bitmap->getAddr32(0, 1);
1905 uint32_t* row3 = bitmap->getAddr32(0, 2);
1906 uint32_t* row4 = bitmap->getAddr32(0, 3);
1908 // Pattern: X0o o0X0o o0
1912 const SkPMColor row1Color[] = { lineColor, antiColor1, antiColor2, 0, 0, 0, antiColor2, antiColor1 };
1913 const SkPMColor row2Color[] = { lineColor, lineColor, antiColor1, antiColor2, 0, antiColor2, antiColor1, lineColor };
1914 const SkPMColor row3Color[] = { 0, antiColor2, antiColor1, lineColor, lineColor, lineColor, antiColor1, antiColor2 };
1915 const SkPMColor row4Color[] = { 0, 0, antiColor2, antiColor1, lineColor, antiColor1, antiColor2, 0 };
1917 for (int x = 0; x < bitmap->width() + 8; x += 8) {
1918 int count = std::min(bitmap->width() - x, 8);
1920 memcpy(row1 + x, row1Color, count * sizeof(SkPMColor));
1921 memcpy(row2 + x, row2Color, count * sizeof(SkPMColor));
1922 memcpy(row3 + x, row3Color, count * sizeof(SkPMColor));
1923 memcpy(row4 + x, row4Color, count * sizeof(SkPMColor));
1928 void GraphicsContext::draw1xMarker(SkBitmap* bitmap, int index)
1930 const uint32_t lineColor = lineColors(index);
1931 const uint32_t antiColor = antiColors2(index);
1933 // Pattern: X o o X o o X
1935 uint32_t* row1 = bitmap->getAddr32(0, 0);
1936 uint32_t* row2 = bitmap->getAddr32(0, 1);
1937 for (int x = 0; x < bitmap->width(); x++) {
1940 row1[x] = lineColor;
1943 row1[x] = antiColor;
1944 row2[x] = antiColor;
1947 row2[x] = lineColor;
1950 row1[x] = antiColor;
1951 row2[x] = antiColor;
1957 const SkPMColor GraphicsContext::lineColors(int index)
1959 static const SkPMColor colors[] = {
1960 SkPreMultiplyARGB(0xFF, 0xFF, 0x00, 0x00), // Opaque red.
1961 SkPreMultiplyARGB(0xFF, 0xC0, 0xC0, 0xC0) // Opaque gray.
1964 return colors[index];
1967 const SkPMColor GraphicsContext::antiColors1(int index)
1969 static const SkPMColor colors[] = {
1970 SkPreMultiplyARGB(0xB0, 0xFF, 0x00, 0x00), // Semitransparent red.
1971 SkPreMultiplyARGB(0xB0, 0xC0, 0xC0, 0xC0) // Semitransparent gray.
1974 return colors[index];
1977 const SkPMColor GraphicsContext::antiColors2(int index)
1979 static const SkPMColor colors[] = {
1980 SkPreMultiplyARGB(0x60, 0xFF, 0x00, 0x00), // More transparent red
1981 SkPreMultiplyARGB(0x60, 0xC0, 0xC0, 0xC0) // More transparent gray
1984 return colors[index];
1988 void GraphicsContext::setupShader(SkPaint* paint, Gradient* grad, Pattern* pat, SkColor color) const
1990 RefPtr<SkShader> shader;
1993 shader = grad->shader();
1994 color = SK_ColorBLACK;
1996 shader = pat->shader();
1997 color = SK_ColorBLACK;
1998 paint->setFilterBitmap(imageInterpolationQuality() != InterpolationNone);
2001 paint->setColor(m_state->applyAlpha(color));
2006 paint->setShader(shader.get());
2009 void GraphicsContext::didDrawTextInRect(const SkRect& textRect)
2011 if (m_trackTextRegion) {
2012 TRACE_EVENT0("skia", "PlatformContextSkia::trackTextRegion");
2013 m_textRegion.join(textRect);